pytorch - 使用 torch.autograd.grad (PyTorch) 计算矩阵导数
问题描述
我正在尝试使用 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 但渐变返回为无。我不确定是什么导致图表在这里断开连接。
解决方案
仅当使用 pytorch 函数时才会创建 Pytorch autograd 图。
我认为创建时使用的 python 2d 列表rot_mat
断开了图形的连接。所以使用火炬函数创建旋转矩阵,也只使用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)
推荐阅读
- pandas - Axis 必须设置 `freq` 才能转换为 Periods pandas
- c# - 是否可以将 RenderTargetBitmap.RenderAsync 与用户不可见的 Grid 一起使用?
- visual-studio-code - 调用 Azure ML Endpoint、命名空间操作方法的 Visual Studio 项目
- php - Magento 2 rest API:按名称过滤类别
- javascript - 使用 shopify-api-node 访问 Shopify 产品时遇到问题
- react-native - @react-native-async-storage/async-storage getItem 的值为 false
- node.js - 使用 MongoDb 和 Node.Js 从对象引用数组中获取整个文档
- java - Java Swing 在 HTMLEditorKit.HTMLTextAction 中使用 .getElementsAt 来获取包含选择的元素列表
- outlook - Outlook 加载项中的 REST 请求和响应是否有通信限制?
- javascript - 反应输入字段验证 - 通过按回车避免请求;测试失败