Designing an interactive web application to deploy the ML model using flask
In this article, I will share my experience in creating an interactive web application out of the ML model using the Flask framework. For demonstration purposes, I am using a model of my own that predicts the price of used cars in major cities of India. Dataset used here is from a hackathon hosted by MachineHack. Go to the hackathon homepage to know more about the dataset. Dataset set contains features like Location, Manufacture details, car features such as Fuel type, Engine, and usage parameters. To understand the code some basic knowledge of HTML and JQuery is useful but not mandatory. I will try my best to explain as we go along.
I encourage you to look at files as I go along explaining things. Go to this git repository and download the webApp folder to your local. Please refer to PricePredictions_UsedCars.ipynb
if you want to understand the featurization and model selection pipeline. Have a glance at the working application.
This application is developed using the Flask web development framework. Web application setup contains two files
1. Application.py — python script that handles routing and preforms computation in the backend.
2. index.html — HTML file that acts as a GUI interface between client and server. It allows users to submit inputs and transfers them to application.py for computation and renders output on the interface.
Other python objects used in Flask application:
- GBM_Regressor_pipeline.pkl — Pickle object that encodes all the preprocessing, feature transformation, and model trained model parameters. Sklearn’s pipeline is a great way to store work-flow for reproducibility as in this case. Raw inputs from users passed into the pipeline which applies transformations and then predicts price.
- Encoded_dicts.pkl- There are categorical variables in features. we need to pass them along with the encoded numerical values. This pickle object stores the mapping hash table.
- model2brand.pkl -Model feature is partially dependent on the Brand feature. Dependent in the sense a set of models are unique to a particular brand. When a user selects a brand, only the models that belong to the selected brand should appear in model selection dropdown object (
choose a model
). To make it possible, we need to store a dictionary of the brand and models set mappings i.e brand as key and set of car models belong to that brand as value. This is used to filter models for the user-selected brand.
{'Fiat': ['Siena', 'Punto', 'Avventura', 'Grande', 'Petra', 'Linea']}
Explore the contents in Application.py
Importing required libraries
Loading inputs
@application.before_first_request
is the decorator that calls the function startup
when the server starts. The function loads all the python objects.
@application.route
decorator calls background_process
API, whenever this route is requested. This function uses default inputs ('GET' method) when the page is loaded and retrieves inputs from request objects ('POST' method) as well. This function compute price based on provided inputs and outputs prediction in JSON
format.
finally,
Renders index.html and Also pass other arguments to be used inside the template (dictionaries in this case).
Explore Contents in Index.html
The core purpose of index.html is to get user arguments from the client-side and pass them to application.py script for processing and retrieve prediction. We need to create interactive elements that make it easy for the user to submit inputs.
As we noticed we have both numerical and categorical features. For collecting numerical inputs, I will use slider objects and for categorical inputs, it is appropriate to use dropdown objects.
Slider object
Let’s take a slider object HTML
snippet and understand what's happening.
div
tag separates objects within it from other elements. It's always preferable to separate objects from each other.label
tag used to show the user what field he is providing input for (variable is Year in this case).span
tag allows us to highlight part of the text enclosed withinlabel
tag. Only the text inside this tag can be highlighted(right now it is empty).input
tag is the one that receives input from the user. The min and max attributes decide slider range, value attribute holds selected value by the user, class tells the type of object (slider in this case) and step decides step size of slider movement.
Note: id
attribute in each tag is important as it serves as a unique identifier of objects or tags, therefore, no two tags should have the same id.
Making Slider object interactive
Now that we have created a slider object which allows the user to select a value between a certain range. To let the user know what value he has selected we can pass the selected value inside the span tag. Let see how it is done.
the above snippet is Jquery script (a proxy of javascript that makes simple to code).
What this snippet does is:
- It creates a slider3variable which tag element with attribute
id=year_range
. This allows us to retrieve or modify attribute values. - As we are interested user-selected value stored in the value attribute.
slider3.val()
fetches this value and passing it inside html() in the$("#Year").html()
as text making it appear inside the tag withid=Year
(span tag inside Yearlabel
tag).
Now, all we did is to read the value attribute from the input tag and pass it along inside the label tag. But, right now the object is not capable of recording other than the default value (provided by us). We need to make it detect slider movement and read the corresponding user-selected value.
slider3.change()
detects slider movement of slider3
object and then calls function()
that does the same as the above one except and updates text inside label tag making it interact with slider object.
Dropdown object
As I already mentioned, the dropdown object is used for categorical variables where the user selects an option and this option needs to be mapped to the numerical value, unlike slider objects where the user input value is directly passed for model prediction. To achieve this, we need to have mapping python dictionaries.
below is the mapping hash table for the variable brand.
Let us understand how we can create a dropdown allowing users to pass input.
The select
tag in the above HTML snippet creates an empty dropdown list. To fill a dropdown with possible options, we use option
tag inside select
tag to store keys. But, what if we have a lot of keys to fill in which makes this job cumbersome. In such a case, we can iterate the dictionary keys.
The above code creates a variable brands
that stores le_brands_Encdict dictionary passed by index()
function from application.py. while iterating dictionary keys it fetches value stores in variable value
and then passes it inside a option
tag created along with the key.
option
tags are appended inside the select
tag with id=brand
filling the dropdown with options.
below Jquery snippet fetches the brand the user has selected from dropdown options.
$('#brand option:selected').html()
I have explained taking two objects as reference (year for numerical and brand for categorical). we have similar objects for the rest of the variables.
Passing user inputs to the function
Till now we have discussed how we could get user inputs in the background. Now, we have to pass those to background_process()
function that computes price.
Let’s go through the above code snippet. $(document).mouseup()
and $(document).on
are the event listeners that captures mouse clicks and drop-down changes respectively, then calls fetchdata()
function that routes to url_for('background_process')
calling background_process
API (refer to application.py file). The data argument inside the function collects user inputs from all the objects and passes them to background_process
function as arguments that compute price and then output a JSON object. The output JSON object has keyprice_prediction
and price computed is value.
Upon successful success: function(data)
takes JSON object and then passes predicted value to theupdate_dashboard
function which in turn passes it to the tag with id = estimated_price
(price label
tag) displaying the predicted price on the web page.
I hope the ideas discussed in this article help you in designing a user-friendly application interface to deploy the model you built.
If you are also interested in the applications deploying on AWS platform. Please check out my other article where I discussed the application deployment step by step using Elastic Beanstalk service.
Thank you for reading. Any thoughts would be appreciated. please CLAP if you liked it.