淺析對(duì)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)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
pycharm自定義TODO類注釋以及高亮顏色的設(shè)置方法
這篇文章主要介紹了pycharm自定義TODO類注釋以及高亮顏色的設(shè)置方法,文中通過圖文結(jié)合的方式給大家介紹的非常詳細(xì),具有一定的參考價(jià)值,需要的朋友可以參考下2024-03-03
布同 統(tǒng)計(jì)英文單詞的個(gè)數(shù)的python代碼
最近需要翻譯英文文章,所以需要統(tǒng)計(jì)單詞個(gè)數(shù)。索性寫了一段代碼在此,可以簡(jiǎn)單的統(tǒng)計(jì)單詞的個(gè)數(shù)2011-03-03
opencv+tesseract實(shí)現(xiàn)驗(yàn)證碼識(shí)別的示例
本文主要介紹了opencv+tesseract實(shí)現(xiàn)驗(yàn)證碼識(shí)別的示例,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2022-06-06
python制作一個(gè)簡(jiǎn)單的gui 數(shù)據(jù)庫查詢界面
這篇文章主要介紹了python制作一個(gè)簡(jiǎn)單的gui 數(shù)據(jù)庫查詢界面,幫助大家更好的理解和學(xué)習(xí)python tkinter的使用,感興趣的朋友可以了解下2020-11-11
基于Python爬取fofa網(wǎng)頁端數(shù)據(jù)過程解析
這篇文章主要介紹了基于Python爬取fofa網(wǎng)頁端數(shù)據(jù)過程解析,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-07-07
python實(shí)現(xiàn)自動(dòng)獲取IP并發(fā)送到郵箱
這篇文章主要為大家詳細(xì)介紹了python實(shí)現(xiàn)自動(dòng)獲取IP并發(fā)到郵箱,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2018-12-12

