【发布时间】:2018-09-06 23:24:42
【问题描述】:
我正在尝试在 PyTorch 中手动实现梯度下降作为学习练习。我有以下内容来创建我的合成数据集:
import torch
torch.manual_seed(0)
N = 100
x = torch.rand(N,1)*5
# Let the following command be the true function
y = 2.3 + 5.1*x
# Get some noisy observations
y_obs = y + 2*torch.randn(N,1)
然后我创建我的预测函数 (y_pred),如下所示。
w = torch.randn(1, requires_grad=True)
b = torch.randn(1, requires_grad=True)
y_pred = w*x+b
mse = torch.mean((y_pred-y_obs)**2)
它使用 MSE 来推断权重 w,b。我使用下面的块根据渐变更新值。
gamma = 1e-2
for i in range(100):
w = w - gamma *w.grad
b = b - gamma *b.grad
mse.backward()
但是,循环仅在第一次迭代中有效。 从w.grad 开始的第二次迭代设置为None。我很确定发生这种情况的原因是因为我将 w 设置为它自身的函数(我可能错了)。
问题是如何使用梯度信息正确更新权重?
【问题讨论】: