我们自定义数据,使用torch实现线性回归。
假设我们的基础模型是y=wb+c,其中,w,b均为参数;我们是用y=3x+0.8
来构造数据x,y;所以最后求出的w,b应该接近3,0.8.
1.准备数据
2.计算预测值
3.计算损失,把参数梯度设置为0,进行反向传播。
4.更新参数
import torch
import matplotlib.pyplot as plt
learing_rate=0.01
#1.准备数据
#y=3x+0.8
x=torch.rand([500,1])#准备500个0~1之间的数据
y_true=x*3+0.8
#2.通过模型计算y_predict
w=torch.rand([1,1],requires_grad=True)
b=torch.tensor(0,requires_grad=True,dtype=torch.float32)
#
#4.通过循环,反向传播,更新参数
for i in range(2000):
# 3. 计算Loss
y_predict = torch.matmul(x, w) + b # 矩阵相乘
loss = (y_true - y_predict).pow(2).mean() # 均方误差
if w.grad is not None:
w.grad.data.zero_()
if b.grad is not None:
b.grad.data.zero_()
loss.backward() #反向传播
w.data=w.data-learing_rate* w.grad #更新w,b
b.data=b.data-learing_rate* b.grad
if i%50==0:
print("w,b,loss",w.item(),b.item(),loss.item())
#画图
plt.figure(figsize=(20,8))
plt.scatter(x.numpy().reshape(-1),y_true.numpy().reshape(-1))
y_predict = torch.matmul(x, w) + b
plt.plot(x.numpy().reshape(-1),y_predict.detach().numpy().reshape(-1))
plt.show()