再会!
我正在尝试掌握 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
这给出了预期的结果 (2., 2., 1.)。我想我以错误的方式定义了张量 y 。如果我只是简单地做 y = x * 2,那么梯度会起作用,但是在这种情况下如何创建更复杂的张量呢?谢谢你。
最佳答案
您不应该通过 torch.tensor()
定义张量 y , torch.tensor()
是张量构造函数,而不是运算符,因此在操作图中无法跟踪。您应该使用 torch.stack()
反而。
只需将该行更改为:
y = torch.stack((x[0]**2+x[1], x[1]**2+x[2], x[2]**2))
x.grad
的结果应该是 tensor([ 6., 13., 19.])
关于python - pytorch:计算向量函数的向量雅可比积,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64260561/