Blue
Blue

Reputation: 663

Save tensorflow checkpoint to .pb protobuf file

I have trained a pix2pix model on tensorflow and the model has been saved in the form of checkpoints with the following files:

model-15000.meta, model-15000.index, model-15000.data-00000-of-00001, graph.pbtxt, checkpoint.

Now, I want to convert it to a protobuf file (.pb) for deployment purposes. I came across the freeze_graph.py script to do so, but I am facing trouble with one of the arguments, it being output_node_names.

I have tried out a couple of layer names, but I get the following error:

AssertionError: generator/decoder_2/batchnorm/scale/gradients is not in graph

Unsure how to find the output_node_names

Upvotes: 5

Views: 7545

Answers (2)

ReInvent_IO
ReInvent_IO

Reputation: 477

Try the below code to convert meta to pb file:

import tensorflow as tf
#Step 1 
#import the model metagraph
saver = tf.train.import_meta_graph('./model.meta', clear_devices=True)
#make that as the default graph
graph = tf.get_default_graph()
input_graph_def = graph.as_graph_def()
sess = tf.Session()
#now restore the variables
saver.restore(sess, "./model")

#Step 2
# Find the output name
graph = tf.get_default_graph()
for op in graph.get_operations(): 
  print (op.name)

#Step 3
from tensorflow.python.platform import gfile
from tensorflow.python.framework import graph_util

output_node_names="predictions_mod/Sigmoid"
output_graph_def = graph_util.convert_variables_to_constants(
        sess, # The session
        input_graph_def, # input_graph_def is useful for retrieving the nodes 
        output_node_names.split(",")  )    

#Step 4
#output folder
output_fld ='./'
#output pb file name
output_model_file = 'model.pb'
from tensorflow.python.framework import graph_io
#write the graph
graph_io.write_graph(output_graph_def, output_fld, output_model_file, as_text=False)

Hope this works!!!

Upvotes: 2

steve
steve

Reputation: 51

I am having the same problem when trying to freeze the model.

AssertionError: pose:0 is not in graph

I am using this script to print all the tensor names, but I'm still getting the error.

import tensorflow as tf

from tensorflow.python.tools import inspect_checkpoint as chkp


meta_path = './data/trained_variables.ckpt.meta' # Your .meta file

with tf.Session() as sess:

# Restore the graph
saver = tf.train.import_meta_graph(meta_path)

# Load weights
saver.restore(sess,"/Users/me/Desktop/data/trained_variables.ckpt")

## Print tensors
chkp.print_tensors_in_checkpoint_file(file_name="/Users/me/Desktop/data/trained_variables.ckpt",
                                      tensor_name='',
                                      all_tensors=False,
                                      all_tensor_names=True)

Give it a shot, see if you can get the correct name. Let me know, I am facing the same problem.

Upvotes: 0

Related Questions