目录
🍆🍆3.通过thop.profile计算网络参数量和计算效率
🍑🍑1.params、FLOPS、MACs参数定义
🍈params
参数量是指模型训练中需要训练的参数总数。用来衡量模型的大小(计算空间复杂度)。
🍈FLOPS
floating point operations per second的缩写,意指每秒浮点运算次数,理解为计算速度,通常用来计算算法的复杂度。
🍈MACs
Multiply–Accumulate Operations的缩写,1MACs包含一个乘法操作与一个加法操作,大约包含2FLOPs。通常MACs与FLOPs存在一个2倍的关系,通常用来计算算法的复杂度。
🍈使用范围
params通常用来计算空间复杂度;一般情况下ReLU层和Pooling层计算FLOPs,而conv层、FC层,计算MACs数
🍍🍍2.安装thop
安装thop有两种方式。
🏆第一种
直接pip安装
pip install thop
通常第一种方式很难直接安装成功,本人就是怎么都装不好,所以试试第二种方式吧。
🏆第二种
用源码编译安装
源码编译安装步骤如下:
- 从官网下载【github】thop安装压缩包
- 下载压缩文件,解压到虚拟环境的site-packages文件下
- 激活进入自己的虚拟环境
- cd到压缩包解压的路径下
- 输入命令python setup.py install,等待安装完成即可
压缩包解压
setup.py源码如下:
#!/usr/bin/env python
import os, sys
import shutil
import datetime
from setuptools import setup, find_packages
from setuptools.command.install import install
readme = open("README.md").read()
fp = open("thop/__version__.py", "r").read()
VERSION = eval(fp.strip().split()[-1])
requirements = [
"torch",
]
# import subprocess
# commit_hash = subprocess.check_output("git rev-parse HEAD", shell=True).decode('UTF-8').rstrip()
# VERSION += "_" + str(int(commit_hash, 16))[:8]
VERSION += "_" + datetime.datetime.now().strftime("%Y%m%d%H%M")[2:]
print(VERSION)
setup(
# Metadata
name="thop",
version=VERSION,
author="Ligeng Zhu",
author_email="ligeng.zhu+github@gmail.com",
url="https://github.com/Lyken17/pytorch-OpCounter/",
description="A tool to count the FLOPs of PyTorch model.",
long_description=readme,
long_description_content_type="text/markdown",
license="MIT",
# Package info
packages=find_packages(exclude=("*test*",)),
#
zip_safe=True,
install_requires=requirements,
# Classifiers
classifiers=[
"Programming Language :: Python :: 3",
],
)
运行过程稍微有点长,在下载其他的依赖包,耐心等待出现如下页面,看到“Finished processing dependencies for thop==0.11.post2311150925” 这一句就代表成功安装完成了。
🍆🍆3.通过thop.profile计算网络参数量和计算效率
安装完成后即可使用thop库进行网络参数量和效率计算了,以下是一段测试代码 ,如果能成功输出结果就代表成功了,只需要在后续替换成自己的model和输入就可以了 。
🍠测试代码
from torchvision.models import resnet50
import torch
from thop import profile
model = resnet50()
input = torch.randn(1, 3, 224, 224)
macs, params = profile(model, inputs=(input, ))
print(macs)
print(params)
🍠测试代码输出
>>>
>>> from torchvision.models import resnet50
>>> import torch
>>> from thop import profile
>>> model = resnet50()
>>> input = torch.randn(1, 3, 224, 224)
>>> macs, params = profile(model, inputs=(input, ))
[INFO] Register count_convNd() for <class 'torch.nn.modules.conv.Conv2d'>.
[INFO] Register count_normalization() for <class 'torch.nn.modules.batchnorm.BatchNorm2d'>.
[INFO] Register zero_ops() for <class 'torch.nn.modules.activation.ReLU'>.
[INFO] Register zero_ops() for <class 'torch.nn.modules.pooling.MaxPool2d'>.
[INFO] Register zero_ops() for <class 'torch.nn.modules.container.Sequential'>.
[INFO] Register count_adap_avgpool() for <class 'torch.nn.modules.pooling.AdaptiveAvgPool2d'>.
[INFO] Register count_linear() for <class 'torch.nn.modules.linear.Linear'>.
>>> print(macs)
4133742592.0
>>> print(params)
25557032.0
>>>
>>>
🍠代码步骤
- 定义一个自己的网络结构
- 输入一个满足尺寸要求的随机输入
- 随机影像数据输入网络
- 通过profile(model,(input,))进行网络参数量和运行效率算
🍠定义自己的model
比如自己自定义网络Test:
from thop import profile
class Test(nn.Module):
def __init__(self, input_size, output_szie):
super(Test, self).__init__()
self.out = nn.Linear(input_size, output_szie)
def forward(self, x):
output = self.out(x)
return output
t = Test(10, 2)
x = torch.randn(4, 10)
flops,params = profile(t, (x,), verbose=False)
print('FLOPs = ' + str(flops / 1000 ** 3) + 'G')
print('Params = ' + str(params / 1000 ** 2) + 'M')
🍅🍅4.增加输出结果可读性
为了增加结果的可读性,除了自己通过公式进行计算,将结果转换成Gb,Mb或者其他格式的,官网还提供了参数clever_format,可以通过该参数将结果输出成可读性较友好的结果。使用方法如下:
#all thop.clever_format to give a better format of the output.
from thop import clever_format
macs, params = clever_format([macs, params], "%.3f")
输出结果如下:
>>> from thop import clever_format
>>> macs, params = clever_format([macs, params], "%.3f")
>>> print(macs)
4.134G
>>> print(params)
25.557M
此时就不再是一长串的数字,就可以直观换算成可视化较好的单位了。
🌽🌽5.常见网络参数量展示
既然都看到这里了,投个票吧,你学会了吗?
整理不易,欢迎一键三连!!!
送你们一条美丽的--分割线--
🌷🌷🍀🍀🌾🌾🍓🍓🍂🍂🙋🙋🐸🐸🙋🙋💖💖🍌🍌🔔🔔🍉🍉🍭🍭🍋🍋🍇🍇🏆🏆📸📸⛵🍑 🍈 🍌 🍐 🍍 🍠 🍆 🍅 🌽