macs(Multiply–Accumulate Operations)原本是硬件方面的指标,不过近年来深度学习模型运算速度评估的时候也会经常出现,我们可以使用torchprofile
进行计算。 这里我直接使用这个计算torch包里面的自带的模型,具体使用方法如下:
from torchprofile import profile_macs
profile_macs(model,inputs)
复制代码
完整代码如下:
import torch
from torchvision import models
from torchprofile import profile_macs
import os
ls=dir(models)
ls.sort()
res=[]
for i in ls:
if not (i.startswith('_')) and (i!='utils.py'):
res.append(i.split('.')[0])
print(res)
macs_results={}
for i in res:
try:
MACs=profile_macs(eval('models.'+i+'()'),inputs)
macs_results[i]=MACs
except Exception as e:
pass
复制代码
我们可以将结果画出来:
import matplotlib.pyplot as plt
x_x = []
y_y = []
s = sorted(macs_results.items(), key=lambda x: x[1], reverse=False)
for i in s:
x_x.append(i[0])
y_y.append(i[1])
x = x_x
y = y_y
fig, ax = plt.subplots()
ax.barh(x, y, color="deepskyblue")
labels = ax.get_xticklabels()
plt.setp(labels, rotation=0, horizontalalignment='right')
for a, b in zip(x, y):
plt.text(b+1, a, b, ha='center', va='center')
ax.legend(["label"],loc="lower right")
plt.rcParams['font.sans-serif'] = ['SimHei'] # 用来正常显示中文标签
plt.ylabel('model name')
plt.xlabel('MACs')
plt.rcParams['savefig.dpi'] = 300 # 图片像素
plt.rcParams['figure.dpi'] = 300 # 分辨率
plt.rcParams['figure.figsize'] = (20.0, 1.0) # 尺寸
plt.title("models for MACs")
复制代码
结果如下: