从 python 文件在 hydra DictConfig 中创建一个新密钥
Create a new key in hydra DictConfig from python file
我想在加载 Hydra Config 后添加键 + 值。本质上,我想 运行 我的代码并检查 gpu 是否可用。如果是,将设备记录为 gpu,否则保留 cpu.
基本上保存了 :
的输出
torch.cuda.is_available()
当我尝试添加带有“setdefault”的键时:
@hydra.main(config_path="conf", config_name="config")
def my_app(cfg: DictConfig) -> None:
cfg.setdefault("new_key", "new_value")
如果我这样做,同样的错误:
cfg.new_key = "new_value"
print(cfg.new_key)
我收到错误:
omegaconf.errors.ConfigKeyError: Key 'new_key' is not in struct
full_key: new_key
reference_type=Optional[Dict[Union[str, Enum], Any]]
object_type=dict
我目前的解决方法是直接使用 OmegaConfig:
cfg = OmegaConf.structured(OmegaConf.to_yaml(cfg))
cfg.new_key = "new_value"
print(cfg.new_key)
>>>> new_value
一定有更好的方法吗?
Hydra 在其生成的 OmegaConf 配置对象的根上设置结构标志。
有关结构标志的更多信息,请参阅 this。
您可以使用 open_dict() 暂时禁用此功能并允许添加新密钥:
>>> from omegaconf import OmegaConf,open_dict
>>> conf = OmegaConf.create({"a": {"aa": 10, "bb": 20}})
>>> OmegaConf.set_struct(conf, True)
>>> with open_dict(conf):
... conf.a.cc = 30
>>> conf.a.cc
30
我想在加载 Hydra Config 后添加键 + 值。本质上,我想 运行 我的代码并检查 gpu 是否可用。如果是,将设备记录为 gpu,否则保留 cpu.
基本上保存了 :
的输出torch.cuda.is_available()
当我尝试添加带有“setdefault”的键时:
@hydra.main(config_path="conf", config_name="config")
def my_app(cfg: DictConfig) -> None:
cfg.setdefault("new_key", "new_value")
如果我这样做,同样的错误:
cfg.new_key = "new_value"
print(cfg.new_key)
我收到错误:
omegaconf.errors.ConfigKeyError: Key 'new_key' is not in struct
full_key: new_key
reference_type=Optional[Dict[Union[str, Enum], Any]]
object_type=dict
我目前的解决方法是直接使用 OmegaConfig:
cfg = OmegaConf.structured(OmegaConf.to_yaml(cfg))
cfg.new_key = "new_value"
print(cfg.new_key)
>>>> new_value
一定有更好的方法吗?
Hydra 在其生成的 OmegaConf 配置对象的根上设置结构标志。 有关结构标志的更多信息,请参阅 this。
您可以使用 open_dict() 暂时禁用此功能并允许添加新密钥:
>>> from omegaconf import OmegaConf,open_dict
>>> conf = OmegaConf.create({"a": {"aa": 10, "bb": 20}})
>>> OmegaConf.set_struct(conf, True)
>>> with open_dict(conf):
... conf.a.cc = 30
>>> conf.a.cc
30