您好,登錄后才能下訂單哦!
今天就跟大家聊聊有關(guān)Detectron2注冊(cè)機(jī)制Registry實(shí)現(xiàn)的示例分析,可能很多人都不太了解,為了讓大家更加了解,小編給大家總結(jié)了以下內(nèi)容,希望大家根據(jù)這篇文章可以有所收獲。
在Detectron2 中,經(jīng)常會(huì)對(duì)一個(gè)類或者函數(shù)進(jìn)行注冊(cè):
關(guān)于這種操作,必須要明確兩點(diǎn):
registry_machine = Registry('registry_machine')
registry_machine.register()
def print_hello_world(word):
print('hello {}'.format(word))
registry_machine.register()
def print_hi_world(word):
print('hi {}'.format(word))
if __name__ == '__main__':
cfg1 = 'print_hello_word'
registry_machine.get(cfg1)('world')
cfg2 = 'print_hi_word'
registry_machine.get(cfg2)('world')
可以看到,如果創(chuàng)建了一個(gè)Registry的對(duì)象,并在方法/類定義的時(shí)候用裝飾器裝飾它,則可以通過 registry_machine.get(方法名)的 辦法來間接的調(diào)用被注冊(cè)的函數(shù)
如果是我,我可能會(huì)寫出這種可擴(kuò)展性超級(jí)低的暴搓的代碼:
if class_name == 'VGG': model = build_VGG(args)elif class_name == 'ResNet': model = build_ResNet(args)
但是如果用了注冊(cè)類,代碼就是這樣的:
class_name = 'VGG' # 'ResNet'model = model_registry(class_name)(args)
可以看到代碼的可擴(kuò)展性變得非常強(qiáng)了
這部分就直接展示注冊(cè)類的代碼了,有興趣的朋友可以研究一下其中的細(xì)節(jié),個(gè)人覺得對(duì)裝飾器的應(yīng)用是非常的好了
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
class Registry(object):
def __init__(self, name):
"""
Args:
name (str): the name of this registry
"""
self._name = name
self._obj_map = {}
def _do_register(self, name, obj):
assert (
name not in self._obj_map
), "An object named '{}' was already registered in '{}' registry!".format(name, self._name)
self._obj_map[name] = obj
def register(self, obj=None):
"""
Register the given object under the the name `obj.__name__`.
Can be used as either a decorator or not. See docstring of this class for usage.
"""
if obj is None:
# used as a decorator
def deco(func_or_class):
name = func_or_class.__name__
self._do_register(name, func_or_class)
return func_or_class
return deco
# used as a function call
name = obj.__name__
self._do_register(name, obj)
def get(self, name):
ret = self._obj_map.get(name)
if ret is None:
raise KeyError("No object named '{}' found in '{}' registry!".format(name, self._name))
return ret
registry_machine = Registry('registry_machine')
registry_machine.register()
def print_hello_world(word):
print('hello {}'.format(word))
registry_machine.register()
def print_hi_world(word):
print('hi {}'.format(word))
if __name__ == '__main__':
cfg1 = 'print_hello_word'
registry_machine.get(cfg1)('world')
cfg2 = 'print_hi_word'
registry_machine.get(cfg2)('world')
看完上述內(nèi)容,你們對(duì)Detectron2注冊(cè)機(jī)制Registry實(shí)現(xiàn)的示例分析有進(jìn)一步的了解嗎?如果還想了解更多知識(shí)或者相關(guān)內(nèi)容,請(qǐng)關(guān)注億速云行業(yè)資訊頻道,感謝大家的支持。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。