使用PyTorch预测房价
代码
import torch
import matplotlib.pyplot as plt
import numpy as np
# 准备数据
x = torch.linspace(0, 100, steps=100).type(torch.FloatTensor)
rand = torch.randn(100) * 10
y = x + rand
x_train = x[:-10]
x_test = x[-10:]
y_train = y[:-10]
y_test = y[-10:]
plt.figure(figsize=(10, 8))
plt.plot(x_train.data.numpy(), y_train.data.numpy(), 'o')
plt.xlabel('X')
plt.ylabel('Y')
plt.show()
# 训练
a = torch.rand(1, requires_grad=True)
b = torch.rand(1, requires_grad=True)
learning_rate = 0.0001
for i in range(1000):
preditions = a.expand_as(x_train) * x_train + b.expand_as(x_train)
loss = torch.mean((preditions - y_train)**2)
print("loss:", loss)
loss.backward()
a.data.add_(-learning_rate*a.grad.data)
b.data.add_(-learning_rate*b.grad.data)
a.grad.data.zero_()
b.grad.data.zero_()
x_data = x_train.data.numpy()
plt.figure(figsize=(10, 7))
xplot, = plt.plot(x_data, y_train.data.numpy(), 'o')
yplot, = plt.plot(x_data, a.data.numpy() * x_data + b.data.numpy())
plt.xlabel('X')
plt.ylabel('Y')
str1 = str(a.data.numpy()[0]) + 'x + ' + str(b.data.numpy()[0])
plt.legend([xplot, yplot], ['Data', str1])
plt.show()
preditions = a.expand_as(x_test) * x_test + b.expand_as(x_test)
print(preditions)
# 预测
x_data = x_train.data.numpy()
x_pred = x_test.data.numpy()
plt.figure(figsize=(10, 7))
plt.plot(x_data, y_train.data.numpy(), 'o')
plt.plot(x_pred, y_test.data.numpy(), 's')
x_data = np.r_[x_data, x_test.data.numpy()]
plt.plot(x_data, a.data.numpy() * x_data + b.data.numpy())
plt.plot(x_pred, a.data.numpy() * x_pred + b.data.numpy(), 'o')
plt.xlabel('X')
plt.ylabel('Y')
str1 = str(a.data.numpy()[0]) + 'x + ' + str(b.data.numpy()[0])
plt.legend([xplot, yplot], ['Data', str1])
plt.show()
执行结果



最后更新于1年前
本文由人工编写,AI优化,转载请注明原文地址: 使用PyTorch预测房价
推荐阅读
VMware Workstation 17许可证密钥及免费激活方法详解
25972025-10-26
VMware Workstation 16激活码及许可证密钥获取方法
20752025-10-26
天融信VPN客户端详解:VONE与安全接入的区别、下载与使用指南
11752025-12-03
OpenVPN安装配置完整指南:从零搭建安全VPN服务器与客户端
17042025-10-30
Windows系统PyTorch安装教程:CUDA 12.1环境配置与TorchText版本兼容性指南
22612025-10-08
Kaggle Notebook性能实测:免费GPU主机配置与运行时间分析
7202025-11-23
评论 (0)
发表评论
昵称:加载中...
暂无评论,快来发表第一条评论吧!