在mmdetection的官方文档中,计算参数量和浮点计算数可以使用命令行
python tools/analysis_tools/get_flops.py ${CONFIG_FILE} [--shape ${INPUT_SHAPE}]
但是在最新版本的实际使用中发现,get_flops.py中并没有--shape这个参数了,想要更改输入图片的size我是在代码的95行和99行更改resize后的图片形状为640但是在运行命令行的时候,发现还是会报错
assert isinstance(name, str), AssertionError: type of name should be str, but got <class 'mmengine.utils.manager.ManagerMeta'>
这是因为少了配置文件config中少了参数default_scope,可以直接在你使用的配置文件中加上这个参数,同时注意使用的config是最原始设置的文件,不是运行之后生成在你设置的文件夹里面的配置文件,因为生成的配置文件不完整.
default_scope = 'mmdet'
以我的命令行为例,之后运行
python tools/analysis_tools/get_flops.py E:/GoogleDownload/mmdetection-main/mmdet/configs/detr/detr_r18_8xb2_500e_coco.py
会得到参数量和浮点计算数的结果.
但是注意最后一句: !!!Please be cautious if you use the results in papers. You may need to check if all ops are supported and verify that the flops computation is correct.这个结果不保证完全正确,写进论文的话还要谨慎!!!!!
这里可以引入一个库calflops,我在使用后发现这个计算的较为准确
首先pip安装两个库
pip install calflops
pip install transformers
然后在get_flops.py中直接添加代码并将结果加入到result中,为了避免变量重名可以稍微修改加个后缀:
imageshape = (1, 3, 640, 640)
flops1, macs1, params1 = calculate_flops(model=model, input_shape=imageshape, output_as_string=True,
output_precision=4, print_detailed=False)
result['flops1'] = flops1
result['macs1'] = macs1
result['params1'] = params1
最后在main函数中加入以下代码就能输出准确的结果了
flops1 = result['flops1']
macs1 = result['macs1']
params1 = result['params1']
print("Model FLOPs:%s MACs:%s Params:%s \n" % (flops1, macs1, params1))
重新运行命令行得到结果
可以看到计算的结果并不一样,在对照论文中的参数量之后,发现新加入的包计算较为准确.