Pytorch--view()--reshape()--traspose()--permute()

view()和reshape()

不是转置的效果,而是相当于将原tensor的元素按行取出,然后按行放入到新形状的tensor中。

  • 相同之处
    都可以用来重新调整 tensor 的形状。
  • 不同之处
    • view 函数只能用于 contiguous 后的 tensor 上,也就是只能用于内存中连续存储的 tensor。如果对 tensor 调用过 transpose, permute 等操作的话会使该 tensor 在内存中变得不再连续,此时就不能再调用 view 函数。因此,需要先使用 contiguous 来返回一个 contiguous copy。
  • 判断ternsor是否为contiguous,可以调用torch.Tensor.is_contiguous()函数:
import torch 
x = torch.ones(10, 10) 
x.is_contiguous()                                 # True 
x.transpose(0, 1).is_contiguous()                 # False
x.transpose(0, 1).contiguous().is_contiguous()    # True
  • reshape 则不需要依赖目标 tensor 是否在内存中是连续的。
  • 所以
    reshape可以用来替换view
    tensor.contiguous().view() = tensor.reshape()
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]])  
              
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和transpose

转置:行变为列;列变为行.

  • permute:将tensor维度换位
    • 只能用Tensor.permute()
    • 不能用torch.permute()
    • 可以对任意高维矩阵进行转置
    • 参数是desired ordering of dimensions期望的维度顺序
    • 可以理解为,对于一个高维的Tensor执行permute,我们没有改变数据的相对位置,而只是旋转了一下这个(超)立方体。或者也可以说,改变了我们对这个(超)立方体的“观察角度”而已
>>> x = torch.randn(2, 3, 5) 
>>> x.size() 
torch.Size([2, 3, 5]) 
>>> x.permute(2, 0, 1).size() 
torch.Size([5, 2, 3])
  • transpose
    • 只能操作2D矩阵的转置。
    • 有两种调用方式。
    • 连续使用transpose也可实现permute的效果。
t.rand(2,3,4,5).transpose(1,0).transpose(2,1).transpose(3,1).shape
Out[670]: torch.Size([3, 5, 2, 4])

参考

reference

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值