Pytorch List Tensor转Tensor,reshape拼接等操作

Pytorch List Tensor转Tensor,reshape拼接等操作

持续更新一些常用的Tensor操作,比如List,Numpy,Tensor之间的转换,Tensor的拼接,维度的变换等操作。其它Tensor操作如 einsum等见:待更新。

用到两个函数:torch.cat 和 torch.stack

(一) List Tensor转Tensor (torch.cat)

在这里插入图片描述

// An highlighted block
>>> t1 = torch.FloatTensor([[1,2],[5,6]])
>>> t2 = torch.FloatTensor([[3,4],[7,8]])
>>> l = []
>>> l.append(t1)
>>> l.append(t2)
>>> ta = torch.cat(l,dim=0)
>>> ta = torch.cat(l,dim=0).reshape(2,2,2)
>>> tb = torch.cat(l,dim=1).reshape(2,2,2)
>>> ta
tensor([[[1., 2.],
         [5., 6.]],

        [[3., 4.],
         [7., 8.]]])
>>> tb
tensor([[[1., 2.],
         [3., 4.]],

        [[5., 6.],
         [7., 8.]]])

高维tensor

** 如果理解了2D to 3DTensor,以此类推,不难理解3D to 4D,看下面代码即可明白:**

>>> t1 = torch.range(1,8).reshape(2,2,2)
>>> t2 = torch.range(11,18).reshape(2,2,2)
>>> l = []
>>> l.append(t1)
>>> l.append(t2)
>>> torch.cat(l,dim=2).reshape(2,2,2,2)
tensor([[[[ 1.,  2.],
          [11., 12.]],

         [[ 3.,  4.],
          [13., 14.]]],


        [[[ 5.,  6.],
          [15., 16.]],

         [[ 7.,  8.],
          [17., 18.]]]])
>>> torch.cat(l,dim=1).reshape(2,2,2,2)
tensor([[[[ 1.,  2.],
          [ 3.,  4.]],

         [[11., 12.],
          [13., 14.]]],


        [[[ 5.,  6.],
          [ 7.,  8.]],

         [[15., 16.],
          [17., 18.]]]])
>>> torch.cat(l,dim=0).reshape(2,2,2,2)
tensor([[[[ 1.,  2.],
          [ 3.,  4.]],

         [[ 5.,  6.],
          [ 7.,  8.]]],


        [[[11., 12.],
          [13., 14.]],

         [[15., 16.],
          [17., 18.]]]])

(二)List Tensor转Tensor (torch.stack)

在这里插入图片描述
代码:

import torch

t1 = torch.FloatTensor([[1,2],[5,6]])
t2 = torch.FloatTensor([[3,4],[7,8]])
l = [t1, t2]

t3 = torch.stack(l, dim=2)
print(t3.shape)
print(t3)

## output:
## torch.Size([2, 2, 2])
## tensor([[[1., 3.],
##          [2., 4.]],
##        [[5., 7.],
##         [6., 8.]]])
  • 12
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值