【问题标题】:Google ML Engine: Prediction failed: Error during model executionGoogle ML Engine:预测失败:模型执行期间出错
【发布时间】:2018-03-31 13:30:59
【问题描述】:

我已使用 gcloud 命令行成功运行预测。我正在尝试运行 Python 脚本来运行预测。但我正面临错误。

预测失败:模型执行期间出错:AbortionError(code=StatusCode.INVALID_ARGUMENT, details="assertion failed: [无法将字节解码为 JPEG、PNG、GIF 或 BMP] [[节点:map/while/decode_image/cond_jpeg/cond_png/cond_gif/Assert_1/Assert = Assert[T=[DT_STRING],summary=3,_device="/job:localhost/replica:0/task:0/device: CPU:0"](map/while/decode_image/cond_jpeg/cond_png/cond_gif/is_bmp, map/while/decode_image/cond_jpeg/cond_png/cond_gif/Assert_1/Assert/data_0)]]")

from oauth2client.client import GoogleCredentials
from googleapiclient import discovery
from googleapiclient import errors

PROJECTID = 'ai-assignment-185606'
projectID = 'projects/{}'.format(PROJECTID)
modelName = 'food_model'
modelID = '{}/models/{}/versions/{}'.format(projectID, modelName, 'v3')

scopes = ['https://www.googleapis.com/auth/cloud-platform']
credentials = GoogleCredentials.get_application_default()
ml = discovery.build('ml', 'v1', credentials=credentials)

with open('1.jpg', 'rb') as f:
    b64_x = f.read()
import base64
import json

name = "7_5790100434_e2c3dbfdba.jpg";
with open("images/"+name, "rb") as image_file:
    encoded_string = base64.b64encode(image_file.read()).decode('utf-8')
    row = json.dumps({'inputs': {'b64': encoded_string}})

request_body = {"instances": row}

request = ml.projects().predict(name=modelID, body=request_body)
try:
    response = request.execute()
except errors.HttpError as err:
    print(err._get_reason())

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

print(response)

这个answer 建议版本必须相同。我检查了 1.4 和 1.4.1 的版本。

【问题讨论】:

  • 您能否发布完整的命令行、输出并在代码中标记与引发异常的位置相对应的行,因为我们无法知道。
  • 完整的命令行意味着gcloud命令?我在没有参数的情况下运行这个 python 脚本。这个错误其实是response = request.execute()行后返回的响应

标签: python tensorflow google-cloud-platform


【解决方案1】:

根据https://cloud.google.com/ml-engine/docs/v1/predict-request,该行应该是一个数据列表。每个数据可以是一个值、一个 JSON 对象或一个列表/嵌套列表:

{
  "instances": [
    <value>|<simple/nested list>|<object>,
    ...
  ]
}

相反,您的行是一个表示 JSON 的文本字符串(即收件人必须通过 json.loads(row) 来获取 JSON)。试试这个:

instances = []
with open("images/"+name, "rb") as image_file:
    encoded_string = base64.b64encode(image_file.read()).decode('utf-8')
    instances.append({'b64': encoded_string})

request_body = {"instances": instances}

【讨论】:

  • RuntimeError: 无效请求。服务期望请求是一个有效的 JSON 对象,具有一个名为instances 的列表值属性,即{"instances": [...]}。收到的请求是:"{\"instances\": {\"inputs\": {\"b64\": \".....\"}}}"
  • @samtew 我根据您的评论更新了答案,如果仍然不起作用,请告诉我
【解决方案2】:

根据文档here,格式应该如下:
{"instances": [{"b64": "X5ad6u"}, {"b64": "IA9j4nx"}]}.
但我收到以下错误。
RuntimeError: Prediction failed: unknown error.

我必须添加image_bytes 才能使其按照this post 工作。下面是它的外观:
{"instances": [{"image_bytes": {"b64": encoded_string}, "key": "0"}]

下面的代码sn-p:

@app.route('/predict', methods=['POST'])
def predict():
    if 'images' in request.files:
        file = request.files['images']
        image_path = save_image(file)
        # Convert image to base64
        encoded_string = base64.b64encode(open(file=image_path, mode="rb").read()).decode('utf-8')

        service = discovery.build('ml', 'v1', credentials=credentials)
        name = 'projects/{}/models/{}'.format('my-project-name', 'my-model-name')
        name += '/versions/{}'.format('v1')

        response = service.projects().predict(
            name=name,
            body= {"instances": [{"image_bytes": {"b64": encoded_string}, "key": "0"}]}

        ).execute()

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

        print(response['predictions'])
        return jsonify({'result': response['predictions']})
    else:
        return jsonify({'result': 'Since Image tag is empty, cannot predict'})

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-09-14
    • 1970-01-01
    • 2019-02-16
    • 1970-01-01
    • 2019-02-17
    • 2018-09-01
    • 2019-08-24
    相关资源
    最近更新 更多