【发布时间】:2019-05-22 15:42:33
【问题描述】:
我已经成功训练了一个 Keras 模型并将其用于我的本地机器上的预测,现在我想使用 Tensorflow Serving 来部署它。我的模型将图像作为输入并返回掩码预测。
根据文档here 我的实例需要像这样格式化:
{'image_bytes': {'b64': base64.b64encode(jpeg_data).decode()}}
现在,我的 Keras 模型自动保存的 saved_model.pb 文件具有以下张量名称:
input_tensor = graph.get_tensor_by_name('input_image:0')
output_tensor = graph.get_tensor_by_name('conv2d_23/Sigmoid:0')
因此我需要用不同的signature_def 保存一个新的saved_model.pb 文件。
我尝试了以下方法(请参阅here 以供参考),它有效:
with tf.Session(graph=tf.Graph()) as sess:
tf.saved_model.loader.load(sess, ['serve'], 'path/to/saved/model/')
graph = tf.get_default_graph()
input_tensor = graph.get_tensor_by_name('input_image:0')
output_tensor = graph.get_tensor_by_name('conv2d_23/Sigmoid:0')
tensor_info_input = tf.saved_model.utils.build_tensor_info(input_tensor)
tensor_info_output = tf.saved_model.utils.build_tensor_info(output_tensor)
prediction_signature = (
tf.saved_model.signature_def_utils.build_signature_def(
inputs={'image_bytes': tensor_info_input},
outputs={'output_bytes': tensor_info_output},
method_name=tf.saved_model.signature_constants.PREDICT_METHOD_NAME))
builder = tf.saved_model.builder.SavedModelBuilder('path/to/saved/new_model/')
builder.add_meta_graph_and_variables(
sess, [tf.saved_model.tag_constants.SERVING],
signature_def_map={'predict_images': prediction_signature, })
builder.save()
但是当我将模型部署到 AI 平台并请求预测时,我收到以下错误:
RuntimeError: Prediction failed: Error processing input: Expected float32, got {'b64': 'Prm4OD7JyEg+paQkPrGwMD7BwEA'} of type 'dict' instead.
阅读答案here,我也尝试重写
input_tensor = graph.get_tensor_by_name('input_image:0')
作为
image_placeholder = tf.placeholder(tf.string, name='b64')
graph_input_def = graph.as_graph_def()
input_tensor, = tf.import_graph_def(
graph_input_def,
input_map={'b64:0': image_placeholder},
return_elements=['input_image:0'])
(错误地)理解这将在我的输入张量之上添加一个层与匹配的'b64' 名称(根据文档)接受一个字符串并将其连接到原始输入张量
但是来自AI平台的错误是一样的。
(我用于请求预测的相关代码是:
instances = [{'image_bytes': {'b64': base64.b64encode(image).decode()}}]
response = service.projects().predict(
name=name,
body={'instances': instances}
).execute()
其中image 是numpy.ndarray 的dtype('float32'))
我觉得我已经足够接近了,但我肯定错过了一些东西。你能帮忙吗?
【问题讨论】:
-
我还是一样,你能给我一个你使用占位符的例子吗?