Flask
In this section, we will use the Flask microserver framework provided by Python to make a web application that provides predictions. We will get a RESTful API that we can query to get our results. Before commencing, we need to install Flask (use pip):
- Let's begin by importing the packages:
import re
import pickle
import numpy as np
from flask import Flask, request, jsonify
from keras.models import load_model
from keras.preprocessing.sequence import pad_sequences
- Now, let's write a function that loads the trained model and tokenizer:
def load_variables():
global model, tokenizer
model = load_model('trained_model.h5')
model._make_predict_function() #https://github.com/keras-team/keras/issues/6462
with open('trained_tokenizer.pkl', 'rb') as f:
tokenizer = pickle.load(f)
The make_predict_function() is a hack that allows using keras models with Flask.
- Now, we'll define preprocessing functions similar to the training code...