欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

基于PyTorch的permute和reshape/view的區(qū)別介紹

 更新時間:2020年06月18日 09:51:06   作者:pyxiea  
這篇文章主要介紹了基于PyTorch的permute和reshape/view的區(qū)別介紹,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧

二維的情況

先用二維tensor作為例子,方便理解。

permute作用為調(diào)換Tensor的維度,參數(shù)為調(diào)換的維度。例如對于一個二維Tensor來說,調(diào)用tensor.permute(1,0)意為將1軸(列軸)與0軸(行軸)調(diào)換,相當于進行轉(zhuǎn)置。

In [20]: a    
Out[20]:    
tensor([[0, 1, 2],  
  [3, 4, 5]])  
      
In [21]: a.permute(1,0) 
Out[21]:    
tensor([[0, 3],   
  [1, 4],   
  [2, 5]]) 

如果使用view(3,2)或reshape(3,2),得到的tensor并不是轉(zhuǎn)置的效果,而是相當于將原tensor的元素按行取出,然后按行放入到新形狀的tensor中。

In [22]: a.reshape(3,2) 
Out[22]:    
tensor([[0, 1],   
  [2, 3],   
  [4, 5]])  
      
In [23]: a.view(3,2) 
Out[23]:    
tensor([[0, 1],   
  [2, 3],   
  [4, 5]]) 

高維的情況

一般使用permute的情況都是在更高維的情況下使用,例如對于一個圖像batch,其形狀為[batch, channel, height, width],我們可以使用tensor.permute(0,3,2,1)得到形狀為[batch, width, height, channel]的tensor.

我們構(gòu)造一個模擬的batch用于演示。

In [25]: a=torch.arange(2*3*2*1).reshape(2,3,2,1) 
             
In [26]: a          
Out[26]:           
tensor([[[[ 0],    # 這是第0張“圖片”的第0號通道的2個元素      
   [ 1]],         
             
   [[ 2],    # 這是第0張“圖片”的第1號通道的2個元素      
   [ 3]],         
             
   [[ 4],    # 這是第0張“圖片”的第2號通道的2個元素      
   [ 5]]],         
             
             
  [[[ 6],         
   [ 7]],         
             
   [[ 8],         
   [ 9]],         
             
   [[10],         
   [11]]]]) 

a的形狀為[2,3,2,1],這個batch有2張“圖片”,每張圖片有3個通道,每個通道為2x1,例如第0張圖片的第0號通道為[[0], [1]].

In [27]: a.permute(0,3,2,1)
Out[27]:
tensor([[[[ 0, 2, 4],
   [ 1, 3, 5]]],


  [[[ 6, 8, 10],
   [ 7, 9, 11]]]])
In [28]: a.permute(0,3,2,1).shape
Out[28]: torch.Size([2, 1, 2, 3])

形狀為[2,3,2,1]的batch執(zhí)行permute(0,3,2,1)交換維度之后,得到的是[2,1,2,3],即[batch, width, height, channel]

可以理解為,對于一個高維的Tensor執(zhí)行permute,我們沒有改變數(shù)據(jù)的相對位置,而只是旋轉(zhuǎn)了一下這個(超)立方體?;蛘咭部梢哉f,改變了我們對這個(超)立方體的“觀察角度”而已。

補充知識:pytorch: torch.Tensor.view ------ reshape

如下所示:

torch.Tensoe.view(python method, in torch.Tensor)

作用: 將輸入的torch.Tensor改變形狀(size)并返回.返回的Tensor與輸入的Tensor必須有相同的元素,相同的元素數(shù)目,但形狀可以不一樣

即,view起到的作用是reshape,view的參數(shù)的是改變后的shape.

示例如下:

>>> x = torch.randn(4, 4)
>>> x.size()
torch.Size([4, 4])
>>> y = x.view(16)
>>> y.size()
torch.Size([16])
>>> z = x.view(-1, 8) # the size -1 is inferred from other dimensions
>>> z.size()
torch.Size([2, 8])

view_as:

tensor_1.view_as(tensor_2):將tensor_1的形狀改成與tensor_2一樣

以上這篇基于PyTorch的permute和reshape/view的區(qū)別介紹就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。

相關(guān)文章

最新評論