Pytorch實(shí)現(xiàn)List?Tensor轉(zhuǎn)Tensor,reshape拼接等操作
持續(xù)更新一些常用的Tensor操作,比如List,Numpy,Tensor之間的轉(zhuǎn)換,Tensor的拼接,維度的變換等操作。
其它Tensor操作如 einsum等見:待更新。
用到兩個函數(shù):
torch.cattorch.stack
一、List Tensor轉(zhuǎn)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轉(zhuǎn)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.]]])
以上為個人經(jīng)驗(yàn),希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
Python使用Spire.XLS for Python輕松實(shí)現(xiàn)Excel轉(zhuǎn)PDF的完整指南
在日常辦公和數(shù)據(jù)處理中,我們經(jīng)常需要將 Excel 文檔轉(zhuǎn)換為 PDF 格式,今天我們將介紹如何使用 Spire.XLS for Python 庫來實(shí)現(xiàn) Excel 到 PDF 的高效轉(zhuǎn)換,有需要的可以了解下2025-10-10
詳解Django的CSRF認(rèn)證實(shí)現(xiàn)
這篇文章主要介紹了詳解Django的CSRF認(rèn)證實(shí)現(xiàn),詳細(xì)的介紹了csrf原理和實(shí)現(xiàn),小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-10-10
Python Matplotlib條形圖之垂直條形圖和水平條形圖詳解
這篇文章主要為大家詳細(xì)介紹了Python Matplotlib條形圖之垂直條形圖和水平條形圖,使用數(shù)據(jù)庫,文中示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下2022-03-03
matplotlib之pyplot模塊之標(biāo)題(title()和suptitle())
這篇文章主要介紹了matplotlib之pyplot模塊之標(biāo)題(title()和suptitle()),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2021-02-02
使用pandas將numpy中的數(shù)組數(shù)據(jù)保存到csv文件的方法
今天小編就為大家分享一篇使用pandas將numpy中的數(shù)組數(shù)據(jù)保存到csv文件的方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-06-06
Python使用poplib模塊和smtplib模塊收發(fā)電子郵件的教程
smtplib模塊一般我們比較熟悉、這里我們會來講解使用smtplib發(fā)送SSL/TLS安全郵件的方法,而poplib模塊則負(fù)責(zé)處理接收pop3協(xié)議的郵件,下面我們就來看Python使用poplib模塊和smtplib模塊收發(fā)電子郵件的教程2016-07-07

