一. torch.numel()函数解析
1. 官网链接
torch.numel(),如下图所示:
2. torch.numel()函数解析
torch.numel(input) → int
返回输入张量中元素的总数。
3. 代码举例
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)
二. torch.shape解析
1. torch.shape解析
返回输入tensor张量的维度大小
2. 代码举例
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.size()函数解析
1.torch.size()函数解析
跟torch.shape效果相同,也是返回输入tensor张量的维度大小。
2.代码举例
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()函数解析
1. 官网链接
torch.reshape(),如下图所示:
2. torch.reshape()函数解析
torch.reshape(input, shape) → Tensor
返回将输入的形状转变为shape指定的形状大小,元素总数不变。
3.代码举例
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]))
参考知识文章
网友评论