【问题标题】:Why do we need to pass the gradient parameter to the backward function in PyTorch?为什么我们需要将梯度参数传递给 PyTorch 中的后向函数?
【发布时间】:2021-06-22 22:31:24
【问题描述】:

根据文档,如果张量是非标量(即其数据具有多个元素)并且需要梯度,则当我们调用张量的后向函数时,该函数还需要指定 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.]))

除了缩放 grad 值之外,当我们有一个非标量张量时,传递给后向函数的 gradient 参数如何帮助计算导数?
为什么 PyTorch 不能在不询问显式的情况下隐式计算导数和标量张量一样的梯度参数?

【问题讨论】:

    标签: pytorch


    【解决方案1】:

    这是因为 PyTorch 正在计算雅可比积。对于标量值,不带参数的.backward() 等价于.backward(torch.tensor(1.0))。

    这就是为什么您需要提供要计算乘积的张量。阅读有关automatic differentiation 的更多信息。

    【讨论】:

      猜你喜欢
      • 2011-03-14
      • 1970-01-01
      • 2017-09-13
      • 2018-01-08
      • 2012-07-06
      • 2021-10-09
      • 1970-01-01
      • 2021-05-23
      • 1970-01-01
      相关资源
      最近更新 更多