1

我有一个名为 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=... 参数的函数不支持自动微分,但其中一个参数需要 grad。”。它无法进行操作,因为 pt_num 中的张量需要 grad”。

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

4

1 回答 1

1

错误说,

cat(): 带有 out=... 参数的函数不支持自动微分,但其中一个参数需要 grad。

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

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

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

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

的返回值torch.cat(),无论您是否使用out=kwarg,都是沿上述维度连接的张量。

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

c = torch.cat(pt_num)
于 2020-09-28T21:26:20.560 回答