以pytorch为例
例子
import torch
a = torch.randint(0, 10, (2, 3, 4))
b = torch.randint(0, 10, (2, 3, 4))
print(a.shape, a)
print(b.shape, b)
c = torch.stack([a, b], dim=0)
d = torch.stack([a, b], dim=1)
e = torch.stack([a, b], dim=2)
print(c.shape, c)
print(d.shape, d)
print(e.shape, e)
f = torch.cat([a, b], dim=0)
g = torch.cat([a, b], dim=1)
h = torch.cat([a, b], dim=2)
print(f.shape, f)
print(g.shape, g)
print(h.shape, h)
打印结果:
a: torch.Size([2, 3, 4]) tensor([[[0, 6, 7, 9],
[8, 9, 3, 9],
[1, 5, 9, 0]],
[[2, 6, 7, 2],
[5, 7, 1, 2],
[4, 1, 9, 1]]])
b: torch.Size([2, 3, 4]) tensor([[[5, 7, 9, 0],
[8, 5, 5, 9],
[5, 2, 5, 3]],
[[5, 7, 4, 1],
[2, 9, 4, 3],
[1, 4, 3, 2]]])
c: torch.Size([2, 2, 3, 4]) tensor([[[[0, 6, 7, 9],
[8, 9, 3, 9],
[1, 5, 9, 0]],
[[2, 6, 7, 2],
[5, 7, 1, 2],
[4, 1, 9, 1]]],
[[[5, 7, 9, 0],
[8, 5, 5, 9],
[5, 2, 5, 3]],
[[5, 7, 4, 1],
[2, 9, 4, 3],
[1, 4, 3, 2]]]])
d: torch.Size([2, 2, 3, 4]) tensor([[[[0, 6, 7, 9],
[8, 9, 3, 9],
[1, 5, 9, 0]],
[[5, 7, 9, 0],
[8, 5, 5, 9],
[5, 2, 5, 3]]],
[[[2, 6, 7, 2],
[5, 7, 1, 2],
[4, 1, 9, 1]],
[[5, 7, 4, 1],
[2, 9, 4, 3],
[1, 4, 3, 2]]]])
e torch.Size([2, 3, 2, 4]) tensor([[[[0, 6, 7, 9],
[5, 7, 9, 0]],
[[8, 9, 3, 9],
[8, 5, 5, 9]],
[[1, 5, 9, 0],
[5, 2, 5, 3]]],
[[[2, 6, 7, 2],
[5, 7, 4, 1]],
[[5, 7, 1, 2],
[2, 9, 4, 3]],
[[4, 1, 9, 1],
[1, 4, 3, 2]]]])
f: torch.Size([4, 3, 4]) tensor([[[0, 6, 7, 9],
[8, 9, 3, 9],
[1, 5, 9, 0]],
[[2, 6, 7, 2],
[5, 7, 1, 2],
[4, 1, 9, 1]],
[[5, 7, 9, 0],
[8, 5, 5, 9],
[5, 2, 5, 3]],
[[5, 7, 4, 1],
[2, 9, 4, 3],
[1, 4, 3, 2]]])
g: torch.Size([2, 6, 4]) tensor([[[0, 6, 7, 9],
[8, 9, 3, 9],
[1, 5, 9, 0],
[5, 7, 9, 0],
[8, 5, 5, 9],
[5, 2, 5, 3]],
[[2, 6, 7, 2],
[5, 7, 1, 2],
[4, 1, 9, 1],
[5, 7, 4, 1],
[2, 9, 4, 3],
[1, 4, 3, 2]]])
h: torch.Size([2, 3, 8]) tensor([[[0, 6, 7, 9, 5, 7, 9, 0],
[8, 9, 3, 9, 8, 5, 5, 9],
[1, 5, 9, 0, 5, 2, 5, 3]],
[[2, 6, 7, 2, 5, 7, 4, 1],
[5, 7, 1, 2, 2, 9, 4, 3],
[4, 1, 9, 1, 1, 4, 3, 2]]])
总结
可以看出,concat是拼接tensor,维度不会扩张,但拼接的维度会变成维度之和,如:2个(2,3,4)的tensor在最后一个维度拼接,结果是(2,3,8);stack是堆tensor,然后在该维度外层加一个括号,所以维度会在被堆起来的维度前扩张, 扩张为堆的维度数,如:2个(2,3,4)的tensor在最后一个维度stack,结果是(2,3,2,4)。
其他链接
其他stack相关方法:
(1) stack, vstack, hstack差别