1. 概述
在Detectron2 中,經常對一個類或函數進行注冊,這里舉個例子方便大家理解注冊機制。
from fvcore.common.registry import Registry
# 創建一個Registry對象
registry_machine = Registry('registry_machine')
# 注冊
@registry_machine.register()
def print_hello_world(word):
print(word)
# 其中cfg為所調用的函數名/類名
cfg = "print_hello_world"
# 相當與調用print_hello_world('hello world')
registry_machine.get(cfg)('hello world')
如果創建了一個Registry的對象,並在方法/類定義的時候用裝飾器裝飾它,則可以通過 registry_machine.get(方法名) 來間接調用被注冊的函數
2. 注冊機制的好處
使用注冊機制的好處:代碼的可擴展性變強
對於detectron2這種,需要支持許多不同模型的大型框架,理想情況下所有的模型的參數都希望寫在配置文件中,那問題來了,如果我希望根據我的配置文件,決定我是需要用VGG還是用ResNet ,我要怎么寫?
如果是我,我可能會寫出這種可擴展性超級低的暴搓的代碼:
if class_name == 'VGG':
model = build_VGG(args)
elif class_name == 'ResNet':
model = build_ResNet(args)
但是如果用了注冊類,代碼就是這樣的:
model = model_registry(class_name)(args)
3. 作業
要看懂detectron2中的注冊流程,請先理解以下代碼運行結果
