How I Deployed a Machine Learning Application Using the Flask Webserver

4/5 - (4 votes)

Deployment of Machine Learning models to make them available to end users is the ultimate goal of data scientists. How can you develop a web application if you have little or no knowledge of web development? As data scientists, you can now see that learning Python for web development cannot be overemphasized.

There are many Python frameworks used in building Machine Learning web applications. A project tutorial showing how to build a Machine Learning web app using the Django web framework has been demonstrated.

πŸ‘©β€πŸ’» Recommended: How I Created a Machine Learning Web Application Using Django

In today’s tutorial, we are going to see how this can be done using the Flask web framework.

Flask is a micro framework written in Python for building interactive web pages. It is called a small framework because it is easy to read and understand once you become familiar with it.


The objective of this tutorial is to show you the steps I took to deploy a Machine Learning model using Flask. Specifically, you will learn how the Flask framework interacts with our Machine Learning models.

The Model

We start by creating a file in a new directory. Our task is to train a model to classify the gender of an individual based on height, weight and foot size. You can see that this is a classification problem. Hence, we will use Random Forest Classifier algorithm. Download the dataset from my GitHub page.

We keep things simple so we can focus on our objectives, that is, to implement Machine Learning using the Flask framework. The dataset has 155 rows and 4 features, including GENDER, the target feature. In the GENDER column, 1 means male and 2 means female.

import pandas as pd
from sklearn.ensemble import  RandomForestClassifier
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score
import joblib

df = pd.read_csv('gender_classifier.csv')
X = df.drop(['GENDER'], axis=1)
y = df.GENDER
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=.2, random_state=5)
model = RandomForestClassifier(), y_train.values)
preds = model.predict(X_test.values)
# 90.32258064516128

We achieved an accuracy score of 90% with this simple way we trained the model. The final thing to do in this file is to pickle the trained model for further use.

joblib.dump(model, 'rf_model.pkl')

If you have been following all along, I expect your folder to have the following files:

gender_classifier.csv rf_model.pkl

Creating a Flask App

If you are new to the Flask framework, this article can set you up for the remaining part of this tutorial. The first step in creating a flask app is to define the application object as an instance of the Flask class. Create a file named

from flask import Flask, request, render_template
import joblib
import pandas as pd

app = Flask(__name__)

@app.route('/', methods=['GET', 'POST'])
def index():
    if request.method == 'POST':
        model = joblib.load('rf_model.pkl')

        height = request.form['heit']
        hand_len = request.form['hlen']
        foot_len = request.form['flen']

        mapping = {1: 'Male', 2: 'Female'}

        df = pd.DataFrame([[height, hand_len, foot_len]], columns=['height', 'hand_len', 'foot_len'])
        prediction = model.predict(df.values)[0]
        results = mapping[prediction]

        return render_template('index.html', results=results)
    return render_template('index.html')

if __name__ == '__main__':

The __name__ variable is Python predefined variable used by Flask to find the location of all the resources necessary for the smooth running of the app.

We create a function known as the view function that handles the application routes. Routes are simply the URLs implemented by the application. The index() function is mapped to the route URL represented as / which means the home page. When a client requests a URL such as the above, Flask executes the view function.

The view function has a Python decorator @app.route. This links the function to the URL passed as an argument. Thus, when a client requests a given URL, Flask will not only execute the function, it will also pass the function’s return value back to the browser as a response.

πŸ‘©β€πŸ’» Recommended: An Introduction To Closures and Decorators in Python

The route has two methods, GET and POST. They are used to retrieve data from template files. In the template file, we will create a form where users will input their height, hand length and foot length. Are you starting to see the connection? Once the data are retrieved, the trained model is unpickled and used to make prediction based on the data.

All these will execute provided the request method is POST. The request method is used to send data to the server. Check out this article to learn more about them. How will Flask know if the request method is POST? We will find the answer when we create the template file.

Finally, we render the returned value using the render_template() method, which has the HTML file that will be displayed to the user. Notice the arguments passed to render_template() method. The results of the predictions!

Can you see how the Flask framework interacts with our Machine Learning model? Then, to run the Flask webserver, we use the method.

The Template File

Create a folder named templates. By now, your main folder should have the following files:

__pycache__  gender_classifier.csv  rf_model.pkl  templates 

Gender Classification

A Machine Learning model to determine the gender of an individual

Inside the template folder, create an index.html file.

<DOCTYPE html>
   <title>Gender Classification</title>
   <body style="background:black; color:white; text-align:center">
     <h1 style="color:blue">Gender Classification</h1>
      <h3>A Machine Learning model to determine the gender of an individual</h3>
        <form action="{{ url_for('index') }}" method="POST">
            <div style="width: 400px">
                    Height: <input type="number" value='0.00' step="0.01" name="heit" id="heit">

                    Hand Length: <input type="number" value='0.00' step="0.01" name="hlen" id="hlen">

                    Foot Length: <input type="number" value='0.00' step="0.01" name="flen" id="flen">
                {% if results %}
                <p>The individual is a {{ results }}</p>
                {% endif %}

The form element has the request method as POST. The action argument points to the index() view function. Once the submit button is pressed, the data collected through the form will be sent to the index() function. Then, the result will be generated and displayed.


We have created a Machine Learning web application using the Flask framework. Check out my GitHub page for the complete code. Keep practicing project tutorials like this. In no distant time, you will master the Flask framework.