torch.numel(input) → int
返回输入张量中元素的总数。
a1 = torch.randn(1, 2, 3, 4, 5)
b = torch.numel(a1)#输入元素总数为1x2x3x4x5=120
a2 = torch.zeros(4,4)
c = torch.numel(a2)#输入元素总数为4x4=16
a3 = torch.randn(size=(5,4))
d = torch.numel(a3)#输入元素总数为5x4=20
a4 = torch.randn(6)
e = torch.numel(a4)#输入元素总数为6
a1.shape,b,a2.shape,c,a3.shape,d,a4.shape,e
输出结果如下:
(torch.Size([1, 2, 3, 4, 5]),
120,
torch.Size([4, 4]),
16,
torch.Size([5, 4]),
20,
torch.Size([6]),
6)
返回输入tensor张量的维度大小
a1 = torch.randn(1, 2, 3, 4, 5)
a2 = torch.randn(size=(5,4))
a1.shape,a2.shape
输出结果如下:
(torch.Size([1, 2, 3, 4, 5]), torch.Size([5, 4]))
跟torch.shape效果相同,也是返回输入tensor张量的维度大小。
a1 = torch.randn(1, 2, 3, 4, 5)
a2 = torch.randn(size=(5,4))
a1.size(),a2.size()
输出结果如下:
(torch.Size([1, 2, 3, 4, 5]), torch.Size([5, 4]))
torch.reshape(input, shape) → Tensor
返回将输入的形状转变为shape指定的形状大小,元素总数不变。
a = torch.zeros(size=(5,4))
b = a.reshape(-1)#输出张量b的size为torch.Size([20])
c = a.reshape(2,-1) #输出张量c的size为torch.Size([2, 10])
d = a.reshape(shape=(2,10)) #输出张量d的size为torch.Size([2, 10])
e = a.reshape(shape=(4,-1))#输出张量e的size为torch.Size([4, 5])
a,a.shape,b,b.shape,c,c.shape,d,d.shape,e,e.shape
输出结果如下:
(tensor([[0., 0., 0., 0.],
[0., 0., 0., 0.],
[0., 0., 0., 0.],
[0., 0., 0., 0.],
[0., 0., 0., 0.]]),
torch.Size([5, 4]),
tensor([0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.]),
torch.Size([20]),
tensor([[0., 0., 0., 0., 0., 0., 0., 0., 0., 0.],
[0., 0., 0., 0., 0., 0., 0., 0., 0., 0.]]),
torch.Size([2, 10]),
tensor([[0., 0., 0., 0., 0., 0., 0., 0., 0., 0.],
[0., 0., 0., 0., 0., 0., 0., 0., 0., 0.]]),
torch.Size([2, 10]),
tensor([[0., 0., 0., 0., 0.],
[0., 0., 0., 0., 0.],
[0., 0., 0., 0., 0.],
[0., 0., 0., 0., 0.]]),
torch.Size([4, 5]))