Deploying Machine Learning Models in Production with Flask

By Steven | December 20, 2019


After we generate the Machine Learning models and tuning and evaluating them, we would then consider to apply the model into production. The blog here will show the steps to put the models we trained to production environments.

python environment setup

# install Anaconda
yum install libXcomposite libXcursor libXi libXtst libXrandr alsa-lib mesa-libEGL libXdamage mesa-libGL libXScrnSaver
download Anaconda from
bash ~/Downloads/
ln -s [python under anaconda/bin/]  /usr/bin/python  
ln -s [pip under anaconda/bin]  /usr/bin/pip

# install flask and gunicorn
source ~/.bashrc
pip install flask
pip install gunicorn
  • We’ll try out a simple Flask Hello-World application and serve it using gunicorn:
    • Open up your favourite text editor and create file in a folder
    • Write the code below:
cat ../../swam/

from flask import Flask

app = Flask(__name__)

def hello_world(username=None):

    return("Hello {}!".format(username))
steven@linux:/workspace/swam> gunicorn --bind hello_world:app
[2019-12-20 18:41:16 -0500] [4457] [INFO] Starting gunicorn 20.0.4
[2019-12-20 18:41:16 -0500] [4457] [INFO] Listening at: (4457)
[2019-12-20 18:41:16 -0500] [4457] [INFO] Using worker: sync
[2019-12-20 18:41:16 -0500] [4460] [INFO] Booting worker with pid: 4460

Viola! You wrote your first Flask application. As you have now experienced with a few simple steps, we were able to create web-endpoints that can be accessed locally.

Creating a Machine Learning Model

Suppose we have created our ML model using jupyter notebook. The model we have is called gridSearchCVModel:

    def trainGridSearchCVModel( self, corpus, label):
        self.gridSearchCVModel = GridSearchCV( self.pipeline, self.param_grid, cv = 5, verbose = 0)
        self.gridSearchCVModel =, label)

Saving Machine Learning Model : Serialization & Deserialization

We will store the model in our production environment:

pip install dill

from jupyter notebook,

import dill as pickle
file_name = ''
with open('./'+file_name, 'wb') as file:
    pickle.dump(gs_mnb.gridSearchCVModel, file)

go to our production environment, deploy the model and use the model to predict real data:

steven@linux:/workspace/swam/project> cat
import dill as pickle
import os, sys, re

file_name = open('', 'rb')
with open('', 'rb') as f:
   loaded_model =pickle.load(f)
twitt = ["$FB watching for bounce tomorrow"]
comments powered by Disqus