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

使用torch.autograd.grad(PyTorch)计算矩阵导数,pytorch,autograd,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.

我正在尝试使用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。我不确定是什么原因导致图形在此断开连接。

Pytork autograd graph仅在使用Pytork函数时才会创建。 我认为在创建
rot\u 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)