Surya Sharma

Machine Learning Applications | Computer Vision

Use a frozen Tensorflow (keras) graph for predictions in PYTHON

This guide is a part of a series of articles that show you how to save a Keras model and use it for predictions in a Visual Studio C program.

In this guide we’ll use a frozen Keras (Tensorflow) graph to make predictions. As a note, this works only for graphs that are frozen with their weights. If the weights are not a part of the file, you will also have to load a checkpoint file (not covered in this guide). Additionally, make sure you don’t reset the graph after loading a file, otherwise your predictions won’t work.

Load the dataset and normalize

You will need the slope-dataset and the model saved in the previous guide (slopemodel.pb). Go ahead and load the dataset again (assuming you’re starting in a new file).

normdata[1]

We’re also going to pick a single sample to classify, this is the first sample i.e. normdata[1], which is a rising series (see above), and has a ground truth label label[1] = 1. This sample is forced into a (1,21) shape because tensorflow is expecting an input of shape (?, 21). Without specifying this parameter, this shape assigned would be (21,) which tensorflow doesn’t like.

Load the GRAPH

Lets load the .pb file, and read a list of all the operations available.

This should give us a long list of operations. I’ve listed some of them here:

Call a prediction

Note these are operations. Tensorflow operates on graphs, so the code defines them differently. For prediction we want the output of the last layer, i.e. Sigmoid, so we’ll call the output tensor as : import/dense_2/Sigmoid:0

This should give you a prediction on the sample that was provided as input, and the output should be: [[0.698449]]

Wait a minute…

Shouldn’t the prediction be 1 (rising) or 0 (falling)? Yes and no.
The prediction should be 1, but it isn’t. What we’re seeing is the output of the sigmoid function, which is the probability of the class being 1. Keras has two functions, predict, and predict_label. What you’re getting is the output of the predict() function.

How do you get a label?

You predict the label yourself. Thankfully, predicting the label from a probability in the case of a binary classification problem is easy to implement, return a 1 if the value is greater than 0.5, otherwise return a 0:

int(predictions > 0.5)

This line of code first gets a True or False value, then converts the returned value (True or False) to a number (0 or 1) so that we can use that label.

Moving on…

Now that we know how to load a graph and run a prediction using that graph, we’re ready to do the same thing using libtensorflow and C. But first, we must get libtensorflow, create a .lib file, and setup our Visual Studio environment.

Next Post

Previous Post

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

© 2020 Surya Sharma

Theme by Anders Norén