pytorch——张量连接

我们可以把多个张量连接在一起,把它们端对端地叠起来形成一个更大的张量。我们只需要提供张量列表,并给出沿哪个轴连接。

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}')

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值