首页 > 解决方案 > 将 SERVING 元标记添加到 TensorFlow 中的冻结模型

问题描述

如何准备一个冻结的 Tensorflow 模型来服务?请注意,官方指南仅演示了如何使用检查点,但我想使用冻结模型。

使用冻结的 inception_v3 模型,我想添加SERVING元标记,以便该模型可以与 Tensorflow Serving 一起使用

inception_v3_2016_08_28_frozen.pb使用summarise_graph检查冻结模型,可以找到模型输入和输出张量:

Found 1 possible inputs: (name=input, type=float(1), shape=[1,299,299,3])
No variables spotted.
Found 1 possible outputs: (name=InceptionV3/Predictions/Reshape_1, op=Reshape)
Found 23853946 (23.85M) const parameters, 0 (0) variable parameters, and 0 control_edges
Op types used: 489 Const, 379 Identity, 188 Mul, 188 Add, 95 Conv2D, 94 Sub, 94 Rsqrt, 94 Relu, 15 ConcatV2, 10 AvgPool, 4 MaxPool, 2 Reshape, 1 BiasAdd, 1 Softmax, 1 Squeeze, 1 Placeholder
To use with tensorflow/tools/benchmark:benchmark_model try these arguments:
bazel run tensorflow/tools/benchmark:benchmark_model -- --graph=assets/inception_v3_2016_08_28_frozen.pb --show_flops --input_layer=input --input_layer_type=float --input_layer_shape=1,299,299,3 --output_layer=InceptionV3/Predictions/Reshape_1

这产生了输入张量input:0和输出张量InceptionV3/Predictions/Reshape_1:0。在我的脚本中,我使用它们来创建签名定义并保存更新后的版本。

model_path = './assets/inception_v3_2016_08_28_frozen.pb'
target_dir = './models/inception/3'

with tf.gfile.FastGFile(model_path, 'rb') as f:
    graph_def = tf.GraphDef()
    graph_def.ParseFromString(f.read())
    _ = tf.import_graph_def(graph_def, name='')

input_name = 'input'
output_name = 'InceptionV3/Predictions/Reshape_1'

with tf.Session() as sess:
    model_input = build_tensor_info(sess.graph.get_tensor_by_name(input_name + ':0'))
    model_output = build_tensor_info(sess.graph.get_tensor_by_name(output_name + ':0'))

    signature_definition = signature_def_utils.build_signature_def(
        inputs={input_name: model_input},
        outputs={output_name: model_output},
        method_name=signature_constants.PREDICT_METHOD_NAME)

    builder = saved_model_builder.SavedModelBuilder(target_dir)
    builder.add_meta_graph_and_variables(sess, [tag_constants.SERVING], signature_def_map={
        signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY: signature_definition
    }, clear_devices=True)
    builder.save()

不幸的是,我无法让如此创建的 protobuffer 文件工作。测试工具label_image.py不会产生正确的结果,尽管它确实适用于原始inception_v3_2016_08_28_frozen.pb文件。

$ python3 tensorflow/examples/label_image/label_image.py --graph models/inception/3/saved_model.pb

Traceback (most recent call last):
  File "tensorflow/examples/label_image/label_image.py", line 118, in <module>
    graph = load_graph(model_file)
  File "tensorflow/examples/label_image/label_image.py", line 31, in load_graph
    graph_def.ParseFromString(f.read())
google.protobuf.message.DecodeError: Error parsing message

但是标签已设置

$ saved_model_cli show --dir models/inception/3
The given SavedModel contains the following tag-sets:
serve

如此改变的冻结模型有什么问题?这将如何正确完成?

标签: pythontensorflowtensorflow-serving

解决方案


推荐阅读