python pytorch中.view()函數(shù)的用法解讀
python pytorch中.view()函數(shù)
在使用pytorch定義神經(jīng)網(wǎng)絡時,經(jīng)常會看到類似如下的.view()用法,這里對其用法做出講解與演示。

普通用法 (手動調整size)
view()相當于reshape、resize,重新調整Tensor的形狀。
import torch a1 = torch.arange(0,16) print(a1)
tensor([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15])
a2 = a1.view(8, 2) a3 = a1.view(2, 8) a4 = a1.view(4, 4) print(a2) print(a3) print(a4)
tensor([[ 0, 1],
[ 2, 3],
[ 4, 5],
[ 6, 7],
[ 8, 9],
[10, 11],
[12, 13],
[14, 15]])
tensor([[ 0, 1, 2, 3, 4, 5, 6, 7],
[ 8, 9, 10, 11, 12, 13, 14, 15]])
tensor([[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11],
[12, 13, 14, 15]])特殊用法:參數(shù)-1 (自動調整size)
view中一個參數(shù)定為-1,代表自動調整這個維度上的元素個數(shù),以保證元素的總數(shù)不變。
import torch a1 = torch.arange(0,16) print(a1)
tensor([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15])
a2 = a1.view(-1, 16) a3 = a1.view(-1, 8) a4 = a1.view(-1, 4) a5 = a1.view(-1, 2) a6 = a1.view(4*4, -1) a7 = a1.view(1*4, -1) a8 = a1.view(2*4, -1) print(a2) print(a3) print(a4) print(a5) print(a6) print(a7) print(a8)
tensor([[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]])
tensor([[ 0, 1, 2, 3, 4, 5, 6, 7],
[ 8, 9, 10, 11, 12, 13, 14, 15]])
tensor([[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11],
[12, 13, 14, 15]])
tensor([[ 0, 1],
[ 2, 3],
[ 4, 5],
[ 6, 7],
[ 8, 9],
[10, 11],
[12, 13],
[14, 15]])
tensor([[ 0],
[ 1],
[ 2],
[ 3],
[ 4],
[ 5],
[ 6],
[ 7],
[ 8],
[ 9],
[10],
[11],
[12],
[13],
[14],
[15]])
tensor([[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11],
[12, 13, 14, 15]])
tensor([[ 0, 1],
[ 2, 3],
[ 4, 5],
[ 6, 7],
[ 8, 9],
[10, 11],
[12, 13],
[14, 15]])python中view()函數(shù)怎么用
初學者在使用pytorch框架定義神經(jīng)網(wǎng)絡時,經(jīng)常會在代碼中看到:

這樣的用法。
view()的作用相當于numpy中的reshape,重新定義矩陣的形狀。
例1 普通用法:
import torch v1 = torch.range(1, 16) v2 = v1.view(4, 4)
其中v1為1*16大小的張量,包含16個元素。v2為4*4大小的張量,同樣包含16個元素。注意view前后的元素個數(shù)要相同,不然會報錯。
例2 參數(shù)使用-1
import torch v1 = torch.range(1, 16) v2 = v1.view(-1, 4)
和圖例中的用法一樣,view中一個參數(shù)定為-1,代表動態(tài)調整這個維度上的元素個數(shù),以保證元素的總數(shù)不變。因此兩個例子的結果是相同的。
總結
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
Python實現(xiàn)查找字符串數(shù)組最長公共前綴示例
這篇文章主要介紹了Python實現(xiàn)查找字符串數(shù)組最長公共前綴,涉及Python針對字符串的遍歷、判斷、計算等相關操作技巧,需要的朋友可以參考下2019-03-03
淺談tensorflow語義分割api的使用(deeplab訓練cityscapes)
這篇文章主要介紹了淺談tensorflow語義分割api的使用(deeplab訓練cityscapes),具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-05-05

