torch.unsqueeze()函数和torch.squeeze()函数使用举例

参考链接: torch.unsqueeze(input, dim, out=None)
参考链接: torch.squeeze(input, dim=None, out=None)

在这里插入图片描述
说明:

torch.unsqueeze()函数用来在张量的某个位置上增加一个长度为1的维度
注意dim的取值:[-input.dim() - 1, input.dim() + 1)
注意dim=0表示起始的维度,向后依次增加
注意dim=-1表示当前张量末尾维度的再往后一个维度,
并且向前依次减小.

实验代码展示:


(base) C:\Users\chenxuqi>python
Python 3.7.4 (default, Aug  9 2019, 18:34:13) [MSC v.1915 64 bit (AMD64)] :: Anaconda, Inc. on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import torch
>>> input = torch.zeros(2, 3, 4, 5, 6)
>>> input.dim()
5
>>> input.shape
torch.Size([2, 3, 4, 5, 6])
>>> torch.unsqueeze(input, dim=0).shape
torch.Size([1, 2, 3, 4, 5, 6])
>>> input.shape
torch.Size([2, 3, 4, 5, 6])
>>>
>>>
>>> torch.unsqueeze(input, dim=5).shape
torch.Size([2, 3, 4, 5, 6, 1])
>>> input.shape
torch.Size([2, 3, 4, 5, 6])
>>>
>>> torch.unsqueeze(input, dim=6).shape  # 超出范围
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: Dimension out of range (expected to be in range of [-6, 5], but got 6)
>>>
>>> torch.unsqueeze(input, dim=-6).shape
torch.Size([1, 2, 3, 4, 5, 6])
>>> input.shape
torch.Size([2, 3, 4, 5, 6])
>>>
>>> torch.unsqueeze(input, dim=-7).shape  # 超出范围
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: Dimension out of range (expected to be in range of [-6, 5], but got -7)
>>>
>>>
>>>
>>> input.shape
torch.Size([2, 3, 4, 5, 6])
>>> torch.unsqueeze(input, dim=3).shape
torch.Size([2, 3, 4, 1, 5, 6])
>>>
>>> input.shape
torch.Size([2, 3, 4, 5, 6])
>>> torch.unsqueeze(input, dim=-3).shape
torch.Size([2, 3, 4, 1, 5, 6])
>>>
>>>
>>>  

在这里插入图片描述
说明:

功能: 
如果不指明dim那么删去一个张量中所有长度为1的维度,
如果指明dim那么这个维度长度同时是1,那么删去这个维度,
否则不修改原来的张量.

实验代码展示:

(base) PS C:\Users\chenxuqi> python
Python 3.7.4 (default, Aug  9 2019, 18:34:13) [MSC v.1915 64 bit (AMD64)] :: Anaconda, Inc. on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import torch
>>> x = torch.zeros(2, 1, 3, 1, 4, 5, 6, 1, 1, 1, 7)
>>> x.shape
torch.Size([2, 1, 3, 1, 4, 5, 6, 1, 1, 1, 7])
>>> y = torch.squeeze(x)
>>> y.shape
torch.Size([2, 3, 4, 5, 6, 7])
>>>
>>>
>>> x.shape
torch.Size([2, 1, 3, 1, 4, 5, 6, 1, 1, 1, 7])
>>> x.size()
torch.Size([2, 1, 3, 1, 4, 5, 6, 1, 1, 1, 7])
>>>
>>>
>>> y = torch.squeeze(x, 0)
>>> y.size()
torch.Size([2, 1, 3, 1, 4, 5, 6, 1, 1, 1, 7])
>>>
>>> y = torch.squeeze(x, 1)
>>> y.size()
torch.Size([2, 3, 1, 4, 5, 6, 1, 1, 1, 7])
>>>
>>>
>>> torch.squeeze(x, 2).size()
torch.Size([2, 1, 3, 1, 4, 5, 6, 1, 1, 1, 7])
>>>
>>> torch.squeeze(x, 3).size()
torch.Size([2, 1, 3, 4, 5, 6, 1, 1, 1, 7])
>>>
>>>
>>>  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值