squeeze和unsqueeze

1.unqueeze-指定dim添加一个维度

import torch
# 创建一个3X3的tensor
a = torch.tensor([[1, 2, 3], 
                  [4, 5, 6], 
                  [7, 8, 9]])
a.shape

torch.Size([3, 3])

# dim的范围在[-input.dim() - 1, input.dim() + 1), 左闭右开区间,如果dim是负数,dim = dim + input.dim() + 1.

b0 = a.unsqueeze(0) # 相当于:a.unsqueeze(-3)  # dim = -3 + 2 + 1 =0
b1 = a.unsqueeze(1) # 相当于:a.unsqueeze(-2)  # dim = -2 + 2 + 1 =1
b2 = a.unsqueeze(2) # 相当于:a.unsqueeze(-1) # dim = -1 + 2 + 1 =2

b0.shape, b1.shape, b2.shape

(torch.Size([1, 3, 3]), torch.Size([3, 1, 3]), torch.Size([3, 3, 1]))

2.squeeze-指定dim减少一个维度

# 我们再给所有b*的dim=1加一个维度
b00 = b0.unsqueeze(1) 
b11 = b1.unsqueeze(1) 
b22 = b2.unsqueeze(1) 

b00.shape, b11.shape, b22.shape, 

(torch.Size([1, 1, 3, 3]), torch.Size([3, 1, 1, 3]), torch.Size([3, 1, 3, 1]))

# dim为空时, 去除所有为1的维度
c0 = b00.squeeze()
c1 = b11.squeeze()
c2 = b22.squeeze()

c0.shape, c1.shape, c2.shape

(torch.Size([3, 3]), torch.Size([3, 3]), torch.Size([3, 3]))

# dim为不为空时, 去除指定的dim=1的维度
# 以 b22(torch.Size([3, 1, 3, 1]))) 为例
d0 = b22.squeeze(0)  # 不变
d1 = b22.squeeze(1)  #  维度减少
d2 = b22.squeeze(2)  # 不变
d3 = b22.squeeze(3)  #  维度减少
d4 = b22.squeeze(-3)
d0.shape, d1.shape, d2.shape, d3.shape, d4.shape

(torch.Size([3, 1, 3, 1]),
torch.Size([3, 3, 1]),
torch.Size([3, 1, 3, 1]),
torch.Size([3, 1, 3]),
torch.Size([3, 3, 1]))

>>> x = torch.zeros(2, 1, 2, 1, 2)
>>> x.size()
torch.Size([2, 1, 2, 1, 2])
>>> y = torch.squeeze(x)
>>> y.size()
torch.Size([2, 2, 2])
>>> y = torch.squeeze(x, 0)
>>> y.size()
torch.Size([2, 1, 2, 1, 2])
>>> y = torch.squeeze(x, 1)
>>> y.size()
torch.Size([2, 2, 1, 2])
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值