iis服务器助手广告广告
返回顶部
首页 > 资讯 > 精选 >pytorch怎么获得模型的计算量和参数量
  • 227
分享到

pytorch怎么获得模型的计算量和参数量

2023-06-15 07:06:50 227人浏览 泡泡鱼
摘要

这篇文章给大家分享的是有关PyTorch怎么获得模型的计算量和参数量的内容。小编觉得挺实用的,因此分享给大家做个参考,一起跟随小编过来看看吧。方法1 自带pytorch自带方法,计算模型参数总量total = sum([

这篇文章给大家分享的是有关PyTorch怎么获得模型的计算量和参数量的内容。小编觉得挺实用的,因此分享给大家做个参考,一起跟随小编过来看看吧。

方法1 自带

pytorch自带方法,计算模型参数总量

total = sum([param.nelement() for param in model.parameters()])print("Number of parameter: %.2fM" % (total/1e6))

或者

total = sum(p.numel() for p in model.parameters())print("Total params: %.2fM" % (total/1e6))

方法2 编写代码

计算模型参数总量和模型计算量

def count_params(model, input_size=224):    # param_sum = 0    with open('models.txt', 'w') as fm:        fm.write(str(model))     # 计算模型的计算量    calc_flops(model, input_size)     # 计算模型的参数总量    model_parameters = filter(lambda p: p.requires_grad, model.parameters())    params = sum([np.prod(p.size()) for p in model_parameters])     print('The network has {} params.'.fORMat(params))  # 计算模型的计算量def calc_flops(model, input_size):     def conv_hook(self, input, output):        batch_size, input_channels, input_height, input_width = input[0].size()        output_channels, output_height, output_width = output[0].size()         kernel_ops = self.kernel_size[0] * self.kernel_size[1] * (self.in_channels / self.groups) * (            2 if multiply_adds else 1)        bias_ops = 1 if self.bias is not None else 0         params = output_channels * (kernel_ops + bias_ops)        flops = batch_size * params * output_height * output_width         list_conv.append(flops)     def linear_hook(self, input, output):        batch_size = input[0].size(0) if input[0].dim() == 2 else 1         weight_ops = self.weight.nelement() * (2 if multiply_adds else 1)        bias_ops = self.bias.nelement()         flops = batch_size * (weight_ops + bias_ops)        list_linear.append(flops)     def bn_hook(self, input, output):        list_bn.append(input[0].nelement())     def relu_hook(self, input, output):        list_relu.append(input[0].nelement())     def pooling_hook(self, input, output):        batch_size, input_channels, input_height, input_width = input[0].size()        output_channels, output_height, output_width = output[0].size()         kernel_ops = self.kernel_size * self.kernel_size        bias_ops = 0        params = output_channels * (kernel_ops + bias_ops)        flops = batch_size * params * output_height * output_width         list_pooling.append(flops)     def foo(net):        childrens = list(net.children())        if not childrens:            if isinstance(net, torch.nn.Conv2d):                net.reGISter_forward_hook(conv_hook)            if isinstance(net, torch.nn.Linear):                net.register_forward_hook(linear_hook)            if isinstance(net, torch.nn.BatchNorm2d):                net.register_forward_hook(bn_hook)            if isinstance(net, torch.nn.ReLU):                net.register_forward_hook(relu_hook)            if isinstance(net, torch.nn.MaxPool2d) or isinstance(net, torch.nn.AvgPool2d):                net.register_forward_hook(pooling_hook)            return        for c in childrens:            foo(c)     multiply_adds = False    list_conv, list_bn, list_relu, list_linear, list_pooling = [], [], [], [], []    foo(model)    if '0.4.' in torch.__version__:        if assets.USE_GPU:            input = torch.cuda.FloatTensor(torch.rand(2, 3, input_size, input_size).cuda())        else:            input = torch.FloatTensor(torch.rand(2, 3, input_size, input_size))    else:        input = Variable(torch.rand(2, 3, input_size, input_size), requires_grad=True)    _ = model(input)     total_flops = (sum(list_conv) + sum(list_linear) + sum(list_bn) + sum(list_relu) + sum(list_pooling))     print('  + Number of FLOPs: %.2fM' % (total_flops / 1e6 / 2))

方法3 thop

需要安装thop

pip install thop

调用方法:计算模型参数总量和模型计算量,而且会打印每一层网络的具体信息

from thop import profile input = torch.randn(1, 3, 224, 224)flops, params = profile(model, inputs=(input,))print(flops)print(params)

或者

from torchvision.models import resnet50from thop import profile # model = resnet50()checkpoints = '模型path'model = torch.load(checkpoints)model_name = 'yolov3 cut asff'input = torch.randn(1, 3, 224, 224)flops, params = profile(model, inputs=(input, ),verbose=True)print("%s | %.2f | %.2f" % (model_name, params / (1000 ** 2), flops / (1000 ** 3)))#这里除以1000的平方,是为了化成M的单位,

注意:输入必须是四维的

提高输出可读性, 加入一下代码。

from thop import clever_formatMacs, params = clever_format([flops, params], "%.3f")

方法4 torchstat

from torchstat import statfrom torchvision.models import resnet50, resnet101, resnet152, resnext101_32x8d model = resnet50()stat(model, (3, 224, 224))  #  (3,224,224)表示输入图片的尺寸

使用torchstat这个库来查看网络模型的一些信息,包括总的参数量params、MAdd、显卡内存占用量和FLOPs等。需要安装torchstat:

pip install torchstat

方法5 ptflops

作用:计算模型参数总量和模型计算量

安装方法:pip install ptflops

或者

pip install --upgrade git+https://GitHub.com/sovrasov/flops-counter.pytorch.git

使用方法

import torchvision.models as modelsimport torchfrom ptflops import get_model_complexity_infowith torch.cuda.device(0):  net = models.resnet18()  flops, params = get_model_complexity_info(net, (3, 224, 224), as_strings=True, print_per_layer_stat=True) #不用写batch_size大小,默认batch_size=1  print('Flops:  ' + flops)  print('Params: ' + params)

或者

from torchvision.models import resnet50import torchimport torchvision.models as models# import torchfrom ptflops import get_model_complexity_info # model = models.resnet50()   #调用官方的模型,checkpoints = '自己模型的path'model = torch.load(checkpoints)model_name = 'yolov3 cut'flops, params = get_model_complexity_info(model, (3,320,320),as_strings=True,print_per_layer_stat=True)print("%s |%s |%s" % (model_name,flops,params))

注意,这里输入一定是要tuple类型,且不需要输入batch,直接输入输入通道数量与尺寸,如(3,320,320) 320为网络输入尺寸。

输出为网络模型的总参数量(单位M,即百万)与计算量(单位G,即十亿)

方法6 torchsummary

安装:pip install torchsummary

使用方法:

from torchsummary import summary...summary(your_model, input_size=(channels, H, W))

作用:

每一层的类型、shape 和 参数量

模型整体的参数量

模型大小,和 fp/bp 一次需要的内存大小,可以用来估计最佳 batch_size

补充:pytorch计算模型算力与参数大小

ptflops介绍

官方链接

这个脚本设计用于计算卷积神经网络中乘法-加法操作的理论数量。它还可以计算参数的数量和打印给定网络的每层计算成本。

支持layer:Conv1d/2d/3D,ConvTranspose2d,BatchNorm1d/2d/3d,激活(ReLU, PReLU, ELU, ReLU6, LeakyReLU),Linear,Upsample,Poolings (AvgPool1d/2d/3d、MaxPool1d/2d/3d、adaptive ones)

安装要求:Pytorch >= 0.4.1, torchvision >= 0.2.1

get_model_complexity_info()

get_model_complexity_info是ptflops下的一个方法,可以计算出网络的算力与模型参数大小,并且可以输出每层的算力消耗。

栗子

以输出Mobilenet_v2算力信息为例:

from ptflops import get_model_complexity_infofrom torchvision import modelsnet = models.mobilenet_v2()ops, params = get_model_complexity_info(net, (3, 224, 224), as_strings=True, print_per_layer_stat=True, verbose=True)

pytorch怎么获得模型的计算量和参数量

从图中可以看到,MobileNetV2在输入图像尺寸为(3, 224, 224)的情况下将会产生3.505MB的参数,算力消耗为0.32G,同时还打印出了每个层所占用的算力,权重参数数量。当然,整个模型的算力大小与模型大小也被存到了变量ops与params中。

感谢各位的阅读!关于“pytorch怎么获得模型的计算量和参数量”这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,让大家可以学到更多知识,如果觉得文章不错,可以把它分享出去让更多的人看到吧!

--结束END--

本文标题: pytorch怎么获得模型的计算量和参数量

本文链接: https://www.lsjlt.com/news/278638.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
  • pytorch怎么获得模型的计算量和参数量
    这篇文章给大家分享的是有关pytorch怎么获得模型的计算量和参数量的内容。小编觉得挺实用的,因此分享给大家做个参考,一起跟随小编过来看看吧。方法1 自带pytorch自带方法,计算模型参数总量total = sum([...
    99+
    2023-06-15
  • pytorch如何获得模型的计算量和参数量
    方法1 自带 pytorch自带方法,计算模型参数总量 total = sum([param.nelement() for param in model.parameters()...
    99+
    2024-04-02
  • Pytorch 统计模型参数量的操作 param.numel()
    param.numel() 返回param中元素的数量 统计模型参数量 num_params = sum(param.numel() for param in net.para...
    99+
    2024-04-02
  • 如何在Pytorch中操作统计模型参数量
    本篇文章为大家展示了如何在Pytorch中操作统计模型参数量,内容简明扼要并且容易理解,绝对能使你眼前一亮,通过这篇文章的详细介绍希望你能有所收获。param.numel()返回param中元素的数量统计模型参数量num_params&nb...
    99+
    2023-06-15
  • Pytorch怎么统计参数网络参数数量
    这篇文章主要介绍了Pytorch怎么统计参数网络参数数量的相关知识,内容详细易懂,操作简单快捷,具有一定借鉴价值,相信大家阅读完这篇Pytorch怎么统计参数网络参数数量文章都会有所收获,下面我们一起来看看吧。Pytorch统计参数网络参数...
    99+
    2023-07-05
  • 关于mmdetection、mmrotate如何计算参数量、计算量和速度FPS
    近几天跑完实验后,发现效果还是不错,于是开始进行模型的参数量、计算量和速度指标的计算对比,话不多说,直接上干货。 ---------------------------------------------------------------...
    99+
    2023-10-20
    python pytorch 深度学习
  • Pytorch训练模型得到输出后计算F1-Score 和AUC的操作
    1、计算F1-Score 对于二分类来说,假设batch size 大小为64的话,那么模型一个batch的输出应该是torch.size([64,2]),所以首先做的是得到这个二维...
    99+
    2024-04-02
  • PyTorch中怎么进行模型的量化
    在PyTorch中,可以使用torch.quantization模块来进行模型的量化。具体步骤如下: 定义模型并加载预训练的模型参...
    99+
    2024-03-05
    PyTorch
  • PyTorch计算损失函数对模型参数的Hessian矩阵示例
    目录前言模型定义求解Hessian矩阵前言 在实现Per-FedAvg的代码时,遇到如下问题: 可以发现,我们需要求损失函数对模型参数的Hessian矩阵。 模型定义 我们定义一个...
    99+
    2024-04-02
  • 怎么调整PyTorch模型的超参数
    调整PyTorch模型的超参数通常包括学习率、批大小、优化器类型、正则化参数等。以下是一些调整超参数的方法: 学习率:学习率决定...
    99+
    2024-03-05
    PyTorch
  • Pytorch模型参数的保存和加载
    目录一、前言二、参数保存三、参数的加载四、保存和加载整个模型五、总结一、前言 在模型训练完成后,我们需要保存模型参数值用于后续的测试过程。由于保存整个模型将耗费大量的存储,故推荐的做...
    99+
    2023-03-11
    Pytorch模型参数保存 Pytorch模型参数加载
  • Pytorch训练模型得到输出后计算F1-Score 和AUC的示例分析
    小编给大家分享一下Pytorch训练模型得到输出后计算F1-Score 和AUC的示例分析,相信大部分人都还不怎么了解,因此分享这篇文章给大家参考一下,希望大家阅读完这篇文章后大有收获,下面让我们一起去了解一下吧!1、计算F1-Score对...
    99+
    2023-06-15
  • java8怎么实现分组计算数量和计算总数
    本篇内容介绍了“java8怎么实现分组计算数量和计算总数”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有所成!java8分组计算数量和计算总数pac...
    99+
    2023-06-20
  • Pandas怎么计算元素的数量和频率
    本篇内容介绍了“Pandas怎么计算元素的数量和频率”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有所成!在pandas.Series的pandas...
    99+
    2023-07-05
  • 怎么在pytorch中查看网络参数总量
    本篇文章为大家展示了怎么在pytorch中查看网络参数总量,内容简明扼要并且容易理解,绝对能使你眼前一亮,通过这篇文章的详细介绍希望你能有所收获。netG = Generator()print('# g...
    99+
    2023-06-15
  • Chainer怎么支持模型量化和轻量化
    Chainer并不直接支持模型量化和轻量化,但可以通过一些方法来实现。 使用深度学习框架的转换工具:可以先使用Chainer训练...
    99+
    2024-04-02
  • CNTK怎么支持模型量化和轻量化
    CNTK(Microsoft Cognitive Toolkit)支持模型量化和轻量化的方法包括以下几种: 使用量化模型训练技术...
    99+
    2024-04-02
  • 怎么获得css元素中的计算样式
    这篇文章主要讲解了“怎么获得css元素中的计算样式”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“怎么获得css元素中的计算样式”吧!要获得css元素中的计算样式(即经过层叠之后,最终的样式)...
    99+
    2023-06-08
  • Python中的变量,参数和模块介绍
    目录前言1 变量2 参数3 模块前言 简单的使用python函数之后,我们在日常开发中还需要经常使用的三个地方,分别是变量、参数和模块。其中,Python的变量类型已经在语法介绍中做...
    99+
    2024-04-02
  • linux中shell怎么计算变量的数值
    这期内容当中小编将会给大家带来有关linux中shell怎么计算变量的数值,文章内容丰富且以专业的角度为大家分析和叙述,阅读完这篇文章希望大家可以有所收获。1、expr命令a=123expr $a + 10&n...
    99+
    2023-06-09
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作