Friday, September 20, 2024
Google search engine
HomeData Modelling & AIHow to Integrate Machine Learning into Web Applications with Flask

How to Integrate Machine Learning into Web Applications with Flask

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

05 Sep 2020

RELATED ARTICLES

Most Popular

Recent Comments