Tips for regenerating a model while replacing INPUT Placeholder in Tensorflow's FreezeGraphed .pb file [Replace / Replace / Convert / Change / Update / Replace]

** [1,?,?, 3] ** in a .pb file defined with an input size of ** Placeholder ** [1, 513, 513, 3] A sample program that regenerates .pb by forcing it to replace ** Placeholder ** in.

** name ='image' ** part allows you to freely specify the name of the replaced Placeholder. The ** ʻimage: 0 ** part of ** ʻinput_map = {'image: 0': inputs} ** specifies the Placeholder name of the model before conversion.

replacement_of_input_placeholder.py


import tensorflow as tf
from tensorflow.tools.graph_transforms import TransformGraph

with tf.compat.v1.Session() as sess:

    # shape=[1, ?, ?, 3] -> shape=[1, 513, 513, 3]
    # name='image' specifies the placeholder name of the converted model
    inputs = tf.compat.v1.placeholder(tf.float32, shape=[1, 513, 513, 3], name='image')
    with tf.io.gfile.GFile('./model-mobilenet_v1_101.pb', 'rb') as f:
        graph_def = tf.compat.v1.GraphDef()
    graph_def.ParseFromString(f.read())

    # 'image:0' specifies the placeholder name of the model before conversion
    tf.graph_util.import_graph_def(graph_def, input_map={'image:0': inputs}, name='')
    print([n for n in tf.compat.v1.get_default_graph().as_graph_def().node if n.name == 'image'])

    # Delete Placeholder "image" before conversion
    # see: https://github.com/tensorflow/tensorflow/tree/master/tensorflow/tools/graph_transforms
    # TransformGraph(
    #     graph_def(),
    #     input_op_name,
    #     output_op_names,
    #     conversion options
    # )
    optimized_graph_def = TransformGraph(
                              tf.compat.v1.get_default_graph().as_graph_def(),
                              'image',
                              ['heatmap','offset_2','displacement_fwd_2','displacement_bwd_2'],
                              ['strip_unused_nodes(type=float, shape="1,513,513,3")'])

    tf.io.write_graph(optimized_graph_def, './', 'model-mobilenet_v1_101_513.pb', as_text=False)

Result


[name: "image"
op: "Placeholder"
attr {
  key: "dtype"
  value {
    type: DT_FLOAT
  }
}
attr {
  key: "shape"
  value {
    shape {
      dim {
        size: 1
      }
      dim {
        size: 513
      }
      dim {
        size: 513
      }
      dim {
        size: 3
      }
    }
  }
}
]

Graph Transform Tool https://github.com/tensorflow/tensorflow/tree/master/tensorflow/tools/graph_transforms

Recommended Posts

Tips for regenerating a model while replacing INPUT Placeholder in Tensorflow's FreezeGraphed .pb file [Replace / Replace / Convert / Change / Update / Replace]
Tips for implementing a slightly difficult Model or Training in Keras