How to Integrate Machine Learning into Web Applications with Flask

guest_blog 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

#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, 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
def home():
    return render_template('index.html')
#To use the predict button in our web-app
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__":

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
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


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 05 Sep, 2020

Frequently Asked Questions

Lorem ipsum dolor sit amet, consectetur adipiscing elit,

Responses From Readers


Cabrel N'gako
Cabrel N'gako 08 Sep, 2020

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 14 Dec, 2021

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 26 Feb, 2022

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ã 07 Sep, 2023

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 08 Feb, 2024

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