torch.squeeze()和unsqueeze()

queeze()

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

其中squeeze(0)代表若第一维度值为1则去除第一维度,squeeze(1)代表若第二维度值为1则去除第二维度。

eg1:

a = torch.Tensor(1,3)

print a

tensor([[-1.37,4.56,-3.57]])

print a.squeeze(0)

tensor([-1.37,4.56,-3.57])

print a.squeeze(1)

tensor([[-1.37,4.56,-3.57]])

eg2:

b = torch.Tensor(2,3)

print b

tensor([[-3.17,3.09,1.43],
[0.00,0.00,0.00]])

print b.squeeze(0)

tensor([[-3.17,3.09,1.43],
[0.00,0.00,0.00]])

print b.squeeze(1)

tensor([[-3.17,3.09,1.43],
[0.00,0.00,0.00]])

eg3:

c = torch.Tensor(3,1)

print c

tensor([[-3.54],
[3.09],
[0.00]])

print c.squeeze(0)

tensor([[-3.54],
[3.09],
[0.00]])

print c.squeeze(1)

tensor([-3.54,3.09,0.00])

unsqueeze()

函数功能:与squeeze()函数功能相反,用于添加维度。

eg:

g = torch.Tensor(3)

print g

tensor([3.27,4.56,-4.84])

print g.unsqueeze(0)

tensor([[3.27,4.56,-4.84]])

print g.unsqueeze(1)

tensor([[3.27],
[4.56],
[-4.84]])

print g.unsqueeze() 必须指明维度

你可能感兴趣的:(PyTorch学习)