torch.Tensor.view
會傳回具有相同資料但大小不同的新張量。 傳回的張量必須有與原張量相同的資料和相同數量的元素,但可以有不同的大小。一個張量必須是連續
contiguous()
的才能被檢視。類似于Numpy的
np.reshape()。
pytorch中view的用法
torch.Tensor.view
會将原有資料重新配置設定為一個新的張量,比如我們使用:
x = torch.randn(2, 4)
會輸出一個随機張量:
1.5600 -1.6180 -2.0366 2.7115
0.8415 -1.0103 -0.4793 1.5734
[torch.FloatTensor of size 2x4]
然後我們看一下使用view重新構造一個
Tensor
y = x.view(4,2)
print y
# 輸出如下
1.5600 -1.6180
-2.0366 2.7115
0.8415 -1.0103
-0.4793 1.5734
[torch.FloatTensor of size 4x2]
從這裡我們可以看出來他的作用,既然這樣,我們可以将他變成一個三維數組:
z = x.view(2,2,2)
# 輸出
(0 ,.,.) =
1.5600 -1.6180
-2.0366 2.7115
(1 ,.,.) =
0.8415 -1.0103
-0.4793 1.5734
[torch.FloatTensor of size 2x2x2]
注意:我們不能随便定義參數,需要根據自己的資料使用,比如
x.view(2,2,1)
會傳回錯誤
RuntimeError: invalid argument 2: size '[2 x 2 x 1]' is invalid for input of with 8 elements at /Users/soumith/code/builder/wheel/pytorch-src/torch/lib/TH/THStorage.c:41
下面是官方的案例:
x = torch.randn(4, 4)
print x
print x.size()
# 輸出(4L, 4L)
y = x.view(16)
print y.size()
# 輸出(16L,)
z = x.view(-1, 8) # the size -1 is inferred from other dimensions
print z.size()
# 輸出(2L, 8L)
轉自:https://ptorch.com/news/59.html