【python】torch.squeeze() 和torch.unsqueeze()

关于python的torch.squeeze() 和torch.unsqueeze()

torch.squeeze() 是降维
torch.unsqueeze() 是升维
torch.squeeze() 针对1进行处理,非1不处理,指定是指定位置,不指定去掉所有1
torch.unsqueeze()在指定位置加1维,不指定报错

例1

>>> import torch
>>> x=torch.zeros(2,1,2,1,3)
>>> x.size()
torch.Size([2, 1, 2, 1, 3])
>>> y=torch.squeeze(x,3)
>>> y.size()
torch.Size([2, 1, 2, 3])
>>> y=torch.squeeze(x,4)
>>> y.size()
torch.Size([2, 1, 2, 1, 3])

例2

>>> z=torch.zeros(2,1,4,8,1,3)
>>> z.size()
torch.Size([2, 1, 4, 8, 1, 3])
>>> y1=torch.squeeze(z)
>>> y1.size()
torch.Size([2, 4, 8, 3])
>>> y2=torch.squeeze(z,0)
>>> y2.size()
torch.Size([2, 1, 4, 8, 1, 3])
>>> y2=torch.squeeze(z,1)
>>> y2.size()
torch.Size([2, 4, 8, 1, 3])
>>> y3=torch.squeeze(z,4)
>>> y3.size()
torch.Size([2, 1, 4, 8, 3])
>>> y4=torch.squeeze(z,5)
>>> y4.size()
torch.Size([2, 1, 4, 8, 1, 3])
>>> y4=torch.squeeze(z,3)
>>> y4.size()
torch.Size([2, 1, 4, 8, 1, 3])
>>> y4=torch.squeeze(z,2)
>>> y4.size()
torch.Size([2, 1, 4, 8, 1, 3])
>>> y6=torch.squeeze(z,2)
>>> y6.size()
torch.Size([2, 1, 4, 8, 1, 3])

>>> y6=torch.squeeze(z,2)
>>> y6.size()
torch.Size([2, 1, 4, 8, 1, 3])
>>> y6=torch.unsqueeze(z,0)
>>> y6.size()
torch.Size([1, 2, 1, 4, 8, 1, 3])
>>> y7=torch.unsqueeze(z,1)
>>> y7.size()
torch.Size([2, 1, 1, 4, 8, 1, 3])
>>> y8=torch.unsqueeze(z,-1)
>>> y8.size()
torch.Size([2, 1, 4, 8, 1, 3, 1])

>>> y9=torch.unsqueeze(z,-0)
>>> y9.size()
torch.Size([1, 2, 1, 4, 8, 1, 3])
>>> 
>>> y9=torch.unsqueeze(z,2)
>>> y9.size()
torch.Size([2, 1, 1, 4, 8, 1, 3])
>>> y9=torch.unsqueeze(z,3)
>>> y9.size()
torch.Size([2, 1, 4, 1, 8, 1, 3])

torch.squeeze()多写变量会报错

y6=torch.squeeze(z,2,2)
Traceback (most recent call last):
File “”, line 1, in
TypeError: squeeze() received an invalid combination of arguments - got (Tensor, int, int), but expected one of:* (Tensor input) * (Tensor input, int dim)

torch.unsqueeze()少写指定位置会报错

y8=torch.unsqueeze(z)
Traceback (most recent call last):
File “”, line 1, in
TypeError: unsqueeze() missing 1 required positional arguments: “dim”

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值