我刚刚安装火炬-1.0.0 on Python 3.7.2(macOS),并尝试tutorial https://pytorch.org/tutorials/beginner/blitz/autograd_tutorial.html#sphx-glr-beginner-blitz-autograd-tutorial-py,但是下面的代码:
import torch
x = torch.ones(2, 2, requires_grad=True)
y = x + 2
z = y * y * 3
out = z.mean()
out.backward()
print(out.grad)
prints None
这不是我们所期望的。
有什么问题?
这是预期的结果。
.backward
仅在叶节点中累积梯度。out
不是叶节点,因此 grad 为 None。
autograd.backward
也做同样的事情
autograd.grad
可用于查找任何张量相对于任何张量的梯度。所以如果你这样做autograd.grad (out, out)
你得到(tensor(1.),)
作为预期的输出。
Ref:
- 张量.向后 (https://pytorch.org/docs/stable/autograd.html#torch.Tensor.backward https://pytorch.org/docs/stable/autograd.html#torch.Tensor.backward)
- autograd.向后(https://pytorch.org/docs/stable/autograd.html#torch.autograd.backward https://pytorch.org/docs/stable/autograd.html#torch.autograd.backward)
- autograd.grad (https://pytorch.org/docs/stable/autograd.html#torch.autograd.grad https://pytorch.org/docs/stable/autograd.html#torch.autograd.grad)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)