Difference between tensor.permute and tensor.view in PyTorch?

后端 未结 2 441
一向
一向 2021-01-01 15:37

What is the difference between tensor.permute() and tensor.view()?

They seem to do the same thing.

2条回答
  •  心在旅途
    2021-01-01 16:27

    View changes how the tensor is represented. For ex: a tensor with 4 elements can be represented as 4X1 or 2X2 or 1X4 but permute changes the axes. While permuting the data is moved but with view data is not moved but just reinterpreted.

    Below code examples may help you. a is 2x2 tensor/matrix. With the use of view you can read a as a column or row vector (tensor). But you can't transpose it. To transpose you need permute. Transpose is achieved by swapping/permuting axes.

    In [7]: import torch
    
    In [8]: a = torch.tensor([[1,2],[3,4]])
    
    In [9]: a
    Out[9]: 
    tensor([[ 1,  2],
            [ 3,  4]])
    
    In [11]: a.permute(1,0)
    Out[11]: 
    tensor([[ 1,  3],
            [ 2,  4]])
    
    In [12]: a.view(4,1)
    Out[12]: 
    tensor([[ 1],
            [ 2],
            [ 3],
            [ 4]])
    
    In [13]: 
    

    Bonus: See https://twitter.com/karpathy/status/1013322763790999552

提交回复
热议问题