Python 为什么';t torch.autograd在这种情况下计算梯度?

Python 为什么';t torch.autograd在这种情况下计算梯度?,python,pytorch,gradient,backpropagation,autograd,Python,Pytorch,Gradient,Backpropagation,Autograd,在这种情况下,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 输出为空行(无)。对于x[0]。grad,也会发生同样的情况。为什么? PS:回想起来,我意识到用requi

在这种情况下,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
输出为空行(无)。对于
x[0]。grad
,也会发生同样的情况。为什么?


PS:回想起来,我意识到用
requires\u grad
制作
y
张量的动机是为了检查它自己的梯度。我学会了在这里必须使用
retain_grad
:当你使用
torch.tensor
表示
y
时,它只使用
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

结果是张量([0,2.])

谢谢。现在回想起来,我意识到把y变成一个带有requires_grad的张量的动机是为了检查它自己的梯度。我学到了在这里必须使用retain_grad: