使用calflops计算网络的模型参数和FLOPs

文章指导如何计算ResNet18模型的FLOPs、MACs和参数,以及处理transformers模块缺失的安装问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

from calflops import calculate_flops
model = models.resnet18()
flops, macs, params =calculate_flops(model=model,
input_shape(1,3,224,224),output_as_string=True,output_precision=4)



如果出现ModuleNotFoundError: No module named 'transformers

请直接 pip install transformer

上面的不是resnet18的参数! 是我随机编的。

### 计算深度学习模型的参数数量 对于卷积神经网络(CNN),参数主要包括卷积核权重其他需要学习的权值。具体来说: - 卷积层中的每个滤波器(即卷积核)都有自己的权重矩阵,以及偏置项。 - 对于全连接层而言,则由输入节点到输出节点之间的连接权重构成。 以AlexNet的第一个卷积层(CONV1)为例,假设该层有96个大小为\(11 \times 11\)且通道数为3的过滤器,并带有bias,则CONV1的总参数量可表示为\[ (11\times11\times3+1)\times96=34944\]这里额外加上了1是因为每一个filter还有一个对应的bias term[^1]。 ### 浮点运算次数(FLOPs) FLOPs代表完成一次正向传播过程中涉及的所有浮点操作的数量。它通常用来评估算法效率硬件需求。针对特定类型的层,比如卷积层,可以按照如下方式估算: 给定一个尺寸为\(H_i\times W_i\)的特征图经过具有\(K_h\times K_w\)感受野、步幅stride s padding p 的卷积处理后得到的新特征图为 \(H_o\times W_o\) ,那么单次卷积操作产生的FLOP数目大约等于\[2\times C_{in}\times C_{out} \times H_k \times W_k \times H_o \times W_o\] 其中因子2来源于每次乘法都会伴随至少一次加法;而当涉及到批量归一化(Batch Normalization)等其他组件时还需进一步增加相应的计算开销[^2]。 回到之前提到的例子,在不考虑激活函数等因素的情况下,如果输入图像分辨率为\(227\times227\)像素,通过上述公式可知CONV1层总的FLOPs约为\[34944\times55\times55=108249600\]。 需要注意的是实际应用中往往还会考虑到更多细节因素来精确统计整个网络架构下的总体FLOPs数值。 ```python def calculate_flops(input_size, kernel_size, output_channels, stride=1, padding=0): """ Calculate the number of floating point operations for a convolutional layer. Args: input_size (tuple): Input feature map size as tuple (height, width). kernel_size (int or tuple): Kernel dimensions either single value or pair (height,width). output_channels (int): Number of filters/output channels. stride (int or tuple, optional): Stride length(s). Defaults to 1. padding (int or str, optional): Padding applied before convolution ('same', 'valid' or int values). Default is no padding. Returns: float: Estimated FLOPs count per forward pass through this conv layer. """ if isinstance(kernel_size,int): kh,kw = kernel_size,kernel_size elif isinstance(kernel_size,(list,tuple)): kh,kw = kernel_size hi,wi=input_size ho=int((hi-kh+(2*padding))/stride)+1 wo=int((wi-kw+(2*padding))/stride)+1 flops_per_conv=(kh*kw)*output_channels*(ho*wo)*2 # Multiply by two because each multiply has an associated add operation return flops_per_conv print(f"FLOPs for Conv Layer with given specs:{calculate_flops((227,227),(11,11),96)}") ```
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值