神经网络中FLOPs和MACs的计算(基于thop和fvcore.nn)

输入为(1,1,200,3)的张量

卷积取

nn.Conv2d(1, 64, kernel_size=(8, 1), stride=(2, 1), padding=(0, 0))

为例。

先计算输出的形状

公式为 \frac{n+2p-k}{s}+1

H上为(200+0-8)/2+1=97

W上依然是3

所以输出的形状是(1,64,97,3)

卷积的本质是wx+b,

但是实际计算过程中,是直接w和x一一对应的乘起来,并且将结果都加起来

计算FLOPs时,一般会忽略b,而MACs并不会忽略b

所以对于一个卷积,对应的FLOPs为

97*3*(8*1)*64=148992

而对应的MACs为

97*3*(8*1)*64+97*3*64=167616

后一个97*3*64,就是对应b的数量

用代码计算的话,可以用thop计算MACs,fvcore.nn计算FLOPs

import torch
import torch.nn as nn
import torch.nn.functional as F
from thop import profile
from fvcore.nn import FlopCountAnalysis, parameter_count_table
class net(torch.nn.Module):
    def __init__(self, image_channels=1, n_classes=6):
        super(net, self).__init__()
        self.cnn = nn.Sequential(
            nn.Conv2d(image_channels, 64, kernel_size=(8, 1), stride=(2, 1), padding=(0, 0)),
        )

    def forward(self, x):
        cnn_x = self.cnn(x)
        return cnn_x

model = net()
x = torch.randn(1, 1, 200, 3)

macs, params = profile(model, inputs=(x, ))  # ,verbose=False
print("MACs", macs)
print("p", params)

print("@@@@@@@@@@@@@@")

flops = FlopCountAnalysis(model, x)
print("FLOPs", flops.total())
print(parameter_count_table(model))

打印的结果为

[INFO] Register count_convNd() for <class 'torch.nn.modules.conv.Conv2d'>.
[WARN] Cannot find rule for <class 'torch.nn.modules.container.Sequential'>. Treat it as zero Macs and zero Params.
[WARN] Cannot find rule for <class '__main__.net'>. Treat it as zero Macs and zero Params.
MACs 167616.0
p 576.0
@@@@@@@@@@@@@@
FLOPs 148992
| name            | #elements or shape   |
|:----------------|:---------------------|
| model           | 0.6K                 |
|  cnn            |  0.6K                |
|   cnn.0         |   0.6K               |
|    cnn.0.weight |    (64, 1, 8, 1)     |
|    cnn.0.bias   |    (64,)             |

对应的WARN不用理会,因为这几个类本来就没有计算

其实计算量的判定还有MACCs,MADDs等方法,具体可以参考

CNN的参数量、计算量(FLOPs、MACs)与运行速度_Dr鹏的博客-CSDN博客_模型复杂度

本文参考

网络模型计算量评估_WTHunt的博客-CSDN博客_网络计算量

  • 5
    点赞
  • 19
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值