再会!
我正在尝试掌握 torch.autograd 基础知识。特别是我想从https://pytorch.org/tutorials/beginner/blitz/autograd_tutorial.html#sphx-glr-beginner-blitz-autograd-tutorial-py测试这个声明
所以我的想法是构造一个向量函数,比如:
(y_1; y_2; y_3) = (x_1*x_1 + x_2; x_2 * x_2 + x_3; x_3 * x_3)
然后计算点 (1,1,1) 处的雅可比矩阵,并将其乘以向量 (3,5,7)。
雅可比行列式 = (2x_1; 1.; 0.) (0.; 2x_2; 1.) (0.; 0.; 2x_3)
我期待结果 Jacobian(x=(1,1,1)) * v = (6+5, 10 + 7, 2 * 7) = (11, 17, 14)。
下面是我在 pytorch 中的尝试:
import torch
x = torch.ones(3, requires_grad=True)
print(x)
y = torch.tensor([x[0]**2 + x [1], x[1]**2 + x[2], x[2]**2], requires_grad=True)
print(y)
v = torch.tensor([3, 5, 7])
y.backward(v)
x.grad
Run Code Online (Sandbox Code Playgroud)
这给出了预期的结果 (2., 2., 1.)。我认为我以错误的方式定义张量 y 。如果我简单地执行 y = x * 2,那么梯度就会起作用,但是像本例中那样创建更复杂的张量怎么样?
谢谢。
小智 5
您不应该通过 来定义张量 y torch.tensor()
,torch.tensor()
是张量构造函数,而不是运算符,因此它在操作图中不可跟踪。你应该改用torch.stack()
。
只需将该行更改为:
y = torch.stack((x[0]**2+x[1], x[1]**2+x[2], x[2]**2))
Run Code Online (Sandbox Code Playgroud)
的结果x.grad
应该是tensor([ 6., 13., 19.])