【问题标题】:Hydra: interpolate variable from children nodeHydra:从子节点插入变量
【发布时间】:2022-01-13 12:10:58
【问题描述】:

给定以下配置文件:

# foo/bar.yaml
_target_: ChildClass
a: 0
b: 1
# config.yaml
defaults:
- foo: bar.yaml

_target_: MainClass
c: 2
d: ${foo.a}  # this line doesn't work

我想构造一个 MainClass 类型的对象,它采用 ChildClass 类型的对象。
ChildClass 的参数之一也用在 MainClass 的构造函数中。

如何使用参数插值读取子属性a

【问题讨论】:

    标签: python fb-hydra omegaconf


    【解决方案1】:

    您的想法应该按原样工作。 请确保您已安装 Hydra 版本 >= 1.1,然后试一试:

    # foo/bar.yaml
    _target_: mod.ChildClass
    a: 0
    b: 1
    
    # config.yaml
    defaults:
    - foo: bar.yaml
    
    _target_: mod.MainClass
    c: 2
    d: ${foo.a}
    
    # mod.py
    class ChildClass:
        def __init__(self, a, b):
            print(f"Child {a=} {b=}")
    
    
    class MainClass:
        def __init__(self, c, d, foo):
            print(f"Child {c=} {d=} {foo=}")
    
    # app.py
    import hydra
    from hydra.utils import instantiate
    from omegaconf import DictConfig, OmegaConf
    
    
    @hydra.main(config_path=".", config_name="config")
    def run(cfg: DictConfig):
        instantiate(cfg)
    
    
    if __name__ == "__main__":
        run()
    
    $ python app.py
    Child a=0 b=1
    Child c=2 d=0 foo=<mod.ChildClass object at 0x7f675436b130>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-11-26
      • 1970-01-01
      • 2016-03-15
      • 1970-01-01
      • 2021-02-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多