Pytorch学习基础——torch.squeeze() & torch.unsqueeze()

Pytorch官方API:torch.squeeze()

squeeze()函数功能:

  1. 主要对数据的维度进行压缩(默认为1)。也可以通过dim指定位置,删掉指定位置的维数。

unsqueeze()函数功能:

对数据维度进行扩充。dim指定位置,添加指定位置的维数添加1。

 

常见参数介绍:

  • input(Tensor):输入张量;
  • dim(int, optional):设定(可选)维度;
  • out(Tensor, optional): 张量输出;

 

常见参数(同上)

举例:

import torch
 
x = torch.zeros(3,2,4,1,2,1)# dimension of 3*2*4*1*2
print(x.size())             # torch.Size([3, 2, 4, 1, 2, 1])
print(x.shape)
 
y = torch.squeeze(x)        # Returns a tensor with all the dimensions of input of size 1 removed.
print(y.size())             # torch.Size([3, 2, 4, 2])
print(y.shape)
 
z = torch.unsqueeze(y,dim=0)# Add a dimension of 1 in the 0th position
print(z.size())             # torch.Size([1, 3, 2, 4, 2])
print(z.shape)
 
z = torch.unsqueeze(y,dim=1)# Add a dimension of 1 in the 1st position
print(z.size())             # torch.Size([3, 1, 2, 4, 2])
print(z.shape)
 
z = torch.unsqueeze(y,dim=2)# Add a dimension of 1 in the 2nd position
print(z.size())             # torch.Size([3, 2, 1, 4, 2])
print(z.shape)
 
y = torch.squeeze(x,dim=0)  # remove the 0th position of 1 (no 1)
print('dim=0', y.size())    # torch.Size([3, 2, 4, 1, 2, 1])
print('dim=0', y.shape)
 
y = torch.squeeze(x, dim=1)  # remove the 1st position of 1 (no 1)
print('dim=1', y.size())     # torch.Size([3, 2, 4, 1, 2, 1])
print('dim=1', y.shape)
 
y = torch.squeeze(x, dim=2)  # remove the 2nd position of 1 (no 1)
print('dim=2', y.size())     # torch.Size([3, 2, 4, 1, 2])
print('dim=2', y.shape)
 
y = torch.squeeze(x, dim=3)  # remove the 3rd position of 1 (yes)
print('dim=3', y.size())     # torch.Size([3, 2, 4, 2])
print('dim=3', y.shape)
 
y = torch.squeeze(x, dim=4)  # remove the 4th position of 1 (no 1)
print('dim=4', y.size())     # torch.Size([3, 2, 4, 1, 2, 1])
print('dim=4', y.shape)
 
y = torch.squeeze(x, dim=5)  # remove the 5th position of 1 (yes)
print('dim=5', y.size())     # torch.Size([3, 2, 4, 1, 2])
print('dim=5', y.shape)
 
y = torch.squeeze(x, dim=6)  # RuntimeError: Dimension out of range (expected to be in range of [-6, 5], but got 6)
print('dim=6', y.size())
print('dim=6', y.shape)

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值