pytorch中的reshape()、view()、transpose()和flatten()

文章內容皆爲個人理解,如有不足歡迎指正。

1、torch.reshape()
reshape()可以由torch.reshape(),也可由torch.Tensor.reshape()調用
其作用是在不改變tensor元素數目的情況下改變tensor的shape

import torch
import numpy as np
a = np.arange(24)
b = a.reshape(4,3,2)
print(np.shape(a))
print(b,np.shape(b))

'''結果
(24,)
[[[ 0  1]
  [ 2  3]
  [ 4  5]]

 [[ 6  7]
  [ 8  9]
  [10 11]]

 [[12 13]
  [14 15]
  [16 17]]

 [[18 19]
  [20 21]
  [22 23]]] (4, 3, 2)
'''

2、view()
view()只可以由torch.Tensor.view()來調用
view()和reshape()在效果上是一樣的,區別是view()只能操作contiguous的tensor,且view後的tensor和原tensor共享存儲,reshape()對於是否contiuous的tensor都可以操作。

3、transpose()

torch.transpose(input, dim0, dim1) -> Tensor

將輸入數據input的第dim0維和dim1維進行交換

#官方例子
>>> x = torch.randn(2, 3)
>>> x
tensor([[ 0.9068,  1.8803, -0.5021],
        [-0.6576,  0.6334, -0.8961]])
>>> torch.transpose(x, 0, 1)
tensor([[ 0.9068, -0.6576],
        [ 1.8803,  0.6334],
        [-0.5021, -0.8961]])

4、flatten()
torch.flatten()的輸入是tensor

torch.flatten(input, start_dim=0, end_dim=-1) → Tensor

其作用是將輸入tensor的第start_dim維到end_dim維之間的數據“拉平”成一維tensor,

#官方例子
>>> t = torch.tensor([[[1, 2],
                               [3, 4]],
                              [[5, 6],
                               [7, 8]]])
>>> torch.flatten(t)
tensor([1, 2, 3, 4, 5, 6, 7, 8])
>>> torch.flatten(t, start_dim=1)
tensor([[1, 2, 3, 4],
        [5, 6, 7, 8]])

torch.nn.Flatten()可以理解爲一種網絡結構,類似Conv2d、Linear。一般放在卷積層和全連接層之間,將卷積層輸出“拉平”成一維,

>>> m = torch.nn.Sequential(
    torch.nn.Conv2d(1, 32, 5, 1, 1),
    torch.nn.Flatten(),
    torch.nn.Linear(160,10))
>>> m
Sequential(
  (0): Conv2d(1, 32, kernel_size=(5, 5), stride=(1, 1), padding=(1, 1))
  (1): Flatten()
  (2): Linear(in_features=160, out_features=10, bias=True)
)

參考:

https://congluwen.top/2018/12/pytorch_reshape_view/
https://blog.csdn.net/GhostintheCode/article/details/102530451
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章