尝试对ML Engine模型进行在线预测时,出现以下错误。 键“值”不正确。 (请参阅图像上的错误。) enter image description here
我已经使用RAW图像数据进行了测试:{"image_bytes":{"b64": base64.b64encode(jpeg_data)}}
&将数据转换为numpy数组。
当前我有以下代码:
from googleapiclient import discovery
import base64
import os
from PIL import Image
import json
import numpy as np
os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = "/Users/jacob/Desktop/******"
def predict_json(project, model, instances, version=None):
"""Send json data to a deployed model for prediction.
Args:
project (str): project where the Cloud ML Engine Model is deployed.
model (str): model name.
instances ([Mapping[str: Any]]): Keys should be the names of Tensors
your deployed model expects as inputs. Values should be datatypes
convertible to Tensors, or (potentially nested) lists of datatypes
convertible to tensors.
version: str, version of the model to target.
Returns:
Mapping[str: any]: dictionary of prediction results defined by the
model.
"""
# Create the ML Engine service object.
# To authenticate set the environment variable
# GOOGLE_APPLICATION_CREDENTIALS=<path_to_service_account_file>
service = discovery.build('ml', 'v1')
name = 'projects/{}/models/{}'.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']
savepath = 'upload/11277229_F.jpg'
img = Image.open('test/01011000/11277229_F.jpg')
test = img.resize((299, 299))
test.save(savepath)
img1 = open(savepath, "rb").read()
def load_image(filename):
with open(filename) as f:
return np.array(f.read())
predict_json('image-recognition-25***08', 'm500_200_waug', [{"values": str(base64.b64encode(img1).decode("utf-8")), "key": '87'}], 'v1')
答案 0 :(得分:1)
错误消息本身表明(如您在问题中所指出的那样),键“值”不是模型中指定的输入之一。要检查模型的输入,请使用saved_model_cli show --all --dir=/path/to/model
。这将为您显示输入名称的列表。您需要使用正确的名称。
也就是说,似乎还有另一个问题。从这个问题尚不清楚,您的模型期望输入哪种类型,尽管这很可能是两件事之一:
确切的解决方案取决于您使用的导出模型是哪种。 saved_model_cli
将根据输入的类型和形状在此提供帮助。它将分别为DT_FLOAT32
(或其他int / float类型)和[NONE, 299, 299, CHANNELS]
或DT_STRING
和[NONE]
。
如果您的模型是类型(1),那么您将需要发送一个整数/浮点数的矩阵(不使用base64编码):
predict_json('image-recognition-25***08', 'm500_200_waug', [{CORRECT_INPUT_NAME: load_image(savepath).tolist(), "key": '87'}], 'v1')
请注意使用tolist
将numpy数组转换为列表列表。
对于类型(2),您需要通过添加{“ b64”:...}:来告诉服务您有一些base64数据:
predict_json('image-recognition-25***08', 'm500_200_waug', [{CORRECT_INPUT_NAME: {"b64": str(base64.b64encode(img1).decode("utf-8"))}, "key": '87'}], 'v1')
所有这些当然都取决于为CORRECT_INPUT_NAME
使用正确的名称。
最后一点,我假设您的模型实际上确实包含key
作为附加输入,因为您已将其包括在请求中;再次,可以全部根据saved_model_cli show
的输出进行验证。
答案 1 :(得分:0)
我也经常遇到此错误。如果有人遇到此错误,请使用gcloud。
张量自动称为csv_rows。例如,这现在对我有效
"instances": [{
"csv_row": "STRING,7,4.02611534,9,14,0.66700000,0.17600000,0.00000000,0.00000000,1299.76500000,57",
"key": "0"
}]