在张量流中为 Google CloudML 部署单独创建服务图?

Creating a serving graph separately from training in tensorflow for Google CloudML deployment?

我正在尝试将 tf.keras 图像分类模型部署到 Google CloudML Engine。我是否必须包含代码来创建与训练分开的服务图,以使其在 Web 应用程序中为我的模型提供服务?我的模型已经采用 SavedModel 格式(saved_model.pb 和变量文件),所以我不确定是否需要执行此额外步骤才能使其正常工作。

例如这是直接来自 GCP Tensorflow 部署模型的代码 documentation

def json_serving_input_fn():
  """Build the serving inputs."""
  inputs = {}
  for feat in INPUT_COLUMNS:
    inputs[feat.name] = tf.placeholder(shape=[None], dtype=feat.dtype)

  return tf.estimator.export.ServingInputReceiver(inputs, inputs)

您可能正在使用实际图像文件训练您的模型,而最好将图像作为编码字节字符串发送到托管在 CloudML 上的模型。因此,正如您提到的,您需要在导出模型时指定一个 ServingInputReceiver 函数。为 Keras 模型执行此操作的一些样板代码:

# Convert keras model to TF estimator
tf_files_path = './tf'
estimator =\
    tf.keras.estimator.model_to_estimator(keras_model=model,
                                          model_dir=tf_files_path)

# Your serving input function will accept a string
# And decode it into an image
def serving_input_receiver_fn():
    def prepare_image(image_str_tensor):
        image = tf.image.decode_png(image_str_tensor,
                                    channels=3)
        return image  # apply additional processing if necessary

    # Ensure model is batchable
    # 
    input_ph = tf.placeholder(tf.string, shape=[None])
    images_tensor = tf.map_fn(
        prepare_image, input_ph, back_prop=False, dtype=tf.float32)

    return tf.estimator.export.ServingInputReceiver(
        {model.input_names[0]: images_tensor},
        {'image_bytes': input_ph})

# Export the estimator - deploy it to CloudML afterwards
export_path = './export'
estimator.export_savedmodel(
    export_path,
    serving_input_receiver_fn=serving_input_receiver_fn)

您可以参考 this very helpful answer 以获得更完整的参考和其他用于导出模型的选项。

编辑: 如果此方法引发 ValueError: Couldn't find trained model at ./tf. 错误,您可以尝试使用我在 .[=15= 中记录的解决方法]