淺析對torch.unsqueeze()函數(shù)理解
torch.unsqueeze()函數(shù)理解
torch.unsqueeze(input, dim) 使用時(shí)等同于 input.unsqueeze(dim)
torch.unsqueeze()函數(shù)起到升維的作用,dim等于幾表示在第幾維度加一,比如原來x的size=([4]),x.unsqueeze(0)之后就變成了size=([1, 4]),而x.unsqueeze(1)之后就變成了size=([4, 1]),注意dim∈[-input.dim() - 1, input.dim() + 1]
例如
輸入一維張量,即input.dim()=1
# 輸入: x = torch.tensor([1, 2, 3, 4]) # x.dim()=1 print(x) print(x.shape) y = x.unsqueeze(0) print(y) print(y.shape) # 此時(shí)y.dim()=2 z = x.unsqueeze(1) print(z) print(z.shape) # 此時(shí)z.dim()=2
# 輸出:
tensor([1, 2, 3, 4])
torch.Size([4])
tensor([[1, 2, 3, 4]])
torch.Size([1, 4])
tensor([[1],
[2],
[3],
[4]])
torch.Size([4, 1])輸入二維張量,即input.dim()=2
# 輸入: x = torch.tensor([[1, 2, 3], [4, 5, 6]]) # x.dim()=2 print(x) print(x.shape) y = x.unsqueeze(0) print(y) print(y.shape) # 此時(shí)y.dim()=3 z = x.unsqueeze(1) print(z) print(z.shape) # 此時(shí)z.dim()=3
# 輸出:
tensor([[1, 2, 3],
[4, 5, 6]])
torch.Size([2, 3])
tensor([[[1, 2, 3],
[4, 5, 6]]])
torch.Size([1, 2, 3])
tensor([[[1, 2, 3]],
[[4, 5, 6]]])
torch.Size([2, 1, 3])輸入四維張量,即input.dim()=4
# 輸入:
x = torch.tensor([[[[1, 2, 3],
[4, 5, 6]],
[[0, 2, 1],
[1, 5, 2]]],
[[[1, 2, 3],
[4, 5, 6]],
[[0, 2, 1],
[1, 5, 2]]]])
print(x)
print(x.shape)
y2 = x.unsqueeze(2)
print(y2)
print(y2.shape)
y3 = x.unsqueeze(3)
print(y3)
print(y3.shape)# 輸出:
tensor([[[[1, 2, 3],
[4, 5, 6]],
[[0, 2, 1],
[1, 5, 2]]],
[[[1, 2, 3],
[4, 5, 6]],
[[0, 2, 1],
[1, 5, 2]]]])
torch.Size([2, 2, 2, 3])
tensor([[[[[1, 2, 3],
[4, 5, 6]]],
[[[0, 2, 1],
[1, 5, 2]]]],
[[[[1, 2, 3],
[4, 5, 6]]],
[[[0, 2, 1],
[1, 5, 2]]]]])
torch.Size([2, 2, 1, 2, 3])
tensor([[[[[1, 2, 3]],
[[4, 5, 6]]],
[[[0, 2, 1]],
[[1, 5, 2]]]],
[[[[1, 2, 3]],
[[4, 5, 6]]],
[[[0, 2, 1]],
[[1, 5, 2]]]]])
torch.Size([2, 2, 2, 1, 3])到此這篇關(guān)于torch.unsqueeze()函數(shù)理解的文章就介紹到這了,更多相關(guān)torch.unsqueeze()函數(shù)內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Python web框架fastapi中間件的使用及CORS跨域問題
fastapi "中間件"是一個(gè)函數(shù),它在每個(gè)請求被特定的路徑操作處理之前,以及在每個(gè)響應(yīng)之后工作,它接收你的應(yīng)用程序的每一個(gè)請求,下面通過本文給大家介紹Python web框架fastapi中間件的使用及CORS跨域問題,感興趣的朋友一起看看吧2024-03-03
Python+PyQt5實(shí)現(xiàn)PDF批量水印工具
本文圍繞 PDF添加水印.py,完整講解如何將單文件水印腳本重構(gòu)為可交互的 PyQt5 桌面應(yīng)用,支持拖拽導(dǎo)入、實(shí)時(shí)預(yù)覽、子線程處理與輸出管理,并給出關(guān)鍵實(shí)現(xiàn)細(xì)節(jié)與結(jié)構(gòu)說明,需要的朋友可以參考下2026-03-03
Python中l(wèi)ogging日志記錄到文件及自動(dòng)分割的操作代碼
這篇文章主要介紹了Python中l(wèi)ogging日志記錄到文件及自動(dòng)分割,本文給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-08-08
詳解如何使用SQLAlchemy連接數(shù)據(jù)庫
這篇文章主要為大家詳細(xì)介紹了如何使用 SQLAlchemy 連接數(shù)據(jù)庫、建立模型、操作表、以及查詢操作表數(shù)據(jù)等內(nèi)容,感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下2023-11-11
通過實(shí)例了解Python str()和repr()的區(qū)別
這篇文章主要介紹了通過實(shí)例了解Python str()和repr()的區(qū)別,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-01-01

