模型预测JSON请求格式不适用于python请求:Google AI平台

时间:2019-06-27 05:38:58

标签: python json tensorflow google-cloud-platform

我正在尝试预测要在Google Cloud AI平台中部署的映像。接下来是预测的请求格式:

{"instances": [{"b64": "X5ad6u"}]} //样本b64格式[代替X5ad6u =>真实图像值]

https://cloud.google.com/ml-engine/docs/v1/predict-request

但是它失败了,并提供了错误作为Prediction错误:instances

{ "error": "JSON Value:  Excepting \'instances\' to be an list/array" }

输入请求格式:{"instances": [{"b64": "X5ad6u"}]}

python示例代码:

import argparse
import base64
import json
import googleapiclient.discovery
import six
import os
from flask import Flask
app = Flask(__name__)

credential_path = "sample.json"
os.environ['GOOGLE_APPLICATION_CREDENTIALS'] = credential_path


@app.route("/")
def home():
    return "Hello, World!"

def predict_json(project, model, instances, version=None):
    print("i am here to predict")

    # Create the ML Engine service object.
    # To authenticate set the environment variable
    # GOOGLE_APPLICATION_CREDENTIALS=<path_to_service_account_file>
    service = googleapiclient.discovery.build('ml', 'v1')
    name = 'projects/myproject/models/beverage_optimizer'.format(project, model)

    if version is not None:
        name += '/versions/'.format(version)

    response = service.projects().predict(
        name=name,
        body={'instances': instances}
    ).execute()

    if 'error' in response:
        raise RuntimeError(response['error'])

    return response['predictions']
a



def main(project, model, version=None):
    """Send user input to the prediction service."""
    print('I m in True')
    try:
        #user_input = json.loads("home/ubuntu/Hrishi/FreshnessWithUI/request.json")
        json_data=open("request.json").read()
        user_input = json.loads(json_data)
        #print(user_input)
    except KeyboardInterrupt:
        return
    try:
        result = predict_json(project, model, user_input, version=None)
       # print(result)
    detectionscores = result['predictions'][0]['detection_scores']
    detectionboxes = result['predictions'][0]['detection_boxes']
    detectionclasses = result['predictions'][0]['detection_classes']
    #print(detectionscores)
    #print(detectionboxes)
    #print(detectionclasses)
    pre_data={}
    k=0
        for a,b,c in zip(detectionscores,detectionboxes,detectionclasses):
            if a >= 0.90:
                pre_data[k+1]={"score":a,"box":b, "class": int(c) } ;
                k=k+1;
        print("pre-data:",pre_data)
        #print("type", type(pre_data))
    except RuntimeError as err:
        print(str(err))



if __name__ == '__main__':
    app.run(debug=True)
    parser = argparse.ArgumentParser()
    parser.add_argument(
        '--project',
        help='Project in which the model is deployed',
        #type=str,
        #required=True
    )
    parser.add_argument(
        '--model',
        help='Model name',
        #type=str,
        #required=True
    )
    parser.add_argument(
        '--version',
        help='Name of the version.',
        #type=str
    )
    args = parser.parse_args()
    main(    
        args.project,
        args.model,
        version=args.version
    )

另一种方法:

通过google cloud命令: gcloud AI平台预测--model Drink_optimizer --version Drink_optimizer --json-instances request.json

错误:(gcloud.ai-platform.predict)输入实例不是JSON格式

0 个答案:

没有答案