fvcore是一个易用的工具。fvcore是Facebook开源的一个轻量级的核心库,它提供了各种计算机视觉框架中常见且基本的功能。其中就包括了统计模型的参数以及FLOPs等。
pip install fvcore
注:
- FLOPS:注意全大写,是floating point operations per second的缩写,意指每秒浮点运算次数,理解为计算速度。是一个衡量硬件性能的指标。
- FLOPs:注意s小写,是floating point operations的缩写(s表复数),意指浮点运算数,理解为计算量。可以用来衡量算法/模型的复杂度。
1.计算FLOPs:
import torch
from torchvision.models import resnet50
from fvcore.nn import FlopCountAnalysis, parameter_count_table
# 创建resnet50网络
model = resnet50(num_classes=1000)
# 创建输入网络的tensor
tensor = (torch.rand(1, 3, 224, 224),)
# 分析FLOPs
flops = FlopCountAnalysis(model, tensor)
print("FLOPs: ", flops.total())
2.计算Param:
import torch
from torchvision.models import resnet50
from fvcore.nn import FlopCountAnalysis, parameter_count_table
# 创建resnet50网络
model = resnet50(num_classes=1000)
# 分析parameters
print(parameter_count_table(model))
pytorch官方计算Param:
sum(p.numel() for p in model.parameters() if p.requires_grad)
fvcore中Registry机制:
why registry:原始的方法来调用方法or函数,需要寻找函数在哪个文件/类里,如果框架里的算法很多,这样找来找去会很麻烦,于是就可以利用Registry机制来简化这个过程:将字符串命名与对象(Object)建立一对一的映射关系,也就是将名字与算法模型建立一一对应关系。然后我下次要调用这个算法的时候,我就不需要管这个算法被写在哪个地方了,直接调用这个名字即可。
使用方法:
1.实例化Registry类:
from detectron2.utils.registry import Registry
#或者用:from fvcore.common import registry
OBGECT_DETECTION_REGISTRY = Registry("object_detection")
2.将算法实现代码与名字建立映射关系
# method1:
@OBGECT_DETECTION_REGISTRY.register()
class MyAlgorithm():
pass
# method2:
class MyAlgorithm():
pass
OBGECT_DETECTION_REGISTRY.register(MyAlgorithm)
3.调用算法
model = OBGECT_DETECTION_REGISTRY.get(MyAlgorithm)(cfg)
#其中的cfg是初始化算法需要传入的参数