python - 是否可以从配置文件中传递 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.NONE
或tf.keras.losses.Reduction.AUTO
。这些值是张量流对象。
我期望的 JSON 文件示例如下:
{
"reduction ": tf.keras.losses.Reduction.NONE
}
但显然,这是一个无效的 JSON 文件。
问题:
有没有办法让用户在配置文件中传递这种参数?如果不是,那么在用户代码中不保留字符串到对象映射的情况下,获取此类用户输入的其他方法是什么?
解决方案
我对 Python 不是很熟悉,但我假设您read_the_config_file()
不仅可以实现该功能(1)将配置文件的内容读取到字典中,而且还可以将一些字符串值替换为字典中一些特殊条目的对象值,例如reduction
在你的例子中。至少这样,字符串到对象的映射代码被封装在其中read_the_contents_file()
而不是分散在其余的用户代码中。
推荐阅读
- odoo - 如何在 Odoo 12 中拆解产品?
- php - PHP cUrl 和 cookie GX_SESSION_ID
- cmake - 无法在 Clion 中使用嵌入式 gdb 服务器进行调试
- php - 使用 cURL 保存图像
- python - 加载 Python 库“/tmp/_MEItueAuk/libpython3.7m.so.1.0”时出错:dlopen:/lib/x86_64-linux-gnu/libc.so.6:找不到版本“GLIBC_2.28”
- flutter - 如何在 Flutter 中从 ip camera 下载图像
- mongodb - 在 Mongoose 和 GraphQL 中解决关系
- html - 当有多个表和特殊性时,在 R 中抓取 html 表及其 href 链接
- javascript - 将两个对象添加到原型链而不链接它们自己
- kubernetes - Kubernetes 部署有时有效,有时无效