Pytorch实现List Tensor转Tensor,reshape拼接等操作
更新时间:2022年11月03日 11:46:45 作者:Bagba
这篇文章主要介绍了Pytorch实现List Tensor转Tensor,reshape拼接等操作,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
持续更新一些常用的Tensor操作,比如List,Numpy,Tensor之间的转换,Tensor的拼接,维度的变换等操作。
其它Tensor操作如 einsum等见:待更新。
用到两个函数:
torch.cattorch.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.]]])
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。
相关文章
Python使用Spire.XLS for Python轻松实现Excel转PDF的完整指南
在日常办公和数据处理中,我们经常需要将 Excel 文档转换为 PDF 格式,今天我们将介绍如何使用 Spire.XLS for Python 库来实现 Excel 到 PDF 的高效转换,有需要的可以了解下2025-10-10
Python Matplotlib条形图之垂直条形图和水平条形图详解
这篇文章主要为大家详细介绍了Python Matplotlib条形图之垂直条形图和水平条形图,使用数据库,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下2022-03-03
matplotlib之pyplot模块之标题(title()和suptitle())
这篇文章主要介绍了matplotlib之pyplot模块之标题(title()和suptitle()),文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧2021-02-02
使用pandas将numpy中的数组数据保存到csv文件的方法
今天小编就为大家分享一篇使用pandas将numpy中的数组数据保存到csv文件的方法,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧2018-06-06
Python使用poplib模块和smtplib模块收发电子邮件的教程
smtplib模块一般我们比较熟悉、这里我们会来讲解使用smtplib发送SSL/TLS安全邮件的方法,而poplib模块则负责处理接收pop3协议的邮件,下面我们就来看Python使用poplib模块和smtplib模块收发电子邮件的教程2016-07-07


最新评论