我运行教程,你使用的 Python 代码:
python -c 'import base64, json; img = base64.b64encode(open("image.jpg").read()); print json.dumps({"image_bytes": {"b64": img}})' image.jpg &> request.json
生成具有以下内容的文件:
{"image_bytes": {"b64": "Base64Text..."}}
使用 export saved_model_dir 选项训练您的模型。
$ python retrain.py --image_dir ~/flower_photos --
saved_model_dir=/tmp/saved_models/$(date +%s)
使用 SavedModel CLI 显示 SavedModel 的签名。输入以下命令以显示 TensorFlow SavedModel 的输入/输出的签名:
$ saved_model_cli show --dir /tmp/saved_models/1575937119 --all
MetaGraphDef with tag-set: 'serve' contains the following SignatureDefs:
signature_def['serving_default']:
The given SavedModel SignatureDef contains the following input(s):
inputs['image'] tensor_info:
dtype: DT_FLOAT
shape: (-1, 299, 299, 3)
name: Placeholder:0
The given SavedModel SignatureDef contains the following output(s):
outputs['prediction'] tensor_info:
dtype: DT_FLOAT
shape: (-1, 5)
name: final_result:0
Method name is: tensorflow/serving/predict
这意味着模型期望输入使用张量,而不是 b64 encoded image.
您可以启动 TensorFlow 服务以在本地进行测试:
tensorflow_model_server --model_base_path=/tmp/saved_models/ --rest_api_port
=9001
URL=http://localhost:9001/v1/models/default:predict
curl -X POST -d @out.json $URL
out.json 是 JSON 格式的文件,您将获得预期的结果。
使用 TF Serving,您可以使用以下代码生成文件:
import numpy as np
import json
from PIL import Image
INPUT_FILE = 'image.jpg'
OUTPUT_FILE = '/tmp/out.json'
def convert_to_json(image_file):
"""Open image, convert it to numpy and create JSON request"""
img = Image.open(image_file).resize((224, 224))
img_array = np.array(img)
predict_request = {"instances": [img_array.tolist()]}
with open(OUTPUT_FILE, 'w') as output_file:
json.dump(predict_request, output_file)
return predict_request
prediction_data = convert_to_json(INPUT_FILE)
你会得到:
{
"predictions": [[0.0, 0.0, 1.0, 0.0, 0.0]]
}
如果您使用 AI Platform,您可以使用 gcloud ai-platform predict 发送请求,或者以 UI 为例进行测试:
检查:How convert a jpeg image into json file in Google machine learning
了解详情。
正如@Puneith 所说,您需要更改Serving 函数来处理b64。
这个问题类似于GCP ML Engine Prediction failed: Error processing input: Expected float32 got base64