根据文档,如果张量是非标量(即其数据有多个元素)并且需要梯度,当我们调用张量的后向函数时,该函数还需要指定 gradient。
import torch
a = torch.tensor([10.,10.],requires_grad=True)
b = torch.tensor([20.,20.],requires_grad=True)
F = a * b
F.backward(gradient=torch.tensor([1.,1.]))
print(a.grad)
Output: tensor([20., 20.])
现在缩放外部渐变:
a = torch.tensor([10.,10.],requires_grad=True)
b = torch.tensor([20.,20.],requires_grad=True)
F = a * b
F.backward(gradient=torch.tensor([2.,2.])) #modified
print(a.grad)
Output: tensor([40., 40.])
因此,将 gradient 参数传递给向后似乎可以缩放渐变。
此外,默认情况下
F.backward()
是 F.backward(gradient=torch.Tensor([1.]))
除了缩放梯度值之外,当我们有非标量张量时,传递给后向函数的
gradient
参数如何帮助计算导数?这是因为 PyTorch 正在计算雅可比积。对于标量值,
.backward()
w/o 参数相当于 .backward(torch.tensor(1.0))
。
这就是为什么您需要提供要用来计算乘积的张量。了解有关自动微分的更多信息。
gradient
参数中的值预计是最终损失相对于当前张量的导数。
这篇文章很好地解释了这个想法:https://stackoverflow.com/a/47026836/1500108。