Deploy a machine learning model using Python Flask

Hello Guys.! Welcome to another great tutorial, Now its time to deploy your machine learning model. Don’t you think every time it’s a big task for you..? But, not anymore. I wanna help you to end up this task so easy.

Whenever you want to deploy your machine learning model, come to our website and copy the code and make small changes according to your machine learning model.

Alright..! First, you need to build your machine learning model and export that model using Python pickle or scikit-earn joblib. you can use either of them, both are giving the same results.

Here I exported the machine learning model using the Python pickle module. If you want to use sklearn joblib click here to see the code.

import pandas as pd
import numpy as np
import pickle
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score

df = pd.read_csv('Iris.csv')

#df.head()

#df.isna().sum()

x = df.drop(['Id','Species'],axis=1)
y = df['Species']

lr = LogisticRegression(class_weight='balanced')
lr.fit(x,y)
y_pred = lr.predict(x)

acc = accuracy_score(y,y_pred)
print('Accuracy:',round(acc,2)*100)

# lr.predict([[5.1,3.5,1.4,0.2]])[0]

with open('iris.pkl','wb') as f:
    pickle.dump(lr,f)



lr_model = pickle.load(open('iris.pkl','rb'))

lr_model.predict([[5.1,3.5,1.4,0.2]])[0]

I think you don’t need to do all these things, but this is a simple code how you can build machine learning model and predict for the test data and finally how you will export the machine learning model.

Now we are ready to deploy our machine learning model using Python flask.

Read more Articles on machine learning

Learn Machine learning

Deploy Machine learning model using Python Flask

Here is the code to deploy the machine learning model, you need to make changes according to your machine learning model. lets say, i used logistic regression so i imported that, but you may not need because your Machine learning algorithm is different from mine.

If you aren’t install flask then use this code in your command prompt or terminal

pip install flask
pip install sklearn
# app.py

from flask import Flask, render_template, request
import pickle
from sklearn.linear_model import LogisticRegression

app = Flask(__name__)


@app.route('/')
def index():
    return render_template('index.html')



@app.route('/predict',methods=['POST'])
def predict():

    if request.method == 'POST':

        spl = request.form['spl']
        spw = request.form['spw']
        ptl = request.form['ptl']
        ptw = request.form['ptw']

        data =[[float(spl),float(spw),float(ptl),float(ptw)]]

        lr = pickle.load(open('iris.pkl', 'rb'))
        prediction = lr.predict(data)[0]

    return render_template('index.html', prediction=prediction)



if __name__ == '__main__':
    app.run()

Remember, I created a form in index.html file with four text fields because our machine learning model trained with four features. And I get those four features of data or inputs in the app.py file.

You need to make changes according to your model training in index.html and app.py file also.

# templates/index.html


<!doctype html>
<html lang="en">
  <head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">

    <title>App</title>
  </head>
  <body>
    <h1>Hello, world!</h1>
    <div class="container text-center">

    <form action="/predict" method="POST">

        <input type="text" name="spl"  placeholder='Sepel Length(CM)'><br>
        <input type="text" name="spw"  placeholder='Sepel Width(CM)'><br>
        <input type="text" name="ptl"  placeholder='Petal Length(CM)'><br>
        <input type="text" name="ptw"  placeholder='Petal Width(CM)'><br>

        <button class='btn btn-success'>Predict</button>

    </form>

    <div class="row">
        
        {% if prediction %}
        <h2 class="text-warning">{{prediction}}</h2>            
        {% endif %}
            
    </div>

</div>

    <!-- Optional JavaScript -->
    <!-- jQuery first, then Popper.js, then Bootstrap JS -->
    <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
    <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js" integrity="sha384-OgVRvuATP1z7JjHLkuOU7Xw704+h835Lr+6QL9UvYjZE3Ipu6Tp75j7Bh/kR0JKI" crossorigin="anonymous"></script>
  </body>
</html>

I used bootstrap to give a better look to my interface, that’s totally optional to you.

Note: Don’t forget to make changes according your machine learning model.

I hope this tutorial helps you to deploy your machine learning models so quickly. Thank you so much for visiting us..!

2 thoughts on “Deploy a machine learning model using Python Flask”

Leave a Reply