【发布时间】:2022-01-25 17:28:26
【问题描述】:
今天偶然发现了一个torch行为,w = w - dw不严格等于w -= dw,下面附上简单的例子:
x_input_, y_gt_ = datasets.make_regression(n_samples=100, n_features=1)
# Model
x_input = torch.from_numpy(x_input_)
w = torch.tensor(1, requires_grad=True, dtype=torch.float32)
x_input = torch.from_numpy(x_input_)
y_gt = torch.unsqueeze(torch.from_numpy(y_gt_), dim=1)
lr = 0.01
for iter in range(3):
y_pred = w * x_input
loss = ((y_gt - y_pred) ** 2).mean()
loss.backward()
with torch.no_grad():
dw = w.grad * lr
print(w)
w -= dw
print(w)
哪个输出(预期)
tensor(1., requires_grad=True)
tensor(1.0413, requires_grad=True)
tensor(1.0413, requires_grad=True)
tensor(1.1230, requires_grad=True)
tensor(1.1230, requires_grad=True)
tensor(1.2431, requires_grad=True)
但是,如果我将 w -= dw 替换为 w = w - dw,则会说不再附加渐变
tensor(1., requires_grad=True)
tensor(3.1186)
我很好奇这可能是什么原因造成的?
【问题讨论】:
-
-=更新现有对象,而=将其替换为新对象。