如何将带有梯度的 Torch 张量列表转换为张量

How to convert a list of Torch tensor with grad to tensor

我有一个名为 pts 的变量,其形状为 [batch, ch, h, w]。这是一个热图,我想将其转换为第二坐标。目标是 pts_o = heatmap_to_pts(pts),其中 pts_o 将是 [batch, ch, 2]。到目前为止我已经写了这个功能,

def heatmap_to_pts(self, pts):  <- pts [batch, 68, 128, 128]
    
    pt_num = []
    
    for i in range(len(pts)):
        
        pt = pts[i]
        if type(pt) == torch.Tensor:

            d = torch.tensor(128)                                                   * get the   
            m = pt.view(68, -1).argmax(1)                                           * indices
            indices = torch.cat(((m / d).view(-1, 1), (m % d).view(-1, 1)), dim=1)  * from heatmaps
        
            pt_num.append(indices.type(torch.DoubleTensor) )   <- store the indices in a list

    b = torch.Tensor(68, 2)                   * trying to convert
    c = torch.cat(pt_num, out=b) *error*      * a list of tensors with grad
    c = c.reshape(68,2)                       * to a tensor like [batch, 68, 2]

    return c

错误显示“cat():具有 out=... 参数的函数不支持自动微分,但其中一个参数需要梯度。”。它无法执行操作,因为 pt_num 中的张量需要梯度。

如何将该列表转换为张量?

错误说,

cat(): functions with out=... arguments don't support automatic differentiation, but one of the arguments requires grad.

这意味着 torch.cat() 等函数的输出作为 out= kwarg 不能用作 autograd 引擎(执行自动微分)的输入。

原因是张量(在您的 Python 列表 pt_num 中)具有不同的 requires_grad 属性值,即一些张量具有 requires_grad=True 而一些其中 requires_grad=False.

在您的代码中,以下行(逻辑上)很麻烦:

c = torch.cat(pt_num, out=b) 

无论您是否使用 out= kwarg,torch.cat() 的 return 值都是张量沿上述维度的串联。

因此,张量 c 已经是 pt_num 中各个张量的串联版本。使用 out=b 多余。因此,您可以简单地摆脱 out=b,一切都应该没问题。

c = torch.cat(pt_num)