Pytorch如何实现List和Tensor的转化,要注意哪些问题
Admin 2022-12-20 群英技术资讯 666 次浏览
持续更新一些常用的Tensor操作,比如List,Numpy,Tensor之间的转换,Tensor的拼接,维度的变换等操作。
其它Tensor操作如 einsum等见:待更新。
用到两个函数:
torch.cat
torch.stack
// 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.]]])
** 如果理解了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.]]]])
代码:
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.]]])
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:mmqy2019@163.com进行举报,并提供相关证据,查实之后,将立刻删除涉嫌侵权内容。
猜你喜欢
1、捕获摄像头和实时显示importcv2importnumpyasnpimportpickleimportmatplotlib.pyplotaspltcap=cv2.VideoCapture(0)whileTrue:ret,frame=cap.read()#Ouroperationsontheframecomehere
这篇文章主要介绍了Python遍历目录下文件、读取、千万条数据合并详情,对文件夹和文件进行属性判断,首先对文件夹进行遍历,看文件夹里有什么样的文件,读取出文件夹中的所有文件,下面文章将详细介绍该内容,需要的小伙伴可以参考一下
这篇文章主要介绍了Python可视化神器pyecharts绘制桑基图,即桑基能量分流图,也叫桑基能量平衡图,更多相关介绍具有一定的参考价值,需要的朋友可以参考一下
这篇文章主要介绍了Python 迭代器Iterator详情,迭代器可以帮助我们解决面对复杂的数据场景时,快速简便的获取数据,下文关于其详细介绍,需要的小伙伴可以参考一下
之前小编向大家介绍过complex函数,complex函数可以表示复数数据类型,创建一个值为 real + imag * j 的复数,real为实部,imag为虚部。或者转化一个字符串或数为复数。本文将以两个示例演示用python中complex函数提供的real获取实数部分的过程。
成为群英会员,开启智能安全云计算之旅
立即注册Copyright © QY Network Company Ltd. All Rights Reserved. 2003-2020 群英 版权所有
增值电信经营许可证 : B1.B2-20140078 粤ICP备09006778号 域名注册商资质 粤 D3.1-20240008