我今天偶然发现了一种火炬行为,即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)我很好奇是什么导致了这一切?
发布于 2021-12-26 02:08:07
表达式w -= dw在w上调用一个特殊函数,允许它修改自己。
表达式w - dw创建一个新对象,而w =将该新对象分配给旧对象而不是旧对象。
https://stackoverflow.com/questions/70483784
复制相似问题