Surya Sharma

Machine Learning Applications | Computer Vision | This website may be my recipe book.

Freeze a Keras Model to a Tensorflow graph (python)

This article 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.

This article will guide you in creating a simple Keras model and then exporting it a Keras graph. It is part of a tutorial on Using a Keras Model For inference in C.

Lets start by creating a simple model in Keras that predicts if a series of numbers is increasing or decreasing. For example, the series 1,2,3,4,5 is increasing, while the series 5,4,3,2,1 is decreasing.

Dataset

We’ll use slope-lownoise.txt. Each row in this text file is a series of numbers. The first number in each row is the class (0: decreasing or 1: increasing). The other 21 numbers are the numbers in the series. Download here.

Preamble

Lets import the things we need, load the data into our python program program, and normalize it.

Here’s an example of the second sample after normalization that was visualized using the command plt.plot(normdata[1]). label[1] = 1 (since it it a rising series).

normdata[1]

Create the network

Lets create a simple sequential model in Keras train it on the dataset. I like importing modules when I need them rather than at the start of code. This helps me remember and understand what I need and why I need it.

Freeze the model to a TF graph

We’re almost at the home stretch. We’re going to take this model (with it’s weights) and freeze them to a TF graph in a .pb file. For this, we’re going to get the TF session from the Keras backend, use a function to convert this to a frozen TF graph, then save this TF graph to a file.

Now save the graph to a file

And that’s it! We’re now ready to use this frozen graph and run inference (predictions) using Tensorflow. We’ll first test it in python, and then test it using libTensorflow in C.

Next Post

Previous Post

Leave a Reply

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

© 2024 Surya Sharma

Theme by Anders Norén