代码之家  ›  专栏  ›  技术社区  ›  enryu

Pytorch增加尺寸

  •  0
  • enryu  · 技术社区  · 2 年前

    假设我有一个大小为(4,4,4,4)的张量,我如何使大小为(4,4,4,5)的张量使得新添加的条目为1?

    即,做以下事情的正确方法是什么?

    #given a tensor points of some size
    pshape = list(points.size())
    pshape[-1] = 1
    z = torch.ones(pshape)
    return torch.cat((points, z), -1)
    
    1 回复  |  直到 2 年前
        1
  •  0
  •   Oskar Hofmann    2 年前

    据我所知,对于非单例维度,没有特殊的方法可以做到这一点。所以你的解决方案在我看来是正确的。

    或者,在这里有效的方法是:

    #given a tensor points of some size
    pshape = list(points.size())
    pshape[-1] += 1
    z = torch.ones(pshape)
    z[..., 0:-1] = points
    

    在我的机器上,你的代码对小张量稍快,而我的建议对大张量稍快。不过,这两种情况的差异微乎其微。