【问题标题】:Computing matrix derivatives with torch.autograd.grad (PyTorch)使用 torch.autograd.grad (PyTorch) 计算矩阵导数
【发布时间】:2023-03-18 11:06:01
【问题描述】:

我正在尝试使用 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 autograd


    【解决方案1】:

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

    我认为创建rot_mat 时使用的python 2d 列表断开了图形的连接。所以使用火炬函数创建旋转矩阵,也只需使用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)
    

    【讨论】:

      猜你喜欢
      • 2023-01-24
      • 2020-06-02
      • 1970-01-01
      • 2021-01-17
      • 2023-02-18
      • 2019-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多