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



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

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

acc = accuracy_score(y,y_pred)

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

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

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


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

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

app = Flask(__name__)

def index():
    return render_template('index.html')

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__':

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

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

# templates/index.html

<!doctype html>
<html lang="en">
    <!-- 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="" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">

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


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


    <!-- Optional JavaScript -->
    <!-- jQuery first, then Popper.js, then Bootstrap JS -->
    <script src="" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
    <script src="" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
    <script src="" integrity="sha384-OgVRvuATP1z7JjHLkuOU7Xw704+h835Lr+6QL9UvYjZE3Ipu6Tp75j7Bh/kR0JKI" crossorigin="anonymous"></script>

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