【问题标题】:torch.cat but create a new dimensiontorch.cat 但创建了一个新维度
【发布时间】:2020-01-03 18:14:20
【问题描述】:

我想连接张量,不是沿着一个维度,而是通过创建一个新维度。

例如:

x = torch.randn(2, 3)
x.shape # (2, 3)

torch.cat([x,x,x,x], 0).shape # (8, 3)
# This concats along dim 0, not what I want

torch.cat([x,x,x,x], -1).shape # (2, 10)
# This concats along dim 1, not what I want

torch.cat([x[None, :, :],x[None, :, :],x[None, :, :],x[None, :, :]], 0).shape 
# => (4, 2, 3)
# This is what I want, but unwieldy

有没有更简单的方法?

【问题讨论】:

    标签: concatenation pytorch tensor


    【解决方案1】:

    只需使用torch.stack:

    torch.stack([x,x,x,x]).shape # (4, 2, 3)
    

    【讨论】:

      猜你喜欢
      • 2021-02-02
      • 2021-03-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-07
      相关资源
      最近更新 更多