数组x,基于表达式: 加上一些噪声数据得到y
然后学习表达式 中的w与b 两个参数,这里采用梯度下降法。
"""
使用Antograd包,以及对应的Tensor,来实现反向传播来求梯度
以下是具体实现的代码
"""
import torch
import torch as t
from matplotlib import pyplot as plt
t.manual_seed(100)
dtype = t.float
# 生成x坐标数据,x为tensor,需要把x的形状转换为100*1
x = t.unsqueeze(torch.linspace(-1, 1, 100), dim=1)
# 生成y坐标数据,y为tensor,形状为100*1,另外加上一些噪声
y = 3 * x.pow(2) + 2 + 0.2 * torch.rand(x.size())
# 画图
plt.scatter(x.numpy(), y.numpy())
plt.show()
# 初始化权重参数 w b 为需要学习的,故需requires_grad = Ture
w = t.randn(1, 1, dtype=dtype, requires_grad=True)
b = t.zeros(1, 1, dtype=dtype, requires_grad=True)
# 训练模型
lr = 0.001
for ii in range(800):
# 前向传播
y_pred = x.pow(2).mm(w) + b
loss = 0.5 * (y_pred - y) ** 2
loss = loss.sum()
# 自动计算梯度,梯度存放在grad属性中
loss.backward()
# 手动更新参数,需要用torch.no_grad(),使得上下文环境中切断自动求导的计算
with t.no_grad():
w -= lr * w.grad
b -= lr * w.grad
# 梯度清零
w.grad.zero_()
b.grad.zero_()
# 可视化训练结果
plt.plot(x.numpy(), y_pred.detach().numpy(), 'r-', label='predict') # predict
plt.scatter(x.numpy(), y.numpy(), color='blue', marker='o', label='ture') # ture data
plt.xlim(-1, 1)
plt.ylim(2, 6)
plt.legend()
plt.show()
print('w=',w,'b=',b)
数据分布图:
拟合效果图: