hydra compos 和 yaml defaults

hydra

Hydra 是一个开源 Python 框架,可简化研究和其他复杂应用程序的开发。
关键特性是能够通过组合动态创建分层配置,并通过配置文件和命令行覆盖它。 Hydra 这个名字来源于它能够运行多个类似的工作——就像一个有多个头的 Hydra。简单来讲,就是管理yaml config配置文件的,hydra配合配置文件.yaml可以实现不使用命令行来运行代码。

1. initialize_config_module

初始化hydra,设定搜寻yaml文件的路径, 此路径为工程下nndet文件夹下conf文件夹

initialize_config_module(config_module="nndet.conf")

2. compose api

其等价于@hydra_main方法,在无法使用命令行的时候使用compose代替

cfg = compose(config_name="config", overrides=["db=mysql", "db.user=me"])

yaml语法

yaml目录结构如下:

config
├── prep
│   └── process.yaml
└── train
│	└── augument
|	|    └── base_more.yaml
│	└── v001.yaml
└── config.yaml

v001.yaml:

defaults:
  - augmentation: base_more

module: RetinaUNetV001
predictor: BoxPredictorSelective

plan: D3V001_3d # plan used for training
planner: D3V001 # planner used for preprocessing

base_more.yaml:

name: "base_more"
transforms: "BaseMoreAug"
transforms_kwargs: {}

selected_data_channels:
selected_seg_channels:

p_eldef: 0.2
do_elastic: False
elastic_deform_alpha: [0., 900.]
elastic_deform_sigma: [9., 13.]

process.yaml

# set this to 1 if you want to override cropped data
overwrite: False

crop: True
analyze: True
plan: True
process: True

1. defaults关键字

defaults关键字一般放在yaml的最前面,表示需要递归读取的顺序,如有文件嵌套的情况,其读取的顺序为深度优先遍历。
首先,程序使用compose api读取config.yaml文件:

cfg = compose(config_name='config.yaml') # yaml 在程序文件目录下config_path可以为空或者'',如果在同级文件夹floder中的话 config_path='floder'

config.yaml中:

defaults:
    - _self_
    - train: v001
    - prep: process

exp:
  tag: ""
  fold: 0
  id: ${module}_${plan}${exp.tag}

train:
  mode: "overwrite" # can be either `overwrite` or `resume`
  val_test: True # run testing on validation data to get final training results

程序读取到defaults关键字,defaults中首先是__self__,故先将config文件中信息读入,config文件中其他信息读取完毕后,接着读取train目录下的v001.yaml文件(self后面是train:v001),读取该文件中defaults关键字,直到每一个文件的内容都读取完毕结束,compose api返回值为:

config.yaml->train/v001.yaml->augumentation/base_more.yaml->prep/process.yaml
posted @ 2023-03-03 14:18  while(1){happiness;}  阅读(508)  评论(0)    收藏  举报