PyTorch中的squeeze()和unsqueeze()的介绍

一、unsqueeze

        squeeze在的中文意思压缩,unsqueeze取消压缩,unsqueeze是添加维度的意思,它的具体用法如下面代码

        当unsqueeze()里面参数是0 的时候,该矩阵由(3,4)变成是(3,4,1)

import torch

a1 = torch.arange(0,12).view(3,4)
print(a1.shape)
print(a1)

# torch.Size([3, 4])
# tensor([[ 0,  1,  2,  3],
#         [ 4,  5,  6,  7],
#         [ 8,  9, 10, 11]])

a2 =a1.unsqueeze(0)
print(a2.shape)
print(a2)

# torch.Size([1, 3, 4])
# tensor([[[ 0,  1,  2,  3],
#          [ 4,  5,  6,  7],
#          [ 8,  9, 10, 11]]])

当unsqueeze()函数的参数是1的时候,,该矩阵由(3,4)变成了3,4,1)
 


a2 =a1.unsqueeze(1)
print(a2.shape)
print(a2)

# torch.Size([3, 1, 4])
# tensor([[[ 0,  1,  2,  3]],
#
#         [[ 4,  5,  6,  7]],
#
#         [[ 8,  9, 10, 11]]])

 当unsqueeze()函数的参数是2的时候,,该矩阵由(3,4)变成了(3,4,1)


a2 =a1.unsqueeze(2)
print(a2.shape)
print(a2)
# 
# torch.Size([3, 4, 1])
# tensor([[[ 0],
#          [ 1],
#          [ 2],
#          [ 3]],
# 
#         [[ 4],
#          [ 5],
#          [ 6],
#          [ 7]],
# 
#         [[ 8],
#          [ 9],
#          [10],

当unsqueeze()函数的参数是3的时候,就会报下列出错误


a2 =a1.unsqueeze(3)
print(a2.shape)
print(a2)
# Traceback (most recent call last):
#   File "C:/Users/yiwan/Desktop/Hornet/test/test01.py", line 12, in <module>
#     a2 =a1.unsqueeze(3)
# IndexError: Dimension out of range (expected to be in range of [-3, 2], but got 3)
# 

 它的意思是IndexError:维度超出范围(应在[-3,2]的范围内,但得到了3)#,同理,unsqueeze()里面的参数-1-2-3,它得到的数据和上述一样

a2 =a1.unsqueeze(-3)
print(a2.shape)
print(a2)
# torch.Size([1, 3, 4])
# tensor([[[ 0,  1,  2,  3],
#          [ 4,  5,  6,  7],
#          [ 8,  9, 10, 11]]])
# torch.Size([3, 4])

 -3对应的是0,-2对应的是1,-1对应的是3

二、squeeze()

    squeeze是压缩的意思,就是降低维度,squeeze()函数智能压缩维度为1的矩阵,比如[3,4,1] ,[1,3,4],[3,1,4]智能压缩里面维度是1的,其他的情况并不能压缩。

a3 = a2.squeeze()
print(a3.shape)
print(a3)

# torch.Size([3, 4])
# tensor([[ 0,  1,  2,  3],
#         [ 4,  5,  6,  7],
#         [ 8,  9, 10, 11]])

去除size为1的维度,包括行和列。当维度大于等于2时,squeeze()无作用;

  • 7
    点赞
  • 30
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值