要将模型重用于 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重新训练您的模型作为您问题的答案,因为转换或重用您的冻结图模型不会成为解决方案。您的模型不保存为模型提供服务所需的变量,并且模型格式不适合生产环境。是的,这是遵循官方文档的最佳方式,因为您可以确信这会奏效。