我有以下几行代码:
param0 = {
'max_depth': 3,
'eta': 0.075,
'objective': 'binary:logistic',
'min_child_weight': 5,
'silent': 1,
'eval_matric': "auc",
'subsample': 0.6,
'gamma': 0.5,
}
它定义了一个 pythons 字典(对于 ml 模型,如果有人感兴趣的话)。我想知道从外包文件创建此 param0 字典参数的最优雅(最简单)的方法是什么。 (即来自 xml 文件、json 文件或我可以在程序外配置的简单文本文件)。
- 我需要知道外包文件的外观(结构)。
- 我需要知道读取外包文件的代码。
请您参考如下方法:
优雅是主观的,但从实用性的角度来看,您可以将其存储/加载为 JSON 数据,假设您的字典在其值中不包含列表、字符串和字典之外的其他 Python 对象。
config.json
{
"max_depth": 3,
"eta": 0.075,
"objective": "binary:logistic",
"min_child_weight": 5,
"silent": 1,
"eval_matric": "auc",
"subsample": 0.6,
"gamma": 0.5,
}
请注意 JSON spec要求字符串用双引号 分隔(单引号不行)。创建/编辑文件时,请记住 JSON 的语法和允许的数据类型。
读取 config.json 的代码,使用 python 的 json 模块。
import json
with open('config.json') as f:
param0 = json.load(f)
