python - pytorch:计算向量函数的向量雅可比积

标签 python pytorch

再会!
我正在尝试掌握 torch.autograd 的基础知识。我特别想测试来自 https://pytorch.org/tutorials/beginner/blitz/autograd_tutorial.html#sphx-glr-beginner-blitz-autograd-tutorial-py 的这个声明

enter image description here

所以我的想法是构造一个向量函数,比如:
(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/

相关文章:

Pytorch:训练期间的中间测试

python - 用 U2Net 去除背景太强了

python - 在非常大的文件中引用 CSV 记录

python - 如何对一个数进行立方

python - 导入随机 - python 中的 randint 不起作用

javascript - 外部键值对的 JSON 转换

python - 为什么在 python 中这样调用列表理解?

python - Pytorch inceptionV3 迁移学习给出错误 - max() 收到无效的参数组合

boolean - PyTorch 使用 boolean 掩码提取张量元素(保留维度)

python - 使用 pytorch/python,覆盖变量还是定义新变量更好?