【发布时间】:2018-09-14 08:43:16
【问题描述】:
我有一个 numpy 数组 (X_test) 用于在 cloud-ml 中测试我的模型。在线预测需要转成JSON格式。
我的 numpy 数组具有以下格式:
[[ 0 0 0 ... 7464 1951 2861]
[ 0 0 0 ... 3395 1996 4999]
[ 0 0 0 ... 5294 9202 17867]
...
[ 0 0 0 ... 3506 977 7818]
[ 0 0 0 ... 1421 75 137]
[ 0 0 0 ... 12857 12686 2928]]
我使用下面的代码将其转换为 JSON:
import json
b = X_test.tolist()
json_file = "file.json"
json.dump(b, codecs.open(json_file, 'w', encoding='utf-8'), sort_keys=True, indent=4)
之后我使用Google Cloud SDK Shell进行云预测并输入下一条命令:
gcloud ml-engine predict --model keras_model --version v1 --json-instances file.json
但是,我得到下一个错误:
ERROR: (gcloud.ml-engine.predict) Input instances are not in JSON format. See "gcloud ml-engine predict --help" for details.
据我了解,我错误地将 numpy 转换为 JSON 以用于 cloud-ml。
如何正确地将 numpy 转换为 JSON 以避免此错误?
UPD:这是帮助我解决此问题的代码:
import json
b = X_test.tolist()
json_file = "file.json"
with open(json_file, 'w', encoding='utf-8') as f:
for i in b:
instance = {"input": i}
json.dump(instance, f , sort_keys=True)
f.write("\n")
【问题讨论】:
标签: python json numpy tensorflow google-cloud-platform