Integrating Machine Learning Into Web Applications With Flask
Integrating Machine Learning Into Web Applications With Flask
Source: Udemy
We all have come across various web applications that use machine learning. For example, Netflix and
YouTube use ML to personalize your experience by recommending you new content based on your viewing
history. This helps them make better decisions and understand the browsing behaviors of their users.
Even you can create such an application in which you feed your input data and it predicts the output for
you using your ML model. The machine learning models that you create can be put to better use if you can
integrate your models into an application. This not only highlights your ML knowledge but also your app
development skills.
In this article, I will teach you how to embed an ML model in your Web Application with Flask. Firstly, we
will create a simple linear regression model to predict the CO2 emission from vehicles. Then we will
develop a web application that takes the input to predict the emission.
Note: This is just a simple example . You can create your own machine learning models like regression,classification,clustering etc. and
deploy them on your web-app. The design of your application completely depends on your Web Development skills.
We use the built-in LinearRegression() class from sklearn to build our regression model. The following
code helps us save our model using the Pickle module. Our ML model is saved as “model.pkl”. We will
later use this file to predict the output when new input data is provided from our web-app.
Pickle : Python pickle module is used for serializing and de-serializing python object structures. The process to convert any kind of
python object (list, dict, etc.) into byte streams (0s and 1s) is called pickling or serialization or flattening or marshalling. We can
converts the byte stream (generated through pickling) back into python objects by a process called as unpickling.
model to current directory # Pickle serializes objects so they can be saved to a file, and loaded in
a program again later on. pickle.dump(regressor, open('model.pkl','wb')) ''' #Loading model to
compare the results model = pickle.load(open('model.pkl','rb')) print(model.predict([[2.6, 8,
10.1]])) '''
2. Develop your web application with Flask and integrate your model
Now that we have our model, we will start developing our web application with Flask. Those of you starting
out in Flask can read about it here.
Flask learning resources: Flask Tutorials by Corey Schafer, Learn Flask for Python — Full Tutorial
You can use the ‘pip install flask’ command. I use the PyCharm IDE to develop flask applications. To easily
install libraries in PyCharm follow these steps.
2.2. Import necessary libraries, initialize the flask app, and load our ML model:
We will initialize our app and then load the “model.pkl” file to the app.
#import libraries import numpy as np from flask import Flask, render_template,request import
pickle#Initialize the flask App app = Flask(__name__) model = pickle.load(open('model.pkl', 'rb'))
2.3. Define the app route for the default page of the web-app :
The decorator is telling our @app that whenever a user visits our app domain (localhost:5000 for local
servers) at the given .route(), execute the home() function. Flask uses the Jinja template library to
render templates. In our application, we will use templates to render HTML which will display in the
browser.
We create a new app route (‘/predict’) that reads the input from our ‘index.html’ form and on clicking the
predict button, outputs the result using render_template.
#To use the predict button in our web-app @app.route('/predict',methods=['POST']) def predict(): #For
Project Structure :
Project Structure
The project is saved in a folder called “heroku_app”. We first run the ‘mlmodel.py’ file to get our ML model
and then we run the ‘app.py’. On running this file, our application is hosted on the local server at port 5000.
You can simply type “localhost:5000″ on your web browser to open your web-application after running ‘app.py’
It is always a good idea to run your application first in the local server and check the functionality of your
application before hosting it online in a cloud platform. Let’s see what happens when we run ‘app.py’ :
Observe the URL (127.0.0.1:5000/predict), this is the use of app routes. On clicking the “Predict” button we
are taken to the predict page where the predict function renders the ‘index.html’ page with the output of
our application.
On the Project Structure, you might have noticed two new files named “Procfile” and “requirements.txt”.
These two files are required to deploy your app on Heroku.
Before creating Procfile, we need to install Gunicorn. You can use the command ‘pip install gunicorn’ or use
the above link to install libraries in PyCharm
A Procfile specifies the commands that are executed by a Heroku app on startup. Open up a new file
named Procfile (without any extension) in the working directory and paste the following.
3.2. Create requirements.txt: The requirements.txt file will contain all of the dependencies for the flask
app. Open a new file and name it as “requirements.txt”. Mention all the requirements as following :
Alternatively, you can also use the following command in your terminal in the working directory to create
this file:
To learn how to create a new repository, click here. You can take help from here if you want to learn how
you can upload files to your repository. Your repository should look somewhat like this once all files are
uploaded.
Note: All of these files in your repository should be at the working directory level and not in another folder
To deploy your app on Heroku from here on, follow the steps 2–3 in my following article: Deploying a Static
Web Application to Heroku
And That’s it !! Your application has been hosted on the Heroku Cloud Platform. You can share the
application link with your friends and family to show them what you have created. Anyone with access to
the Internet and your application will be able to use your application. How Exciting
Note: All the resources that you will require to get started have been mentioned and the links provided in this
article as well. I hope you make good use of it
I hope this article will help you host your ML Web-Application online using Heroku. Don’t forget to click on
the “clap” icon below if you have enjoyed reading this article. Thank you for your time.
Nakukl Lakhotia
Nakul has completed his B.Tech in Computer Science from Vellore Institute of Technology, Vellore. He is a
machine learning and NLP enthusiast and has worked as a Data Science Intern in CustomersFirst Now.
Guest Blog