PyTorch 维度变换-Tensor基本操作

以如下 tensor a 为例,展示常用的维度变换操作

>>> a = torch.rand(4,3,28,28)
>>> a.shape
torch.Size([4, 3, 28, 28])
  • view / reshape 两者功能完全相同: a.view(shape)

    >>> a.view(4,3,28*28)  		## a.view(4,3,28,28) 可恢复
    
  • squeeze / unsqueeze: a.unsqueeze(dim), a.squeeze(dim) 只能挤压 1 维度

    >>> a.unsqueeze(0).shape	## a.squeeze(0) 可恢复
    torch.Size([1, 4, 3, 28, 28])
    
  • transpose / permute:.t() 只能用于二维矩阵

    >>> a.transpose(0,1).shape    ## 两两交换:交换 0 1 维度
    torch.Size([3, 4, 28, 28])
    >>> a.permute(0,1,2,3).shape  ## 新置维度,非两两交换,更方便 
    torch.Size([4, 3, 28, 28])
    
  • expand / repeat 两者效果完全相同 expand 高效更推荐

    >>> a.unsqueeze(0).expand(2,4,3,28,28).shape  # 只能拓展 1 维度的
    torch.Size([2, 4, 3, 28, 28])
    >>> a.unsqueeze(0).repeat(2,1,1,1,1).shape    # 不是填目标维度,而是填每个维度的重复次数   
    torch.Size([2, 4, 3, 28, 28])
    
  • broadcasting 自动扩张:基于已有的小维度的值 自动 进行广播拓展
    在这里插入图片描述

    >>> b = a+torch.tensor(1) 
    >>> b.shape
    torch.Size([4, 3, 28, 28])
    

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值