淺析對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])到此這篇關于torch.unsqueeze()函數(shù)理解的文章就介紹到這了,更多相關torch.unsqueeze()函數(shù)內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
Python web框架fastapi中間件的使用及CORS跨域問題
fastapi "中間件"是一個函數(shù),它在每個請求被特定的路徑操作處理之前,以及在每個響應之后工作,它接收你的應用程序的每一個請求,下面通過本文給大家介紹Python web框架fastapi中間件的使用及CORS跨域問題,感興趣的朋友一起看看吧2024-03-03
Python中l(wèi)ogging日志記錄到文件及自動分割的操作代碼
這篇文章主要介紹了Python中l(wèi)ogging日志記錄到文件及自動分割,本文給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-08-08
詳解如何使用SQLAlchemy連接數(shù)據(jù)庫
這篇文章主要為大家詳細介紹了如何使用 SQLAlchemy 連接數(shù)據(jù)庫、建立模型、操作表、以及查詢操作表數(shù)據(jù)等內容,感興趣的小伙伴可以跟隨小編一起學習一下2023-11-11
通過實例了解Python str()和repr()的區(qū)別
這篇文章主要介紹了通過實例了解Python str()和repr()的區(qū)別,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下2020-01-01

