- github仓库地址:
https://github.com/rbgirshick/yacs
在做各种实验训练时,如何保证实验的可复现性是一个重要的问题,而一个可复现的实验依赖于:代码+相同的参数配置+其他的依赖(库,硬件)。yacs就是一个用于定义和管理实验配置信息的工具。
1.安装
pip install yacs
2. 使用说明
2.1 建立默认参数文件
建立默认参数文件,通常命名为:config.py
或者default.py
,该文件包含了所有可配置的参数,并为每个参数设置默认值。默认参数需要建立CN()作为容器包含各层参数。
# my_project/config.py
from yacs.config import CfgNode as CN
_C=CN()
_C.SYSTEM=CN()
_C.SYSTEM.NUM_GPUS = 8
_C.SYSTEM.NUM_WORKERS = 4
_C.TRAIN = CN()
_C.TRAIN.HYPERPARAMETER_1 = 0.1
_C.TRAIN.SCALES = (2, 4, 8, 16)
def get_cfg_defaults():
return _C.clone() #局部变量使用形式
#cfg = _C #全局变量使用形式
2.2 创建yaml定制文件
针对每个实验,可配置针对性的配置文件,里面仅记录本次实验时,默认参数文件中修改的参数内容
# my_project/experiment.yaml
SYSTEM:
NUM_GPUS: 2
TRAIN:
SCALES: (1, 2)
2.3 在实验时载入实验参数
# my_project/main.py
from config import get_cfg_defaults # local variable usage pattern, or:
# from config import cfg # global singleton usage pattern
if __name__ == "__main__":
cfg = get_cfg_defaults()
cfg.merge_from_file("experiment.yaml")
cfg.freeze()
print(cfg)
SYSTEM:
NUM_GPUS: 2
NUM_WORKERS: 4
TRAIN:
HYPERPARAMETER_1: 0.1
SCALES: (1, 2)
Process finished with exit code 0
API解释
- 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
cfg.clear()
print(cfg)
- merge_from_file()
对于不同的实验,你有不同的超参设置,所以你可以使用yaml文件来管理不同的configs,然后使用merge_from_file()这个方法,这个会比较每个experiments特有的config和默认参数的区别,会将默认参数与特定参数不同的部分,用特定参数覆盖。
Addition:
- 你需要merge的yaml文件中,不能有default参数中不存在的参数,不然会报错,但是可以比default中设定的参数少,比如default文件中有name参数,这是不需要特定改动的,你可以在yaml中不设置name这个key
# 不报错的情况1:参数和default中一样多,并且层级关系一致
# 不报错的情况2:参数可以比default中少
# my_project/experiment.yaml
SYSTEM:
NUM_GPUS: 2
TRAIN:
SCALES: (1, 2)
# 报错的情况1:以下多了model.batch_normalization这个额外的key,这在default中是不存在的
name: test
model:
backbone: resnet
depth: 29
batch_normalization: True
# 报错的情况2:关键词不一致,这里的关键词是NUM_GPUS,而config中是NUM_gPUS
SYSTEM:
NUM_gPUS: 2
# 报错的情况3:赋值格式不一致,默认参数为float,此处为int
TRAIN:
HYPERPARAMETER_1: 20
- merge_from_list()
也可以使用list修改默认参数,其格式为,[参数名,修改后的变量值]
if __name__ == "__main__":
cfg = get_cfg_defaults()
opts = ["SYSTEM.NUM_GPUS",6,"TRAIN.HYPERPARAMETER_1",20.]
cfg.merge_from_list(opts)
print(cfg)
-
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 -
defrost()
reverse operation of freeze()