How to Integrate Machine Learning into Web Applications with Flask

Last Updated : 05 Sep, 2020
7 min read

Web Applications with Flask

import pandas as pd
from sklearn.linear_model import LinearRegression
import pickle

df = pd.read_csv("FuelConsumption.csv")
#use required features
cdf = df[['ENGINESIZE','CYLINDERS','FUELCONSUMPTION_COMB','CO2EMISSIONS']]

#Training Data and Predictor Variable
# Use all data for training (tarin-test-split not used)
x = cdf.iloc[:, :3]
y = cdf.iloc[:, -1]
regressor = LinearRegression()

#Fitting model with trainig data
regressor.fit(x, y)

# Saving 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]]))
'''

 

#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'))
#default page of our web-app
@app.route('/')
def home():
    return render_template('index.html')
#To use the predict button in our web-app
@app.route('/predict',methods=['POST'])
def predict():
    #For rendering results on HTML GUI
    int_features = [float(x) for x in request.form.values()]
    final_features = [np.array(int_features)]
    prediction = model.predict(final_features)
    output = round(prediction[0], 2) 
    return render_template('index.html', prediction_text='CO2    Emission of the vehicle is :{}'.format(output))

Web Applications with Flask

if __name__ == "__main__":
    app.run(debug=True)

Web Applications with Flask - Projct Structure

Project Structure

Web Applications with Flask

Now, let’s enter the required values and click on the “Predict” button and see what happens.

Web Applications with Flask

web: gunicorn app:app
Flask==1.1.1
gunicorn==20.0.4
pandas==0.25.2
scikit-learn==0.23.2
numpy==1.17.3
pickle4==0.0.1
sklearn==0.0
pip freeze > requirements.txt

Image for post

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

About the Author

Author

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.

Responses From Readers

Clear

Cabrel N'gako
Cabrel N'gako

Hi I'm new in flask and I really enjoyed this tutorial, thank N. Lakhotia. Please I wish to continue follow your tutorials.

Shailly Raj
Shailly Raj

hello. i was trying this same code where i have to take only 1 input from user and the error is occurring with $ prediction = model.predict(final_features) the error says "ValueError: X has 1 features, but LinearRegression is expecting 3 features as input." I cant understand how to fix it. Please help

Gift
Gift

WHOA!!!!!!!! This is actually insane I've always wanted to integrate an ml model into a web app but I just could not think of anything the best part is that I can actually create a model like this and integrate it into my own web app!!

Mirzã
Mirzã

Does the model always runs on the new inputs and find the best fit line by regression on the data. Or model just runs a single time to give us best fit equation nd then everytime we have user input the best fit equations just take input and provides output.? Please clarify this i would really appreciate.

Dusan Simic
Dusan Simic

Hello, the way you mentioned is very simple. Anyway, I really enjoyed this tutorial, but I want to know how to integrate AI into frontend frameworks such as React, Next quickly. Thanks

Congratulations, You Did It!
Well Done on Completing Your Learning Journey. Stay curious and keep exploring!

We use cookies essential for this site to function well. Please click to help us improve its usefulness with additional cookies. Learn about our use of cookies in our Privacy Policy & Cookies Policy.

Show details

-->