我们可以把多个张量连接在一起,把它们端对端地叠起来形成一个更大的张量。我们只需要提供张量列表,并给出沿哪个轴连接。
x = torch.arange(12, dtype=torch.float32).reshape(3, 4)
y=torch.tensor([[2.0,1,4,3],[1,2,3,4],[4,3,2,1]])
z=torch.cat((x,y),dim=0)
o=torch.cat((x,y),dim=1)
print(f'x: {x}')
print(f'y: {y}')
print(f'沿行拼接(列数不变): {z}')
print(f'沿列拼接(行数不变): {o}')
-
如果按行拼接,则两个张量的列数应当相同;
-
如果按列拼接,则两个张量的行数应当相同。
X=torch.arange(12).reshape(3,4)
Y=torch.arange(15).reshape(3,5)
Z=torch.arange(16).reshape(4,4)
O0=torch.cat((X,Z),dim=0)
print(f'O0(行拼接): {O0.shape}')
O1=torch.cat((X,Y),dim=1)
print(f'O1(列拼接): {O1.shape}')
拼接时,应当保持张量其余轴的形状相同
x_3d=torch.arange(24).reshape(2,3,4)
y_3d=torch.arange(36).reshape(3,3,4)
z_3d=torch.arange(32).reshape(2,4,4)
m_3d=torch.arange(30).reshape(2,3,5)
o_dim0=torch.cat((x_3d,y_3d),dim=0)
print(f'dim=0: {o_dim0.shape}')
o_dim1=torch.cat((x_3d,z_3d),dim=1)
print(f'dim=1: {o_dim1.shape}')
o_dim2=torch.cat((x_3d,m_3d),dim=2)
print(f'dim=2: {o_dim2.shape}')