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

作者:Bagba 时间:2021-06-06 19:58:51 

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

其它Tensor操作如 einsum等见:待更新。

用到两个函数:

  • torch.cat

  • torch.stack

一、List Tensor转Tensor (torch.cat)

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

// 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)

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

代码:

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.]]])

来源:https://blog.csdn.net/bagba/article/details/107047202

标签:Pytorch,List,Tensor,reshape
0
投稿

猜你喜欢

  • ASP连接MySQL数据库代码示例

    2010-03-14 11:24:00
  • 将ASP纪录集输出成n列表格的方法

    2008-03-19 13:27:00
  • asp 通用修改和增加函数代码

    2011-03-16 11:15:00
  • 解决oracle用户连接失败的解决方法

    2011-01-04 19:35:00
  • 提高网页加载显示速度的方法

    2007-08-10 13:17:00
  • JavaScript的2008[译]

    2009-02-20 13:49:00
  • 全屏flash的尺寸分析

    2009-02-11 13:22:00
  • 如何使用PyTorch实现自由的数据读取

    2022-06-16 12:28:16
  • python中文分词库jieba使用方法详解

    2021-11-14 13:31:06
  • 巧用正则表达式获取新闻中图片地址

    2010-07-17 13:09:00
  • asp 类型转换函数大全第1/2页

    2011-04-07 11:06:00
  • Python 多核并行计算的示例代码

    2022-08-18 11:20:36
  • 详解Python中的Lock和Rlock

    2023-08-11 18:35:20
  • Python中隐藏的五种实用技巧分享

    2023-08-23 15:12:05
  • MySQL安全性指南 (2)

    2010-07-26 13:26:00
  • ASP Framework_1_简介

    2009-10-12 11:35:00
  • asp下以Json获取中国天气网天气的代码

    2011-03-06 11:01:00
  • 磁盘垃圾文件清理器python代码实现

    2023-08-24 23:20:41
  • 获得当前数据库对象依赖关系的实用算法

    2009-01-08 13:28:00
  • 数字人组件反写[asp组件开发实例5]

    2009-06-09 13:23:00
  • asp之家 网络编程 m.aspxhome.com