difference between Tensorflow's Graph and GraphDef

Graph or Computional Graph is the core concept of tensorflow to present computation. When you use tensorflow, you firstly create you own Computation Graph and pass the Graph to tensorflow. How to do that? As you may know, tensorflow support many front-end programming languages, like Python, C++, Java and Go and the core language is C++; how do the other languages transform the Graph to C++? They use a tool called protobuf which can generate specific language stubs, that's where the GraphDef come from. It's a serialized version of Graph.

which one should I have to run a graph loaded from protobuf file (.pb)

You should read your *pb file using GraphDef and bind the GraphDef to a (default) Graph, then use a session to run the Graph for computation, like the following code:

import tensorflow as tf
from tensorflow.python.platform import gfile
with tf.Session() as sess:
    model_filename ='PATH_TO_PB.pb'
    with gfile.FastGFile(model_filename, 'rb') as f:
        graph_def = tf.GraphDef()
        graph_def.ParseFromString(f.read())
        g_in = tf.import_graph_def(graph_def)
LOGDIR='/logs/tests/1/'
train_writer = tf.summary.FileWriter(LOGDIR)
train_writer.add_graph(sess.graph)

GraphDef is the proto defined here. This is the serialized version of graph. You can print, store, or restore a GraphDef in any TensorFlow frontend (Python, R, C++, Java, ...). When it is stored to a file, usually the file name ends with .pb, so you should use GraphDef for .pb files.

Graph is an abstract concept, which can be in different forms for different frontends. For Python, tf.Graph() would return an Python object (code) that contains the GraphDef and many utilities.

For python, you can load a GraphDef using tf.import_graph_def. Here is a simple code example:

  with tf.gfile.GFile(graph_def_pb_file, "rb") as f:
    graph_def = tf.GraphDef()
    graph_def.ParseFromString(f.read())
  with tf.Graph().as_default() as graph:
    tf.import_graph_def(graph_def, name="")
    ...

Tags:

Tensorflow