Pytorch中torch.numel(),torch.shape,torch.size()和torch.reshape()函数解析

一. torch.numel()函数解析

1. 官网链接

torch.numel(),如下图所示:
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(),如下图所示:
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]))
  • 15
    点赞
  • 77
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值