【问题标题】:Prediction fails in Google Cloud with tensorflow model使用 TensorFlow 模型在 Google Cloud 中预测失败
【发布时间】:2019-03-01 17:01:53
【问题描述】:
  • 我按照这个 [tensorflow 教程] 训练了一个图像分类器。(https://www.tensorflow.org/hub/tutorials/image_retraining)

  • 我用这个snippet 在训练过程之后生成了我的SavedModel

  • 我按照 Google 的说明部署我的模型,并尝试使用本地目录中的图像进行一些预测。

  • 为了执行预测,我使用了这个:

# Create request message in json format

python -c 'import base64, json; img =
base64.b64encode(open("image.jpg").read()); print
json.dumps({"image_bytes": {"b64": img}})' image.jpg &> request.json

# Call prediction service API to get classifications
gcloud ml-engine predict --model ${MODEL_NAME} --json-instances
request.json

我收到以下错误:

"error": "Prediction failed: Error processing input: Expected float32, got {u'b64': u'/9j/4AA....lPqevnQf//Z'} of type 'dict' instead.

我应该使用不同的类型重新训练模型还是如何解决这个问题?非常感谢任何提示。

【问题讨论】:

标签: tensorflow machine-learning google-cloud-ml


【解决方案1】:

您需要确保您的服务功能如下所示。请注意,输入的名称是 image_bytes,可以是任何以 _bytes 结尾的名称。

    def serving_input_fn():
       feature_placeholders = {
          'image_bytes': tf.placeholder(dtype=tf.string, shape=[None], name='source')}
          single_image = tf.decode_raw(feature_placeholders['image_bytes'], tf.float32)
          return tf.estimator.export.ServingInputReceiver(feature_placeholders, feature_placeholders)

要了解有关如何发送数据的更多详细信息及其相关原理,请查看https://stackoverflow.com/a/49177909/6031363

另外,您可以访问 AI Platform 文档说明发送预测请求https://cloud.google.com/ml-engine/docs/prediction-overview

【讨论】:

    【解决方案2】:

    我运行教程,你使用的 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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-17
      • 2018-03-24
      • 2018-10-09
      • 2016-02-16
      • 2018-03-30
      相关资源
      最近更新 更多