深度学习中,模型训练完后,查看模型的参数量和浮点计算量,在此记录下:
在pytorch中有现成的包thop用于计算参数数量和FLOP,首先安装thop:
pip install thop
使用方法如下:
from torchvision.models import resnet50 # 引入ResNet50模型
from thop import profile
model = resnet50()
flops, params = profile(model, input_size=(1, 3, 224,224)) # profile(模型,输入数据)
对于自己构建的函数也一样,例如shuffleNetV2
from thop import profile
from utils.ShuffleNetV2 import shufflenetv2 # 导入shufflenet2 模块
import torch
model_shuffle = shufflenetv2(width_mult=0.5)
model = torch.nn.DataParallel(model_shuffle) # 调用shufflenet2 模型,该模型为自己定义的
flop, para = profile(model, input_size=(1, 3, 224, 224),)
print("%.2fM" % (flop/1e6), "%.2fM" % (para/1e6))
更多细节,可参考thop GitHub链接: https://github.com/Lyken17/pytorch-OpCounter
补充:
pytorch本身带有计算参数的方法
from thop import profile
from utils.ShuffleNetV2 import shufflenetv2 # 导入shufflenet2 模块
import torch
model_shuffle = shufflenetv2(width_mult=0.5)
model = torch.nn.DataParallel(model_shuffle)
total = sum([param.nelement() for param in model.parameters()])
print("Number of parameter: %.2fM" % (total / 1e6))
参考:https://blog.csdn.net/qq_26369907/article/details/89857021
网络代码中__all__
如下:
__all__ = ['SENet', 'senet154', 'se_resnet34', 'se_resnet50', 'se_resnet101', 'se_resnet152', 'se_resnext50_32x4d', 'se_resnext101_32x4d']
__all__
是一个字符串list,用来定义模块中对于from XXX import *
时要对外导出的符号,即要暴露的借口,但它只对import *
起作用,对from XXX import XXX
不起作用。
all.py
文件时要导出的模块,内容如下:
__all__ = ['x', 'y', 'test']
x = 2
y = 3
z = 4
def test():
print('test')
from foo import *
print('x: ', x)
print('y: ', y)
print('z: ', z)
test()
x: 2
y: 3
Traceback (most recent call last):
File "test.py", line 6, in
print('z: ', z)
NameError: name 'z' is not defined