一、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()无作用;