torch.cat((a,b), dim=0) 在张量(tensor)的基础维度上拼接在一起
在给定维度上对输入的张量序列seq 进行连接操作。
参数:
(a, b) – a, b可以是任意相同Tensor 类型。输入数据必须是序列,序列中数据是任意相同的shape的同类型tensor。
dim(int, optional) – 沿着此维连接张量序列。维度不可以超过输入数据的任一个张量的维度。
a1 = torch.rand(4,3,32,32) a2 = torch.rand(5,3,32,32) torch.cat([a1,a2],dim=0).shape # torch.Size([9, 3, 32, 32]) a2 = torch.rand(4,1,32,32) torch.cat([a1,a2],dim=1).shape # torch.Size([4, 4, 32, 32]) a1 = torch.rand(4,3,16,32) a2 = torch.rand(4,3,16,32) torch.cat([a1,a2],dim=3).shape # torch.Size([4, 3, 16, 64]) a1 = torch.rand(4,3,32,32) torch.cat([a1,a2],dim=0).shape # RuntimeError: Sizes of tensors must match except in dimension 0. Expected size 32 but got size 16 for tensor number 1 in the list.
注意:使用torch.cat((a, b),dim)时,除拼接维数dim数值可不同外其余维数数值需相同,方能对齐。
torch.stack([a,b], dim=0) 创造一个新的维度
沿着一个新维度对输入张量序列进行连接。 序列中所有的张量都应该为相同形状。
参数:
[Tensor, Tensor, …] – 待连接的张量序列
dim (int) – 插入的维度。必须介于 0 与 待连接的张量序列数之间。
a1 = torch.rand(4,3,16,32) a2 = torch.rand(4,3,16,32) torch.stack([a1,a2],dim=2).shape # 添加了一个维度。 # torch.Size([4, 3, 2, 16, 32]) a = torch.rand(32,8) b = torch.rand(32,8) torch.stack([a,b],dim=0).shape # torch.Size([2, 32, 8]) b = torch.rand([30,8]) torch.stack([a,b],dim=0) # 要求tensor的size完全相同 RuntimeError: stack expects each tensor to be equal size, but got [32, 8] at entry 0 and [30, 8] at entry 1



