import torch
import matplotlib.pyplot as plt
torch.manual_seed(10)
# 随机构建训练样本x,y
x = torch.rand (20,1) * 10
y = 2 * x + (5 + torch.randn(20,1))
# 构建线性回归函数的参数
w = torch.randn((1),requires_grad = True)
b = torch.zeros((1),requires_grad = True)
lr = 0.05 # 学习率
for iteration in range(100):
# 前向传播
wx = torch.mul(w,x)
y_pred = torch.add(wx,b)
# 计算loss
loss = (0.5 * (y - y_pred)**2).mean()
# 反向传播
loss.backward()
# 更新参数
b.data.sub_(lr * b.grad) # 这种_的加法操作时从自身减,相当于-=
w.data.sub_(lr * w.grad)
# 张量的梯度清零
w.grad.data.zero_()
b.grad.data.zero_()
if iteration % 20 == 0:
# 原始数据在坐标轴里的点
plt.scatter(x.data.numpy(), y.data.numpy())
# 预测数据的线性变化,线的颜色是红色,宽度是5
plt.plot(x.data.numpy(), y_pred.data.numpy(), 'r-', lw = 5)
# 画的坐标图中的文字内容
plt.text(2, 20, 'Loss=%.4f'%loss.data.numpy(), fontdict = {'size': 20, 'color': 'red'})
# x,y轴的大小长度
plt.xlim(1.5, 10)
plt.ylim(8, 28)
# 图标的标题
plt.title('Iteration:{}\nw:{}\nb:{}'.format(iteration, w.data.numpy(), b.data.numpy()))
plt.pause(0.5) # 暂停一段时间,不然画的太快会卡住显示不出来
if loss.data.numpy() < 1:
break