Deploying a Machine Learning Model using Flask for Beginners

Aishwarya Valse
Analytics Vidhya
Published in
6 min readAug 19, 2020

The deployment of the machine learning model is rarely discussed. Most of the data science programs, online courses do not focus on model deployment. It is one of the important and last stages in the machine learning life cycle. To start using your machine learning model for practical decision-making, it needs to be effectively deployed into production. The focus of this article is to deploy a machine learning model using a flask.

Here I am using mall customer dataset to understand customer behavior. We are going to build a clustering model on historic data. Using this model we can predict the behavior of the new customer.

Let’s build our model using k-means clustering.

  1. Import Libraries

We need to import all the required libraries

2. Get the data

Getting the dataset is not enough. We have to perform exploratory data analysis.

3. Perform Exploratory Data Analysis

I have performed some initial analysis of this data. In this article, we will not more focus on EDA.

4. Model Building

Now it’s time to cluster the data. Here we are clustering our data using k-means.

We are clustering our data based on annual income and spending scores. For our dataset, we are using the elbow method to find the optimum number of clusters.

Based on the elbow method, we could choose k=3 or 5. Let us try k=5 and visualize the clusters.

The above plot shows the distribution of the 5 clusters. We can interpret them as the following:

Cluster1: Cluster 1 contains the customers with medium annual income and medium annual spend

Cluster2: Cluster 2 contains the customers with medium to high annual income and low annual spend

Cluster3: Cluster 3 contains the customers with low annual income and low annual spend

Cluster4: Cluster 4 contains the customers with low annual income and high annual spend

Cluster5: Cluster 5 contains the customers with medium to high annual income and high annual spend

5. Model Deployment using Flask

Now our simple k-means model is ready. Convert the python object model into a character string using the pickle module. Any object in Python can be pickled so that it can be saved on disk.

Save the above model as .pkl file

Now our model is saved in the directory where our notebook is stored.

As of now, we developed a model i.e. model.pkl which can predict the behavior of the customer based on annual income and spending score.

Now we are designing a web application where the user will input the customer information and the data will be given the model, based on the trained data, the model will predict the behavior of the customer.

HTML Form: In order to collect information about the new customer, we create the HTML form.

<html> 
<body>
<h3>Customer Segmentation</h3>

<div>
<form action="/result" method="POST">
<label for="Annual Income">Annual Income</label>
<input type="text" id="Annual Income" name="Annual Income">
<br>
<label for="Spending Score (1-100)">Spending Score (1-100)</label>
<input type="text" id="Spending Score (1-100)" name="Spending Score (1-100)">
<br>
<input type="submit" value="Submit">
</form>
</div>
</body>
</html>

Output:

Create the following result.html file

<!doctype html>
<html>
<body>
<h1> {{ prediction }}</h1>
</body>
</html>

Here, we must create the templates folder inside the application directory and save the HTML files to the templates folder.

Create the templates folder
Save the HTML files to the templates folder

Now, install the flask with — pip install flask

Flask Script: Below is the flask code to create a very simple web server.

  1. Redirecting the API to collect the data

We need to import the flask module to build the python web application. We need to pass __name__ as the argument into the flask constructor. The route() function defines the URL mapping of the associated function. As we can see here, ‘/index’ URL is bound to the index() function which is responsible for accepting the data from the user. The render_template() function used to render the external HTML file.

2. Redirecting the API to predict the customer behavior

Here we are defining a function to predict the values. We load the model.pkl file and then use the model to predict the values. The /result URL is bound to the result() function which is responsible for returning the predicted values. The POST request is reading the input values from request.form.values().

3. Start the flask server

The run method of the flask is used to run the flask application on the local development server. Now open http://127.0.0.1:5000/index in your web browser. You should view the below home page.

Input the values and click on the submit button, it predicts the behavior of the new customer.

This is a simple tutorial for beginners to learn a flask for model deployment. I hope this is useful for you to deploy a machine learning model.

Here is the GitHub link for the code: https://github.com/aishwaryarajendragulve/Model-Deployment-using-Flask-for-Beginners/tree/master

I hope you find this article useful. You can read my other articles by following the given link, which are very interesting and engaging:

--

--

Aishwarya Valse
Analytics Vidhya

🚀 Data Science & ML Enthusiast 📊 | Blogger 🖋️ | Lifelong Learner 🌱 | Inspiring growth in tech & personal development 💡✨ | Let's code, learn, and thrive tog