【问题标题】:Is there a way to auto-match multiple parameters the same?有没有办法自动匹配多个相同的参数?
【发布时间】:2021-08-06 08:46:44
【问题描述】:

我的模型中有多个深度神经网络,并希望它们具有相同的输入大小 (网络属于不同的类别)。比如我的模型是:

class Model:
 def __init__(self, cfg: DictConfig):
   self.net1 = Net1(**cfg.net1_hparams)
   self.net2 = Net2(**cfg.net2_hparams)

这里Net1和Net2有不同的超参数集,但其中input_size参数是Net1和Net2共享的,必须匹配,即cfg.net1_hparams.input_size == cfg.net2_hparams.input_size

我可以在父级定义 input_size:cfg.input_size 并手动将它们传递给 Net1 和 Net2。但是,我希望每个网络的 hparams-configs 都是完整的,以便以后我可以只使用 cfg.net1_hparams 构建 Net1。

有没有在 hydra 中实现这一点的好方法?

【问题讨论】:

    标签: python fb-hydra hydra-python


    【解决方案1】:

    这可以使用 OmegaConf 的 variable interpolation 功能来实现。

    这是一个使用 Hydra 进行变量插值以达到预期结果的最小示例:

    # config.yaml
    shared_hparams:
      input_size: [128, 128]
    net1_hparams:
      name: net one
      input_size: ${shared_hparams.input_size}
    net2_hparams:
      name: net two
      input_size: ${shared_hparams.input_size}
    
    """my_app.py"""
    import hydra
    from omegaconf import DictConfig
    
    class Model:
        def __init__(self, cfg: DictConfig):
            print("Net1", dict(**cfg.net1_hparams))
            print("Net2", dict(**cfg.net2_hparams))
    
    @hydra.main(config_name="config")
    def my_app(cfg: DictConfig) -> None:
        Model(cfg)
    
    if __name__ == "__main__":
        my_app()
    

    在命令行运行 my_app.py 会产生以下结果:

    $ python my_app.py
    Net1 {'name': 'net one', 'input_size': [128, 128]}
    Net2 {'name': 'net two', 'input_size': [128, 128]}
    

    【讨论】:

    • 感谢您的详细解答!快速提问。虽然上面的代码运行良好,但当我通过 OmegaConf.to_yaml(cfg) 打印 cfg 时,我看到 input_size 的非插值结果:input_size: ${shared_hparams.input_size}。您认为这是预期的行为吗?
    • 不客气!是的,这是意料之中的:默认情况下,OmegaConf.to_yaml 不解析插值。尝试使用 resolve 关键字参数:OmegaConf.to_yaml(cfg, resolve=True)。您可能还感兴趣的是OmegaConf.to_container(cfg, resolve=True),它会将DictConfig 对象转换为普通的Python dict
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-03
    • 1970-01-01
    • 2019-03-09
    • 1970-01-01
    • 2022-11-15
    相关资源
    最近更新 更多