我正试图全面理解PyTorch的自动求导(autograd),在这个过程中我遇到了以下问题:假设函数f(x)=x,根据基础数学知识,我们知道f'(x)=1,但是当我在PyTorch中运用该函数时,得到的结果却是f'(x) = x。
z = torch.linspace(-1, 1, steps=5, requires_grad=True)
y = z
y.backward(z)
print("Z tensor is: {} \n Gradient of y with respect to z is: {}".format(z, z.grad))
我希望得到一个大小为5的张量,其中所有元素都是1,但实际上我得到了:
Z tensor is: tensor([-1.0000, -0.5000, 0.0000, 0.5000, 1.0000], requires_grad=True)
Gradient of y with respect to z is: tensor([-1.0000, -0.5000, 0.0000, 0.5000, 1.0000])
为什么PyTorch表现出这种行为?