How to Build a Prediction API with Keras + Flask in Under 50 Lines

As almost everyone knows, Pickle is one of the main projects for object serialization when we talk about Machine Learning (scikit-learn). However, as you know, Keras does not support Pickle. (and in the official documentation, the Keras team does not recommend using pickle or cPickle to save models in Keras). There are some solutions that can be used to overcome these limitations, such as this great library called Keras Pickle Wrapper and this very good post by Zach Moshe. But, if you want to use Keras’s default options for model serialization and create a Flask API to service your models, this code sketch below might help you (or you can go to github to get the code directly):  

```python
import os
import keras
import numpy as np
from flask import jsonify
from flask import request
from flask import Flask
from keras.models import model_from_json
from keras.models import load_model

# Let's startup the Flask application
app = Flask(__name__)

# Model reload from jSON:
print('Load model...')
json_file = open('models/keras_v1.00_model.json', 'r')
loaded_model_json = json_file.read()
json_file.close()
keras_model_loaded = model_from_json(loaded_model_json)
print('Model loaded...')

# Weights reloaded from .h5 inside the model
print('Load weights...')
keras_model_loaded.load_weights("models/keras_v1.00_weights.h5")
print('Weights loaded...')

# Processing data from request and transform inside numpy array
def get_predict_data(data_unprocessed):
    print('Load data...')
    x = np.array(data_unprocessed)
    print('Data loaded...')
    return x

# URL that we'll use to make predi... [truncated]

```