为什么 torch.autograd 在这种情况下不计算梯度?

Why doesn't torch.autograd compute the gradient in this case?

为什么 torch.autograd 在这种情况下不计算梯度?

import torch
x = torch.tensor([1., 2., ], requires_grad=True)
y = torch.tensor([x[0] + x[1], x[1] - x[0], ], requires_grad=True)
z = y[0] + y[1]
z.backward()
x.grad

输出是一个空行 (None)。 x[0].grad 也是如此。为什么?

PS:回想起来,我意识到让 y 成为带有 requires_grad 的张量的动机是为了检查它自己的梯度。我了解到必须在这里使用 retain_grad

当你对y使用torch.tensor时,它只是使用x的值来初始化张量,梯度链丢失了。

这个有效:

x = torch.tensor([1., 2., ], requires_grad=True)
y = [x[0] + x[1], x[1] - x[0], ]
z = y[0] + y[1]
z.backward()
x.grad

结果是tensor([0., 2.])