7

I have a Tensorflow file AlexNet.pb. I am trying to load it then classify an image that I have. I can't find a way to load it then classify an image.

No-one seems to have a simple example of loading and running the .pb file.

halfer
  • 19,824
  • 17
  • 99
  • 186
Kong
  • 2,202
  • 8
  • 28
  • 56
  • Possible duplicate of [Tensorflow: how to save/restore a model?](https://stackoverflow.com/questions/33759623/tensorflow-how-to-save-restore-a-model) – E_net4 Apr 23 '19 at 13:11

2 Answers2

5

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,
    })
nessuno
  • 26,493
  • 5
  • 83
  • 74
  • Thanks nessuno. Do you know what `.pb` stands for in TensorFlow? How is it different from using `.h5` (HDF5, a binary format) to store TensorFlow models? – Josh Jul 31 '20 at 03:49
  • 1
    @Josh pb stands for "protobuf" – nessuno Jul 31 '20 at 11:52
-1

You can use opencv to load .pb models, eg.

net = cv2.dnn.readNet("model.pb")

Make sure you are using specific version of opencv - OpenCV 3.4.2 or OpenCV 4

piet.t
  • 11,718
  • 21
  • 43
  • 52
  • 1
    Using OpenCV to read .pb files is not the way. OpenCV is an image library, though it started giving support for the ML/DL models. The question is better answered in with respect to Tensorflow rather than OpenCV. – Abhishek Jain Feb 03 '20 at 13:05