Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use the tensorflow .pb file?

Tags:

tensorflow

I have a Tensorflow file AlexNet.pb I am trying to load it then classify an image that I have. I have searched for hours but I still cant find a way to load it then classify an image. Is it so obvious and that I am just so stupid because no one seems to have a simple example of loading and running the .pb file.

like image 855
Kong Avatar asked Jul 12 '18 07:07

Kong


People also ask

How do I open a .PB file?

If you cannot open your PB file correctly, try to right-click or long-press the file. Then click "Open with" and choose an application. You can also display a PB file directly in the browser: Just drag the file onto this browser window and drop it.

What is the use of .PB file?

The PB file extension is a data file format associated to Corel WordPerfect software. PB files and WordPerfect were developed by Corel Corporation. These files contain search and index information for referencing WordPerfect documents and are used for fast lookups or backups of documents.

What is .PB file in TensorFlow?

The . pb format is the protocol buffer (protobuf) format, and in Tensorflow, this format is used to hold models. Protobufs are a general way to store data by Google that is much nicer to transport, as it compacts the data more efficiently and enforces a structure to the data.


1 Answers

It depends on how the protobuf file has been created.

If the .pb file is the result of:

    # Create a builder to export the model
    builder = tf.saved_model.builder.SavedModelBuilder("export")
    # Tag the model in order to be capable of restoring it specifying the tag set
    builder.add_meta_graph_and_variables(sess, ["tag"])
    builder.save()

You have to know how that model has been tagged and use the tf.saved_model.loader.load method to load the saved graph in the current, empty, graph.

If the model instead has been frozen you have to load the binary file in memory manually:

with tf.gfile.GFile(frozen_graph_filename, "rb") as f:
    graph_def = tf.GraphDef()
    graph_def.ParseFromString(f.read())

graph = tf.get_default_graph()
tf.import_graph_def(graph_def, name="prefix")

In both cases, you have to know the name of the input tensor and the name of the node you want to execute:

If, for example, your input tensor is a placeholder named batch_ and the node you want to execute is the node named dense/BiasAdd:0 you have to

    batch = graph.get_tensor_by_name('batch:0')
    prediction = restored_graph.get_tensor_by_name('dense/BiasAdd:0')

    values = sess.run(prediction, feed_dict={
        batch: your_input_batch,
    })
like image 137
nessuno Avatar answered Sep 28 '22 21:09

nessuno