美文网首页
yacs--Python代码运行时的配置系统

yacs--Python代码运行时的配置系统

作者: GA_17 | 来源:发表于2018-03-27 15:59 被阅读0次

    今天瞻仰旷世的Bag-of-tricks的源码, 发现它的配置 管理做的很清晰,所以学习一波.

    参考网页:https://java.ctolib.com/rbgirshick-yacs.html
    yacs有点类似于argparse,只不过用的时候有差别.argparse需要在运行文件中写一堆类似 --input --output_dir 一类的东西, 而yacs写好之后就可以放到别的文档中, 非常方便管理, 也很清晰.
    yacs 使用方法灵活多变, 主要用到两种使用:

    1. 用来指定local variable(Configuration as local variable) ----推荐
    2. 用来指定global singleton(Configuration as a global singleton)

    简单介绍下用法:

    1. 首先需要创建一个config文件, 我们一般将其命名为config.py或者default.py, 我们需要在文件中指定所有默认的configuration options , 文件格式要清晰:
    # my_project/config.py
    from yacs.config import CfgNode as CN
    _C = CN()
    
    _C.MODEL = CN()
    # Using cuda or cpu for training
    _C.MODEL.DEVICE = "cuda"
    # ID number of GPU
    _C.MODEL.DEVICE_ID = '0'
    # Name of backbone
    _C.MODEL.NAME = 'resnet50'
    
    _C.INPUT = CN()
    # Size of the image during training
    _C.INPUT.SIZE_TRAIN = [384, 128]
    # Size of the image during test
    _C.INPUT.SIZE_TEST = [384, 128]
    # Random probability for image horizontal flip
    _C.INPUT.PROB = 0.5
    
    # Misc options
    # ---------------------------------------------------------------------------- #
    # Path to checkpoint and saved log of trained model
    _C.OUTPUT_DIR = ""
    
    def get_cfg_defaults():
      """Get a yacs CfgNode object with default values for my_project."""
      # Return a clone so that the defaults will not be altered
      # This is for the "local variable" use pattern
      return _C.clone()
    
    1. 对于每一次实验, 不同的参数设置我们都需要创建一个YAML configuration files, 这个文件里只需要写出需要改变的参数, 其它的使用config.py里默认的就行了.
    # my_project/experiment.yaml
    INPUT:
      SIZE_TRAIN: [256, 128]
      SIZE_TEST: [256, 128]
    

    这样一来,我们对于每个实验就有了全部的参数配置信息.通常来讲, 我们会在参数设置完之后freeze掉参数, 防止以后发生改变.

    # my_project/main.py
    
    import my_project
    from config import get_cfg  # 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)
    
    1. 除了用这种方式指定实验参数外, 还可以采用在命令行中添加/修改参数的办法;
    cfg.merge_from_file("experiment.yaml")
    # Now override from a list (opts could come from the command line)
    opts = ["SYSTEM.NUM_GPUS", 8, "TRAIN.SCALES", "(1, 2, 3, 4)"]
    cfg.merge_from_list(opts)
    

    相关文章

      网友评论

          本文标题:yacs--Python代码运行时的配置系统

          本文链接:https://www.haomeiwen.com/subject/mdrscftx.html