pytorch - 使用 torch.autograd.grad 计算矩阵导数 (PyTorch)

标签 pytorch autograd

我正在尝试使用 torch.autograd.grad 在 PyTorch 中计算矩阵导数,但是我遇到了一些问题。这是重现错误的最小工作示例。

theta = torch.tensor(np.random.uniform(low=-np.pi, high=np.pi), requires_grad=True)
rot_mat = torch.tensor([[torch.cos(theta), torch.sin(theta), 0], 
                        [-torch.sin(theta), torch.cos(theta), 0]], 
                        dtype=torch.float, requires_grad=True)
torch.autograd.grad(outputs=rot_mat, 
                    inputs=theta, grad_outputs=torch.ones_like(rot_mat), 
                    create_graph=True, retain_graph=True)

此代码会导致错误“图中似乎未使用一个微分张量。如果这是所需的行为,请设置allow_unused=True。”

我尝试使用allow_unused=True,但梯度返回为None。我不确定是什么导致图表在这里断开连接。

最佳答案

仅当使用 pytorch 函数时才会创建 Pytorch autograd 图。

我认为创建 rot_mat 时使用了 python 2d 列表断开图表。因此,使用 torch 函数创建旋转矩阵并且也只需使用 backward()计算梯度的函数。这是示例代码:

import torch
import numpy as np

theta   = torch.tensor(np.random.uniform(low=-np.pi, high=np.pi), requires_grad=True)

# create required values and convert it to torch 1d tensor
cos_t   = torch.cos(theta).view(1)
sin_t   = torch.sin(theta).view(1)
msin_t  = -sin_t
zero    = torch.zeros(1)

# create rotation matrix using only pytorch functions
rot_1d  = torch.cat((cos_t, sin_t, zero, msin_t, cos_t, zero))
rot_mat = rot_1d.view((2, 3)) 

# Autograd
rot_mat.backward(torch.ones_like(rot_mat))

# gradient
print(theta.grad)

关于pytorch - 使用 torch.autograd.grad 计算矩阵导数 (PyTorch),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63437478/

相关文章:

python - 如何计算损失 w.r.t. 的 Hessian PyTorch 中使用 autograd.grad 的参数

python - Pytorch 简单模型没有改进

python - Numpy/PyTorch - 如何用不同维度的索引分配值?

tensorflow - 用于降维的二进制一热编码

Pytorch autograd : Make gradient of a parameter a function of another parameter

python - 使用 Autograd 的偏导数

tensorflow - Adam优化器中的epsilon参数

tensorflow - pytorch 中的 tf.function 属性

Pytorch 的 autograd 问题与 joblib

python - JAX 中的条件更新?