5

我已经用 fastR-CNN 网络训练了一个对象检测模型,frozen_interface_graph.pblabel_map.pbtxt进行了训练。我想将它部署为 RESTAPI 服务器,以便可以从没有 Tensorflow 的系统中调用它。那是我遇到TFX的时候。

如何使用TFX tensorflow-model-server加载此模型并托管 RESTAPI,以便可以将图像作为 POST 请求发送以进行预测?

https://www.tensorflow.org/tfx/tutorials/serving/rest_simple这是我作为参考找到的,但模型的格式与我目前的格式不同。是否有任何机制可以让我重用我目前拥有的模型,或者我必须使用 Keras 重新训练并部署,如参考中所示。

4

1 回答 1

3

要将模型重用于 TFX,冻结图需要指定服务签名。尝试使用下面的代码将您的模型转换为savedmodel格式,该代码成功地创建了一个savedmodel.pb带有标签集“serve”的文件。

import tensorflow as tf
from tensorflow.python.saved_model import signature_constants
from tensorflow.python.saved_model import tag_constants

export_dir = './saved'
graph_pb = 'frozen_inference_graph.pb'

builder = tf.saved_model.builder.SavedModelBuilder(export_dir)

with tf.gfile.GFile(graph_pb, "rb") as f:
    graph_def = tf.GraphDef()
    graph_def.ParseFromString(f.read())

sigs = {}

with tf.Session(graph=tf.Graph()) as sess:
    # name="" is important to ensure we don't get spurious prefixing
    tf.import_graph_def(graph_def, name="")
    g = tf.get_default_graph()
    sess.graph.get_operations()
    inp = g.get_tensor_by_name("image_tensor:0")
    outputs = {}
    outputs["detection_boxes"] = g.get_tensor_by_name('detection_boxes:0')
    outputs["detection_scores"] = g.get_tensor_by_name('detection_scores:0')
    outputs["detection_classes"] = g.get_tensor_by_name('detection_classes:0')
    outputs["num_detections"] = g.get_tensor_by_name('num_detections:0')

    output_tensor = tf.concat([tf.expand_dims(t, 0) for t in outputs], 0)


    sigs[signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY] = \
        tf.saved_model.signature_def_utils.predict_signature_def(
            {"in": inp}, {"out": out})

    sigs["predict_images"] = \
    tf.saved_model.signature_def_utils.predict_signature_def(
        {"in": inp}, {"out": output_tensor} )

    builder.add_meta_graph_and_variables(sess,
                                         [tag_constants.SERVING],
                                         signature_def_map=sigs)

builder.save().

我们通过预测您提供的示例图像测试了转换后的模型。结果未显示任何预测,这可能意味着转换方法无法按预期工作。

至于你的问题:

“是否有任何机制可以让我重用我目前拥有的模型,或者我必须使用 Keras 重新训练和部署,如参考中所示?”

有了这个结果,最好只使用Keras重新训练您的模型作为您问题的答案,因为转换或重用您的冻结图模型不会成为解决方案。您的模型不保存为模型提供服务所需的变量,并且模型格式不适合生产环境。是的,这是遵循官方文档的最佳方式,因为您可以确信这会奏效。

于 2020-04-21T07:24:54.060 回答