ML 引擎在线预测 - 意外的张量名称:值
ML Engine Online Prediction - Unexpected tensor name: values
尝试对我的 ML 引擎模型进行在线预测时出现以下错误。
密钥 "values" 不正确。 (参见图像上的错误。)
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')
错误消息本身表明(正如您在问题中指出的那样),键 "values" 不是模型中指定的输入之一。要检查模型的输入,请使用 saved_model_cli show --all --dir=/path/to/model
。这将向您显示输入名称的列表。您需要使用正确的名称。
也就是说,似乎还有另一个问题。从问题中不清楚你的模型期望什么类型的输入,尽管它可能是以下两种情况之一:
- 整数或浮点数矩阵
- 带有原始图像文件的字节字符串
内容。
确切的解决方案将取决于您导出的模型使用的是上述哪一个。 saved_model_cli
将根据输入的类型和形状提供帮助。它将分别是 DT_FLOAT32
(或其他一些 int/float 类型)和 [NONE, 299, 299, CHANNELS]
或 DT_STRING
和 [NONE]
。
如果你的模型是类型(1),那么你需要发送一个ints/floats的矩阵(不使用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
.
的输出进行验证
我以前也遇到过这个错误。如果有人遇到此错误并使用 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"
}]
尝试对我的 ML 引擎模型进行在线预测时出现以下错误。 密钥 "values" 不正确。 (参见图像上的错误。) 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')
错误消息本身表明(正如您在问题中指出的那样),键 "values" 不是模型中指定的输入之一。要检查模型的输入,请使用 saved_model_cli show --all --dir=/path/to/model
。这将向您显示输入名称的列表。您需要使用正确的名称。
也就是说,似乎还有另一个问题。从问题中不清楚你的模型期望什么类型的输入,尽管它可能是以下两种情况之一:
- 整数或浮点数矩阵
- 带有原始图像文件的字节字符串 内容。
确切的解决方案将取决于您导出的模型使用的是上述哪一个。 saved_model_cli
将根据输入的类型和形状提供帮助。它将分别是 DT_FLOAT32
(或其他一些 int/float 类型)和 [NONE, 299, 299, CHANNELS]
或 DT_STRING
和 [NONE]
。
如果你的模型是类型(1),那么你需要发送一个ints/floats的矩阵(不使用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
.
我以前也遇到过这个错误。如果有人遇到此错误并使用 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"
}]