torch.Tensor.backward() 如何工作?

CSH*_*CSH 9 gradient torch pytorch

最近在研究Pytorch和backward函数的封装。我明白如何使用它,但是当我尝试时

x = Variable(2*torch.ones(2, 2), requires_grad=True)
x.backward(x)
print(x.grad)
Run Code Online (Sandbox Code Playgroud)

我预计

tensor([[1., 1.],
        [1., 1.]])
Run Code Online (Sandbox Code Playgroud)

因为它是恒等函数。然而,它返回

tensor([[2., 2.],
        [2., 2.]]).
Run Code Online (Sandbox Code Playgroud)

为什么会出现这种情况?

Anu*_*ngh 1

实际上,这就是您正在寻找的:

情况 1:当 z = 2*x**3 + x 时

import torch
from torch.autograd import Variable
x = Variable(2*torch.ones(2, 2), requires_grad=True)
z = x*x*x*2+x
z.backward(torch.ones_like(z))
print(x.grad)
Run Code Online (Sandbox Code Playgroud)

输出:

tensor([[25., 25.],
        [25., 25.]])
Run Code Online (Sandbox Code Playgroud)

情况2:当z = x*x时

x = Variable(2*torch.ones(2, 2), requires_grad=True)
z = x*x
z.backward(torch.ones_like(z))
print(x.grad)
Run Code Online (Sandbox Code Playgroud)

输出:

tensor([[4., 4.],
        [4., 4.]])
Run Code Online (Sandbox Code Playgroud)

情况 3:当 z = x (您的情况)

x = Variable(2*torch.ones(2, 2), requires_grad=True)
z = x
z.backward(torch.ones_like(z))
print(x.grad)
Run Code Online (Sandbox Code Playgroud)

输出:

tensor([[1., 1.],
        [1., 1.]])
Run Code Online (Sandbox Code Playgroud)

要了解如何在 pytorch 中计算梯度的更多信息,请检查