torch.squeeze()和unsqueeze()

import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim

"""
queeze()

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

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



unsqueeze()

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


"""

a = torch.Tensor(1,3)
print("a的值是{},纬度是{}".format(a,a.shape))
print("a.squeeze(0)的值是")
print(a.squeeze(0),a.squeeze(0).shape)
print("a.squeeze(1)的值是")
print(a.squeeze(1),a.squeeze(1).shape)
b = torch.Tensor(2,3)
print("b的值")
print(b,b.shape)
print("b.squeeze(0)的值是")
print(b.squeeze(0),b.squeeze(0).shape)
print("b.squeeze(1)的值是")
print(b.squeeze(1),b.squeeze(1).shape)
c = torch.Tensor(3,1)
print("c的值")
print(c,c.shape)
print("c.squeeze(0)的值是")
print(c.squeeze(0),c.squeeze(0).shape)
print("c.squeeze(1)的值是")
print(c.squeeze(1),c.squeeze(1).shape)


# unsqueeze()
g = torch.Tensor(3)
print("g的值是")
print(g,g.shape)
print("g.unsqueeze(0)的值是")
print(g.unsqueeze(0),g.unsqueeze(0).shape)
print("g.unsqueeze(1)的值是")
print(g.unsqueeze(1),g.unsqueeze(1).shape)
#print(g.unsqueeze()) 必须指明维度

a的值是tensor([[-5.6855e-05,  4.5915e-41, -5.6855e-05]]),纬度是torch.Size([1, 3])
a.squeeze(0)的值是
tensor([-5.6855e-05,  4.5915e-41, -5.6855e-05]) torch.Size([3])
a.squeeze(1)的值是
tensor([[-5.6855e-05,  4.5915e-41, -5.6855e-05]]) torch.Size([1, 3])
b的值
tensor([[0., 0., 0.],
        [0., 0., 0.]]) torch.Size([2, 3])
b.squeeze(0)的值是
tensor([[0., 0., 0.],
        [0., 0., 0.]]) torch.Size([2, 3])
b.squeeze(1)的值是
tensor([[0., 0., 0.],
        [0., 0., 0.]]) torch.Size([2, 3])
c的值
tensor([[2.3694e-38],
        [3.6013e-43],
        [       nan]]) torch.Size([3, 1])
c.squeeze(0)的值是
tensor([[2.3694e-38],
        [3.6013e-43],
        [       nan]]) torch.Size([3, 1])
c.squeeze(1)的值是
tensor([2.3694e-38, 3.6013e-43,        nan]) torch.Size([3])
g的值是
tensor([0.0000e+00, 9.5405e-06,        nan]) torch.Size([3])
g.unsqueeze(0)的值是
tensor([[0.0000e+00, 9.5405e-06,        nan]]) torch.Size([1, 3])
g.unsqueeze(1)的值是
tensor([[0.0000e+00],
        [9.5405e-06],
        [       nan]]) torch.Size([3, 1])

你可能感兴趣的:(PyTorch简单使用)