pytorch學習 中 torch.squeeze() 和torch.unsqueeze()的用法


一、先看torch.squeeze() 這個函數主要對數據的維度進行壓縮,去掉維數為1的的維度,比如是一行或者一列這種,一個一行三列(1,3)的數去掉第一個維數為一的維度之后就變成(3)行。

1.squeeze(a)就是將a中所有為1的維度刪掉。不為1的維度沒有影響。

2.a.squeeze(N) 就是去掉a中指定的維數為一的維度。

  還有一種形式就是b=torch.squeeze(a,N) a中去掉指定的維數N為一的維度。

二、再看torch.unsqueeze()這個函數主要是對數據維度進行擴充。

給指定位置加上維數為一的維度,比如原本有個三行的數據(3),在0的位置加了一維就變成一行三列(1,3)。a.unsqueeze(N) 就是在a中指定位置N加上一個維數為1的維度。

還有一種形式就是b=torch.unsqueeze(a,N) a就是在a中指定位置N加上一個維數為1的維度
代碼如下:

折疊:

a=torch.randn(1,1,3)
print(a.shape)
b=torch.squeeze(a)
print(b.shape)
c=torch.squeeze(a,0)
print(c.shape)
d=torch.squeeze(a,1)
print(d.shape)
e=torch.squeeze(a,2)#如果去掉第三維,則數不夠放了,所以直接保留
print(e.shape)

輸出:

torch.Size([1, 1, 3])
torch.Size([3])
torch.Size([1, 3])
torch.Size([1, 3])
torch.Size([1, 1, 3])

展開:

a=torch.randn(1,3)
print(a.shape)
b=torch.unsqueeze(a,0)
print(b.shape)
c=torch.unsqueeze(a,1)
print(c.shape)
d=torch.unsqueeze(a,2)
print(d.shape)

輸出:

torch.Size([1, 3])
torch.Size([1, 1, 3])
torch.Size([1, 1, 3])
torch.Size([1, 3, 1])

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM