這篇文章主要介紹了Pytorch中expand()的使用(擴展某個維度),具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
Pytorch expand()的使用
有兩點需要注意,無論是 expand() 還是 expand_as():文章源自四五設計網-http://www.wasochina.com/38920.html
1.只能在第0維擴展一個維數,比如原來是是(1,3,4)==》(2,1,3,4),而在其他維度擴展不可以(1,3,4)==》(1,2,3,4)【錯誤】文章源自四五設計網-http://www.wasochina.com/38920.html
2.如果不增加維數,只是增加維度,要增加的原維度必須是1才可以在該維度增加維度,其他值均不可以文章源自四五設計網-http://www.wasochina.com/38920.html
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | import torch #1 x = torch.randn( 2 , 1 , 1 ) #為1可以擴展為3和4 x = x.expand( 2 , 3 , 4 ) print ( 'x :' , x.size()) >>> x : torch.Size([ 2 , 3 , 4 ]) #2 #擴展一個新的維度必須在最前面,否則會報錯 x = x.expand( 2 , 3 , 4 , 6 ) >>> RuntimeError: The expanded size of the tensor ( 3 ) must match the existing size ( 2 ) at non - singleton dimension 1. x = x.expand( 6 , 2 , 3 , 4 ) >>> x : torch.Size([ 6 , 2 , 3 , 4 ]) #3 #某一個維度為-1表示不改變該維度的大小 x = x.expand( 6 , - 1 , - 1 , - 1 ) >>> x : torch.Size([ 6 , 2 , 1 , 1 ]) |
1 2 3 4 5 6 7 8 9 10 11 12 13 | import torch #1 x = torch.randn( 2 , 1 , 1 ) #原維度為1可以擴展為其他維度 y = torch.randn( 2 , 3 , 3 ) x = x.expand_as(y) print ( 'x :' , x.size()) >>> x : torch.Size([ 2 , 3 , 3 ]) #2 x = torch.randn( 2 , 2 , 2 ) #原維度為其他不是1的值不可以擴展為其他維度 y = torch.randn( 2 , 3 , 4 ) x = x.expand_as(y) print ( 'x :' , x.size()) >>> RuntimeError: The expanded size of the tensor ( 4 ) must match the existing size ( 2 ) at non - singleton dimension 2. ? Target sizes: [ 2 , 3 , 4 ]. |
Pytorch expand()函數
返回tensor的一個新視圖
單個維度擴大為更大的尺寸。文章源自四五設計網-http://www.wasochina.com/38920.html
tensor也可以擴大為更高維,新增加的維度將附在前面。文章源自四五設計網-http://www.wasochina.com/38920.html
擴大tensor不需要分配新內存,只是僅僅新建一個tensor的視圖,其中通過將stride設為0,一維將會擴展位更高維。文章源自四五設計網-http://www.wasochina.com/38920.html
任何一個一維的在不分配新內存情況下可擴展為任意的數值。文章源自四五設計網-http://www.wasochina.com/38920.html
文章源自四五設計網-http://www.wasochina.com/38920.html
note:使用expand()函數的時候
x自身不會改變,因此需要將結果重新賦值。文章源自四五設計網-http://www.wasochina.com/38920.html
以上為個人經驗,希望能給大家一個參考。文章源自四五設計網-http://www.wasochina.com/38920.html


評論