torch.cat 但创造了一个新的维度

Ben*_*ier 7 concatenation pytorch tensor

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

例如:

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
Run Code Online (Sandbox Code Playgroud)

有没有更简单的方法?

Ben*_*ier 14

只需使用torch.stack

torch.stack([x,x,x,x]).shape # (4, 2, 3)
Run Code Online (Sandbox Code Playgroud)