freeze_model.py 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. import os, argparse
  2. import tensorflow as tf
  3. from tensorflow.python.framework import graph_util
  4. dir = os.path.dirname(os.path.realpath(__file__))
  5. def freeze_graph(model_folder):
  6. # We retrieve our checkpoint fullpath
  7. checkpoint = tf.train.get_checkpoint_state(model_folder)
  8. input_checkpoint = checkpoint.model_checkpoint_path
  9. # We precise the file fullname of our freezed graph
  10. absolute_model_folder = '/'.join(input_checkpoint.split('/')[:-1])
  11. output_graph = absolute_model_folder + '/frozen_model.pb'
  12. # Before exporting our graph, we need to precise what is our output node
  13. # This is how TF decides what part of the Graph he has to keep and what part it can dump
  14. # NOTE: this variable is plural, because you can have multiple output nodes
  15. output_node_names = 'generate_output/output'
  16. # We clear devices to allow TensorFlow to control on which device it will load operations
  17. clear_devices = True
  18. # We import the meta graph and retrieve a Saver
  19. saver = tf.train.import_meta_graph(input_checkpoint + '.meta', clear_devices=clear_devices)
  20. # We retrieve the protobuf graph definition
  21. graph = tf.get_default_graph()
  22. input_graph_def = graph.as_graph_def()
  23. # We start a session and restore the graph weights
  24. with tf.Session() as sess:
  25. saver.restore(sess, input_checkpoint)
  26. # We use a built-in TF helper to export variables to constants
  27. output_graph_def = graph_util.convert_variables_to_constants(
  28. sess, # The session is used to retrieve the weights
  29. input_graph_def, # The graph_def is used to retrieve the nodes
  30. output_node_names.split(",") # The output node names are used to select the usefull nodes
  31. )
  32. # Finally we serialize and dump the output graph to the filesystem
  33. with tf.gfile.GFile(output_graph, 'wb') as f:
  34. f.write(output_graph_def.SerializeToString())
  35. print('%d ops in the final graph.' % len(output_graph_def.node))
  36. if __name__ == '__main__':
  37. parser = argparse.ArgumentParser()
  38. parser.add_argument('--model-folder', type=str, help='Model folder to export')
  39. args = parser.parse_args()
  40. freeze_graph(args.model_folder)