Hydra 组合配置中的列表

发布于 2025-01-15 04:08:33 字数 811 浏览 3 评论 0原文

假设我有以下 Hydra 配置 test.yaml

list1 : [0]
list2 : [1,2,3]

是否可以将 list1list2 合并到包含 [ 的新列表中0,1,2,3],也许使用变量插值?

这是九头蛇代码:

import hydra
from omegaconf import OmegaConf
@hydra.main(config_name="test.yaml", config_path="./")
def main(cfg):
    OmegaConf.resolve(cfg)
    print(cfg)
if __name__ == "__main__":
    main()

尝试(失败):

list1 : [0]
list2 : [1,2,3]
list3 : 
  - ${list1} 
  - ${list2}

list3给出[0,[1,2,3]]

我想要这个的原因是因为我有一些列表其他配置文件中的长度未知,并且想要合并它们以创建对象创建的参数。我不想在代码中执行此操作,而是直接依赖 Hydras 对象实例化(否则我将在各处进行列表合并!)。

Say I have the following hydra config test.yaml:

list1 : [0]
list2 : [1,2,3]

is it possible to merge list1 and list2 into a new list that contains [0,1,2,3], perhaps using variable interpolation?

Here is the hydra code:

import hydra
from omegaconf import OmegaConf
@hydra.main(config_name="test.yaml", config_path="./")
def main(cfg):
    OmegaConf.resolve(cfg)
    print(cfg)
if __name__ == "__main__":
    main()

Attempt (failed):

list1 : [0]
list2 : [1,2,3]
list3 : 
  - ${list1} 
  - ${list2}

list3 gives [0,[1,2,3]]

The reason I want this is because I have some lists of unknown length in other config files and want to merge them to create an argument for object creation. I'd prefer not to do this in the code and just rely directly on hydras object instantiation (otherwise I'll be doing list merging everywhere!).

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

月隐月明月朦胧 2025-01-22 04:08:33

事实证明这并不太困难,我们确实可以依靠 OmegaConfs 变量插值与自定义解析器。

import hydra
from omegaconf import OmegaConf
# custom list merge resolver
OmegaConf.register_new_resolver("merge", lambda x, y : x + y)

@hydra.main(config_name="test.yaml", config_path="./")
def main(cfg):
    OmegaConf.resolve(cfg)
    print(cfg)

if __name__ == "__main__":
    main()

配置文件 test.yaml

list1 : [0]
list2 : [1,2,3]

list3 : ${merge:${list1},${list2}}

list3 现在是所需的 [0,1,2,3]

Turns out this is not too difficult, one can indeed rely on OmegaConfs variable interpolation with a custom resolver.

import hydra
from omegaconf import OmegaConf
# custom list merge resolver
OmegaConf.register_new_resolver("merge", lambda x, y : x + y)

@hydra.main(config_name="test.yaml", config_path="./")
def main(cfg):
    OmegaConf.resolve(cfg)
    print(cfg)

if __name__ == "__main__":
    main()

Config file test.yaml

list1 : [0]
list2 : [1,2,3]

list3 : ${merge:${list1},${list2}}

list3 is now [0,1,2,3] as desired.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文