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.
Asked
Active
Viewed 1.2k times
7
E_net4 - Krabbe mit Hüten
- 24,143
- 12
- 85
- 121
Kong
- 1,984
- 8
- 22
- 45
-
Possible duplicate of [Tensorflow: how to save/restore a model?](https://stackoverflow.com/questions/33759623/tensorflow-how-to-save-restore-a-model) – E_net4 - Krabbe mit Hüten Apr 23 '19 at 13:11
2 Answers
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
- 25,313
- 5
- 80
- 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
-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,400
- 21
- 42
- 50
Ankit Dwivedi
- 17
- 3
-
1Using 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