Reputation: 41855
I would like to concatenate tensors, not along a dimension, but by creating a new dimension.
For example:
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
Is there a simpler way?
Upvotes: 11
Views: 16477
Reputation: 41855
Just use torch.stack:
torch.stack([x,x,x,x]).shape # (4, 2, 3)
Upvotes: 23