torch.squeeze()
这个函数主要对数据的维度进行压缩,去掉维数为1的的维度,比如是一行或者一列这种,一个一行三列(1,3)的数去掉第一个维数为一的维度之后就变成(3)行。squeeze(a)就是将a中所有为1的维度删掉。不为1的维度没有影响。a.squeeze(N) 就是去掉a中指定的维数为一的维度。还有一种形式就是b=torch.squeeze(a,N) a中去掉指定的定的维数为一的维度。
这个函数主要是对数据维度进行扩充。给指定位置加上维数为一的维度,比如原本有个三行的数据(3),在0的位置加了一维就变成一行三列(1,3)。a.squeeze(N) 就是在a中指定位置N加上一个维数为1的维度。还有一种形式就是b=torch.squeeze(a,N) a就是在a中指定位置N加上一个维数为1的维度
a
tensor([[[-0.1313, -1.0998, -1.9624]]])
torch.Size([1, 1, 3])
tensor([-0.1313, -1.0998, -1.9624])
torch.Size([3])
tensor([[-0.1313, -1.0998, -1.9624]])
torch.Size([1, 3])
tensor([[-0.1313, -1.0998, -1.9624]])
torch.Size([1, 3])
tensor([[[-0.1313, -1.0998, -1.9624]]])
torch.Size([1, 1, 3])
注意,这里只能去掉维数为1的的维度,如果我们随机生成2x3x4的矩阵,则无效
a=torch.randn(2,3,4)
print(a,"n",a.shape,"n")
b=torch.squeeze(a)
print(b,"n",b.shape,"n")
c=torch.squeeze(a,0)
print(c,"n",c.shape,"n")
d=torch.squeeze(a,1)
print(d,"n",d.shape,"n")
e=torch.squeeze(a,2)#如果去掉第三维,则数不够放了,所以直接保留
print(e,"n",e.shape,"n")
tensor([[[-0.3312, -0.3903, 0.3732, -0.0094],
[-1.2595, 0.7815, -0.5044, 0.4635],
[ 0.3063, 0.8799, -1.4904, -1.1514]],
[[-0.4506, -1.0506, -2.0797, -0.3425],
[ 1.9772, -0.4648, 0.2649, 0.8535],
[-0.4897, -0.4739, -0.4632, -0.4432]]])
torch.Size([2, 3, 4])
tensor([[[-0.3312, -0.3903, 0.3732, -0.0094],
[-1.2595, 0.7815, -0.5044, 0.4635],
[ 0.3063, 0.8799, -1.4904, -1.1514]],
[[-0.4506, -1.0506, -2.0797, -0.3425],
[ 1.9772, -0.4648, 0.2649, 0.8535],
[-0.4897, -0.4739, -0.4632, -0.4432]]])
torch.Size([2, 3, 4])
tensor([[[-0.3312, -0.3903, 0.3732, -0.0094],
[-1.2595, 0.7815, -0.5044, 0.4635],
[ 0.3063, 0.8799, -1.4904, -1.1514]],
[[-0.4506, -1.0506, -2.0797, -0.3425],
[ 1.9772, -0.4648, 0.2649, 0.8535],
[-0.4897, -0.4739, -0.4632, -0.4432]]])
torch.Size([2, 3, 4])
tensor([[[-0.3312, -0.3903, 0.3732, -0.0094],
[-1.2595, 0.7815, -0.5044, 0.4635],
[ 0.3063, 0.8799, -1.4904, -1.1514]],
[[-0.4506, -1.0506, -2.0797, -0.3425],
[ 1.9772, -0.4648, 0.2649, 0.8535],
[-0.4897, -0.4739, -0.4632, -0.4432]]])
torch.Size([2, 3, 4])
tensor([[[-0.3312, -0.3903, 0.3732, -0.0094],
[-1.2595, 0.7815, -0.5044, 0.4635],
[ 0.3063, 0.8799, -1.4904, -1.1514]],
[[-0.4506, -1.0506, -2.0797, -0.3425],
[ 1.9772, -0.4648, 0.2649, 0.8535],
[-0.4897, -0.4739, -0.4632, -0.4432]]])
torch.Size([2, 3, 4])
a=torch.randn(1,3)
print(a,"n",a.shape,"n")
b=torch.unsqueeze(a,0)
print(b,"n",b.shape,"n")
c=torch.unsqueeze(a,1)
print(c,"n",c.shape,"n")
d=torch.unsqueeze(a,2)
print(d,"n",d.shape,"n")
tensor([[-0.3519, -0.3158, 1.1978]])
torch.Size([1, 3])
tensor([[[-0.3519, -0.3158, 1.1978]]])
torch.Size([1, 1, 3])
tensor([[[-0.3519, -0.3158, 1.1978]]])
torch.Size([1, 1, 3])
tensor([[[-0.3519],
[-0.3158],
[ 1.1978]]])
torch.Size([1, 3, 1])