Torch.Stack Example

torch.stack example
>>> import torch
>>> a = torch.randn([2, 3, 4])
>>> b = torch.randn([2, 3])
>>> b = b.unsqueeze(dim=2)
>>> b.shape
torch.Size([2, 3, 1])
>>> torch.cat([a, b], dim=2).shape
torch.Size([2, 3, 5])
torch.stack example
a.size() # 2, 3, 4
b.size() # 2, 3
b = torch.unsqueeze(b, dim=2) # 2, 3, 1
# torch.unsqueeze(b, dim=-1) does the same thing

torch.stack([a, b], dim=2) # 2, 3, 5
torch.stack
> torch.stack(
(t1,t2,t3)
,dim=0
)
tensor([[1, 1, 1],
[2, 2, 2],
[3, 3, 3]])

Leave a Comment