我有一个 yaml 文件
cars:
- model: "Sedan"
length: 4.5
width: 1.8
height: 1.4
fuel_efficiency:
- 12 # City
- 15 # Highway
- 13 # Combined
- model: "SUV"
length: 4.8
width: 2.0
height: 1.7
fuel_efficiency:
- 10
- 12
- 11
- model: Hatchback
length: 4.0
width: 1.7
height: 1.4
fuel_efficiency:
- 14
- 18
- 16
我使用 Hydra 编写了一个脚本,其中包含以下内容
import hydra
from omegaconf import DictConfig
@hydra.main(config_path="config", config_name="car_data", version_base=None)
def main(cfg:DictConfig):
for car in cfg.cars:
print(car.model)
我得到了值,做了一些计算,一切顺利!
我的问题是如何合并覆盖某些值(Hydra 的一项功能)
我已经尝试过了
>python process_cars.py cars[0].length=4.8
LexerNoViableAltException: cars[0].length=4.8
^
See https://hydra.cc/docs/1.2/advanced/override_grammar/basic for details
我尝试阅读建议的文档,但无法弄清楚如何在这种情况下应用
问题在于 Hydra 的覆盖语法中访问列表元素的语法。对于列表,您需要使用点符号和数字,而不是方括号符号。以下是如何正确覆盖这些值:
python process_cars.py cars.0.length=4.8
针对您的配置的有效 Hydra 覆盖的更多示例:
# Change multiple properties of the first car
python process_cars.py cars.0.length=4.8 cars.0.width=2.0
# Change fuel efficiency values (since it's a nested list)
python process_cars.py cars.0.fuel_efficiency.0=13 cars.0.fuel_efficiency.1=16
# Change values for multiple cars
python process_cars.py cars.0.model=Coupe cars.1.height=1.8
# Change an entire fuel efficiency array
python process_cars.py cars.0.fuel_efficiency=[15,18,16]
至于覆盖 Hydra 中的整个数组,这里有几种方法:
# Method 1: Using square brackets
python process_cars.py cars.0.fuel_efficiency=[20,25,22]
# Method 2: If you prefer comma-separated without spaces
python process_cars.py cars.0.fuel_efficiency=[20\,25\,22]
您还可以将此与其他覆盖结合起来:
python process_cars.py cars.0.fuel_efficiency=[20,25,22] cars.0.length=4.8