如何将numpy数组转换为Google Cloud ML的JSON?

问题描述 投票:2回答:3

我有一个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 for 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
3个回答
3
投票

文件:

https://cloud.google.com/ml-engine/docs/tensorflow/online-predict#formatting_instances_as_json_strings

也许使用这样的东西:

import numpy as np
import codecs

X_test = np.zeros((5,5))
print(X_test)

import json
b = X_test.tolist()
json_file = "file.json"

f = codecs.open(json_file, 'w', encoding='utf-8')

for i in range(0,len(b)):
    row = b[i]
    instance = {"values" : row, "key": i}
    json.dump(instance, f , sort_keys=True)
    f.write("\n")

file.json变为:

{"key": 0, "values": [0.0, 0.0, 0.0, 0.0, 0.0]}
{"key": 1, "values": [0.0, 0.0, 0.0, 0.0, 0.0]}
{"key": 2, "values": [0.0, 0.0, 0.0, 0.0, 0.0]}
{"key": 3, "values": [0.0, 0.0, 0.0, 0.0, 0.0]}
{"key": 4, "values": [0.0, 0.0, 0.0, 0.0, 0.0]}

1
投票

对于在线预测,json需要是每行一个实例。

e.g

    39,State-gov,77516,Bachelors,13,Never-married,Adm-clerical,Not-in-family,White,Male,2174,0,40,United-States,<=50K
50,Self-emp-not-inc,83311,Bachelors,13,Married-civ-spouse,Exec-managerial,Husband,White,Male,0,0,13,United-States,<=50K
38,Private,215646,HS-grad,9,Divorced,Handlers-cleaners,Not-in-family,White,Male,0,0,40,United-States,<=50K
53,Private,234721,11th,7,Married-civ-spouse,Handlers-cleaners,Husband,Black,Male,0,0,40,United-States,<=50K

你可以参考https://github.com/GoogleCloudPlatform/cloudml-samples


0
投票

在写入文件之前,您可以使用类型函数检查您的JSON转换数据(在您的情况下:类型(b))以确保。然后只使用简单的代码来编写json:

    import io
    json.dump(b, io.open(json_file, 'w', encoding='utf-8'))
© www.soinside.com 2019 - 2024. All rights reserved.