You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用OmegaConf递归加载结构化文件夹中的YAML配置文件?

使用OmegaConf递归加载YAML配置文件

文件结构

configs
├── experiment
│   └── test.yaml
└── default.yaml

配置文件内容

default.yaml:

experiment: test.yaml

test.yaml:

learning_rate: 0.1

问题描述

执行以下代码后,conf仅包含experiment: test.yaml,并未递归加载test.yaml中的learning_rate参数:

from omegaconf import DictConfig, OmegaConf
conf = OmegaConf.load("configs/default.yaml")

解决方法

方法1:使用OmegaConf插值语法(推荐)

修改default.yaml,通过${file:}插值语法指定要加载的子配置文件路径:

experiment: ${file:experiment/test.yaml}

保持原加载代码不变,此时conf.experiment会自动包含test.yaml的所有配置项,可直接通过conf.experiment.learning_rate获取值0.1。

方法2:手动加载并合并配置

若不想修改原YAML文件,可在代码中手动读取子配置并合并:

from omegaconf import DictConfig, OmegaConf

# 加载主配置
conf = OmegaConf.load("configs/default.yaml")
# 加载子配置(注意路径需匹配文件实际位置)
sub_conf = OmegaConf.load(f"configs/experiment/{conf.experiment}")
# 将子配置合并到主配置的experiment字段
OmegaConf.update(conf, "experiment", sub_conf)

方法3:递归处理嵌套引用

如果子配置中还存在其他YAML引用,可编写递归函数自动加载所有嵌套配置:

from omegaconf import DictConfig, OmegaConf

def recursive_load(config, base_dir):
    for key, value in config.items():
        if isinstance(value, str) and value.endswith(".yaml"):
            # 拼接子配置文件路径
            sub_path = f"{base_dir}/{value}"
            # 加载子配置
            sub_config = OmegaConf.load(sub_path)
            # 递归处理子配置中的引用
            recursive_load(sub_config, f"{base_dir}/{'/'.join(value.split('/')[:-1])}")
            # 替换当前字段为加载后的子配置
            config[key] = sub_config
    return config

# 加载主配置并递归处理所有引用
conf = OmegaConf.load("configs/default.yaml")
conf = recursive_load(conf, "configs")

内容的提问来源于stack exchange,提问作者Simon

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.06 14:20:05