Exposing Keras as REST API

In my last blog post about Keras, you learned how to use the Kaggle dogs-vs-cats dataset. But would you like your friends to use your model to identify dogs and cats in pictures? Yes, this blog post is about it! You’ll learn how to expose your model as a REST API in a simple way. Lets go!

We’ll use the code created in “Using Kaggle datasets” by adding a modification to save the model. Then, download all the files and run the jupyter notebook to train and save your model.

Download here: https://github.com/waslleysouza/keras

The requirements.txt file has a list of all the libraries needed to install in your environment. There are two files, one for CPU and one for GPU.

In this post I’m using an Oracle Cloud GPU instance, so the GPU version is required for me.

Create a new environment using requirements.txt file.

conda create -n keras_api python=3.6 -y
activate keras_api
pip install --upgrade -r requirements-gpu.txt

The models.yaml file defines the REST API using Swagger 2.0.
I have defined in the file only one path that performs the image classification.

The dogsvscats.py file has the logic to preprocess images and execute the prediction.

The server.py file has the logic to start the server.

To start the server, run the server.py file.

python server.py

Open a browser and go to the URL:

http://<YOUR_IP>:5000/ui

To test the model, I used a picture of George (one of my dogs, the other one is called Peppa).

Now you have a REST API to upload an image and receive a prediction whether it’s a dog or a cat.

Have a good time!

Author: Waslley Souza

Consultor Oracle com foco em tecnologias Oracle Fusion Middleware e SOA. Certificado Oracle WebCenter Portal, Oracle ADF e Java.