首页 > 解决方案 > 是否可以从配置文件中传递 python 对象?

问题描述

我不介意它是 YAML、JSON、.ini 还是其他。

用户应该能够通过如下配置文件更改对tf.keras.losses.CategoricalHingereduction函数的调用中的值:

import tensorflow as tf

# config file reading happens here (expected scenario):
f = read_the_config_file()
reduction = f["reduction"]  # retrieved the reduction value

# pass `reduction` to the loss function:
loss = tf.keras.losses(reduction)

reduction可以是tf.keras.losses.Reduction.NONEtf.keras.losses.Reduction.AUTO。这些值是张量流对象。

我期望的 JSON 文件示例如下:

{
"reduction ": tf.keras.losses.Reduction.NONE
}

但显然,这是一个无效的 JSON 文件。

问题:

有没有办法让用户在配置文件中传递这种参数?如果不是,那么在用户代码中不保留字符串到对象映射的情况下,获取此类用户输入的其他方法是什么?

标签: pythonjsontensorflowconfigurationyaml

解决方案


我对 Python 不是很熟悉,但我假设您read_the_config_file()不仅可以实现该功能(1)将配置文件的内容读取到字典中,而且还可以将一些字符串值替换为字典中一些特殊条目的对象值,例如reduction在你的例子中。至少这样,字符串到对象的映射代码被封装在其中read_the_contents_file()而不是分散在其余的用户代码中。


推荐阅读