【问题标题】:Google Cloud ML Prediction API with Custom Response Structure具有自定义响应结构的 Google Cloud ML 预测 API
【发布时间】:2017-04-28 22:45:09
【问题描述】:

我目前正在探索使用 Google Cloud ML 来托管模型并使用该模型托管预测端点。我仍然不明白的一件事是关于 Prediction API 本身的响应格式:

根据documentation here,API 的响应将采用predictions[] 的形式,其中包含具有labelscores 字段的对象。我的问题:

  • 是否可以自定义predictions[] 中的对象结构?例如,对于给定的实例/数据,如果我希望预测 API 返回数字列表或其他可能的结构怎么办?

  • 如果可能,我应该怎么做(例如,更改我的 TensorFlow 代码?配置文件?)?

到目前为止,我还没有清楚地了解预测 API 将如何获得它会给出的响应的形式,给定我的 TensorFlow 模型。

谢谢。

【问题讨论】:

    标签: google-cloud-ml


    【解决方案1】:

    绝对支持定义您自己的输出。典型的 TensorFlow 训练程序将:

    1. 构建训练图
    2. 使用该图训练模型
    3. 构建预测图
    4. 导出 SavedModel

    这就是例证,例如,在这个sample code中。

    当您构建预测图时,您将为输入创建占位符,例如:

    with tf.Graph() as prediction_graph:
      # dtypes can be anything
      # First dimension of shape is "batch size" which must be None
      # so the system can send variable-length batches. Beyond that,
      # there are no other restrictions on shape.
      x = tf.placeholder(dtype=tf.int32, shape=(None,))
      y = tf.placeholder(dtype=tf.float32, shape=(None,))
      z = build_prediction_graph(x, y)
      saver = tf.train.Saver()
    

    当您导出 SavedModel 时,您在所谓的“签名”中声明您的输入和输出;在这个过程中,你给他们起友好的名字(字典中的键),因为 TensorFlow 确实名字修饰。这些键是您在发送数据时在 JSON 中使用的键,它们是您在预测中返回的 JSON 中的键。

    例如:

    # Define the inputs and the outputs.
    inputs = {"x": tf.saved_model.utils.build_tensor_info(x),
              "y": tf.saved_model.utils.build_tensor_info(y)}
    outputs = {"z": tf.saved_model.utils.build_tensor_info(z)}
    signature = tf.saved_model.signature_def_utils.build_signature_def(
        inputs=inputs,
        outputs=outputs,
        method_name=tf.saved_model.signature_constants.PREDICT_METHOD_NAME
    )
    

    使用该签名对服务的假设请求可能如下所示:

    {"instances": [{"x": 6, "y": 3.14}, {"x": 3, "y": 1.0}]}
    

    假设响应如下:

    {"predictions": [{"z": [1, 2, 3]}, {"z": [4, 5, 6]}]} 
    

    最后,您需要实际保存SavedModel

    with tf.Session(graph=prediction_graph) as session:
      # Restore the most recently checkpointed variables from training
      saver.restore(session, tf.train.latest_checkpoint(job_dir))
    
      # Save the SavedModel
      b = builder.SavedModelBuilder('/path/to/export')
      b.add_meta_graph_and_variables(session, ['serving_default'], signature)
      b.save()
    

    【讨论】:

      猜你喜欢
      • 2020-06-25
      • 1970-01-01
      • 2018-12-09
      • 1970-01-01
      • 2017-02-27
      • 2019-02-08
      • 2019-01-19
      • 1970-01-01
      • 2018-10-03
      相关资源
      最近更新 更多