淺析對torch.unsqueeze()函數(shù)理解
torch.unsqueeze()函數(shù)理解
torch.unsqueeze(input, dim) 使用時等同于 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) # 此時y.dim()=2 z = x.unsqueeze(1) print(z) print(z.shape) # 此時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) # 此時y.dim()=3 z = x.unsqueeze(1) print(z) print(z.shape) # 此時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)文章
布同 統(tǒng)計英文單詞的個數(shù)的python代碼
最近需要翻譯英文文章,所以需要統(tǒng)計單詞個數(shù)。索性寫了一段代碼在此,可以簡單的統(tǒng)計單詞的個數(shù)2011-03-03opencv+tesseract實現(xiàn)驗證碼識別的示例
本文主要介紹了opencv+tesseract實現(xiàn)驗證碼識別的示例,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2022-06-06python制作一個簡單的gui 數(shù)據(jù)庫查詢界面
這篇文章主要介紹了python制作一個簡單的gui 數(shù)據(jù)庫查詢界面,幫助大家更好的理解和學習python tkinter的使用,感興趣的朋友可以了解下2020-11-11基于Python爬取fofa網(wǎng)頁端數(shù)據(jù)過程解析
這篇文章主要介紹了基于Python爬取fofa網(wǎng)頁端數(shù)據(jù)過程解析,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下2020-07-07python實現(xiàn)自動獲取IP并發(fā)送到郵箱
這篇文章主要為大家詳細介紹了python實現(xiàn)自動獲取IP并發(fā)到郵箱,具有一定的參考價值,感興趣的小伙伴們可以參考一下2018-12-12