在阅读Detectron2的源代码是发现,代码中对模型的配置大量使用了yacs这个模块。 yacs是一个python库,用于为一个系统构建config文件
安装
$ pip install yacs
导入
from yacs.config import CfgNode as CN
使用 创建配置节点 需要创建CN()这个作为容器来装载我们的参数,这个容器可以嵌套
from yacs.config import CfgNode as CN
__C = CN()
__C.name = 'test'
__C.model = CN()
__C.model.backbone = 'resnet'
__C.model.depth = 18
print(__C)
'''
name: test
model:
backbone: resnet
depth: 18
'''
API reference 使用__C 作为创建的配置文件
- clone()
return a copy config file, so the defaults will not be altered
def get_cfg_defaults():
return __C.clone()
- clear()
clear your config file, you will get None as the result
print(__C.clear())
- merge_from_file()
对于不同的模型配置,你有不同的超参设置,所以你可以使用yaml文件来管理不同的configs,然后使用merge_from_file()这个方法,这个会比较每个模型特有的config和默认参数的区别,会将默认参数与特定参数不同的部分,用特定参数覆盖。
__C.merge_from_file("./test_config.yaml")
- merge_from_list()
可以用list来传递参数
from yacs.config import CfgNode as CN
__C = CN()
__C.name = 'test'
__C.model = CN()
__C.model.backbone = 'resnet'
__C.model.depth = 18
print(__C)
'''
model:
backbone: resnet
depth: 18
name: test
'''
opts = ["name", 'test_name', "model.backbone", "vgg"]
__C.merge_from_list(opts)
print(__C)
'''
model:
backbone: vgg
depth: 18
name: test_name
'''
-
merge_from_other_cfg() the same as merge_from_file and merge_from_list, the only difference is that the merged file is also a CfgNode class -
freeze() freeze the configs, and you can not change the value after this operation
from yacs.config import CfgNode as CN
__C = CN()
__C.name = 'test'
__C.model = CN()
__C.model.backbone = 'resnet'
__C.model.depth = 18
__C.freeze()
__C.name = 'test2'
- defrost()
reverse operation of freeze()
from yacs.config import CfgNode as CN
__C = CN()
__C.name = 'test'
__C.model = CN()
__C.model.backbone = 'resnet'
__C.model.depth = 18
__C.freeze()
__C.name = 'test2'
__C.defrost()
__C.name = 'test2'
参考博客:https://zhuanlan.zhihu.com/p/366289700
|