广告
返回顶部
首页 > 资讯 > 后端开发 > Python >Pytorch实现List Tensor转Tensor,reshape拼接等操作
  • 439
分享到

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

2024-04-02 19:04:59 439人浏览 泡泡鱼

Python 官方文档:入门教程 => 点击学习

摘要

目录一、List Tensor转Tensor (torch.cat)高维tensor二、List Tensor转Tensor (torch.stack)持续更新一些常用的Tensor

持续更新一些常用的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.]]])

以上为个人经验,希望能给大家一个参考,也希望大家多多支持编程网。

--结束END--

本文标题: Pytorch实现List Tensor转Tensor,reshape拼接等操作

本文链接: https://www.lsjlt.com/news/120902.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作