You are on page 1of 18

Artificial Intelligence and Machine Learning

Model Integration
Supervised Learning

Prepared by Nima Dema

LEARNING GOALS AND PURPOSE

 Create Flask app for integrating machine learning model


 Integrate Machine learning model with flask app

1 | Page 13 May 2023


Artificial Intelligence and Machine Learning

Table of Contents
1. Create Directory...............................................................................................................3
2. Virtual environment.........................................................................................................4
2.1. Create virtual environment......................................................................................4
2.2. Open project in vscode..............................................................................................4
2.3. Activate virtual environment....................................................................................5
3. Install flask........................................................................................................................5
4. Create flask app................................................................................................................5
4.1. Create app.py file.......................................................................................................5
4.2. Write simple code in flask app.................................................................................6
4.3. Test your flask app....................................................................................................6
4.4. Check output in browser...........................................................................................7
5. Import Model....................................................................................................................7
6. Install numpy, pandas and sklearn.................................................................................7
6.1. Install numpy.............................................................................................................7
6.2. Install pandas.............................................................................................................8
6.3. Install sklearn.............................................................................................................8
7. Load model with pickle....................................................................................................8
8. Test model on sample data...............................................................................................9
9. Create UI for project........................................................................................................9
9.1. Create index page......................................................................................................9
9.2. Design index page....................................................................................................10
9.3. Create route for index page....................................................................................14
9.4. View index page in browser....................................................................................15
10. Get input from form....................................................................................................15
10.1. Set form action and method................................................................................15
10.2. Create route..........................................................................................................16
10.3. Get data from form field.....................................................................................16
10.4. output.html page..................................................................................................17
11. Test your app...............................................................................................................17

2 | Page 13 May 2023


Artificial Intelligence and Machine Learning

1. Create Directory
Firstly, we will create a folder in any location and give meaningful name related to your
project.

2. Virtual environment
Next, we will create virtual environment to install packages required for the project. To do
that, open cmd and change the current directory to newly created directory. Now you can
create virtual environment in that directory

2.1. Create virtual environment


To create virtual environment, type following command on the terminal

py –m venv .virtual environment name

Refer this link:


https://flask.palletsprojects.com/en/2.3.x/installation/#virtual-environments

3 | Page 13 May 2023


Artificial Intelligence and Machine Learning

2.2. Open project in vscode


To use virtual environment, you need to activate it first. Let’s activate from vscode. Open
your project in vscode first. In vscode, you should see your virtual environment.

2.3. Activate virtual environment


Open terminal in vscode. Choose command prompt terminal. Activate your virtual
environment by running activate file as shown below

3. Install flask
Now install necessary packages here. For example, you can install flask as shown below.

4 | Page 13 May 2023


Artificial Intelligence and Machine Learning

4. Create flask app


4.1. Create app.py file
In our project directory, outside the virtual environment, create a python file. I have created
as app.py as shown below.

4.2. Write simple code in flask app


Write following code in app.py file to run your first flask app. Or follow the link
https://flask.palletsprojects.com/en/2.3.x/quickstart/

4.3. Test your flask app


Now let’s test our first flask app. Run the following command in the terminal
flask --app filename(app in our case) run

5 | Page 13 May 2023


Artificial Intelligence and Machine Learning

Optionally, if you add following code at the end of your file, you may not need to re-run your
app again when you make changes in your code

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

4.4. Check output in browser

5. Import Model
Now it’s time we import our machine learning model in flask app. Store your saved
model in project directory.

6 | Page 13 May 2023


Artificial Intelligence and Machine Learning

6. Install numpy, pandas and sklearn


Let’s install some additional libraries such as numpy, pandas and sklearn.

6.1. Install numpy

6.2. Install pandas

6.3. Install sklearn


Note: Make sure you check the sklearn version in your jupyter notebook before installing
sklearn for your project.

7 | Page 13 May 2023


Artificial Intelligence and Machine Learning

7. Load model with pickle


Now that we have installed all the required libraries, let’s load our model in our application
using pickle module.
import pickle

app = Flask(__name__)

model = pickle.load(open("mymodel.pkl",'rb'))

8. Test model on sample data


Let us define some sample feature and use predict method to test our model in flask app.

#load our model


model = pickle.load(open("mymodel.pkl",'rb'))

#defining column name


cols = ['A1', 'A2', 'A3', 'A4', 'A5', 'A6', 'A7', 'A8', 'A9', 'A10', 'A11',
       'A12', 'A13', 'A14', 'A15']

#creating x_sample in dataframe format


x_sample = pd.DataFrame([['b', 23.92, 0.665, 'u', 'g', 'c', 'v', 0.165, 'f',
'f', 0, 'f',
        'g', 100.0, 0]],columns=cols)

#predicting passing sample value


result = model.predict(x_sample)

#printing output
print("The output for given sample is",result[0])

When you save the program, you will get output in terminal as shown below

8 | Page 13 May 2023


Artificial Intelligence and Machine Learning

9. Create UI for project


Yay, our model is working as expected. However, do not want to print output in terminal as
done in above step. Let’s create UI to get our data from user. To do that, create a
templates folder inside project folder. Inside the templates folder create
index.html page.

9.1. Create index page


Inside the templates folder create index.html page.

9.2. Design index page


The index.html page should contains form fields to get input for all the features from user.
The sample page for this project is given below.
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <link rel="stylesheet"
href="https://cdn.jsdelivr.net/npm/bootstrap@4.3.1/dist/css/bootstrap.min.css"
integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2M
Zw1T" crossorigin="anonymous">

    <meta name="viewport" content="width=device-width, initial-scale=1.0">

9 | Page 13 May 2023


Artificial Intelligence and Machine Learning

    <link
href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css"
rel="stylesheet">
    <script
src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min
.js"></script>
    <link
href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css"
rel="stylesheet">
  <script
src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min
.js"></script>
  <link rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
  <script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></
script>
  <script
src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></
script>
    <title>Loan</title>
    <style>
        body{width: 500px;
        margin: auto;}
    </style>
   
</head>
<body>
    <h2>Credit Card Approval</h2>

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


        <span>Choose First Feature A1</span>
        <br>
        <div class="form-check">
            <input class="form-check-input" type="radio" name="A1"
id="flexRadioDefault1" value="a">
            <label class="form-check-label" for="flexRadioDefault1">
              a
            </label>
        </div>
        <div class="form-check">
            <input class="form-check-input" type="radio" name="A1"
id="flexRadioDefault2" value ="b" checked>
            <label class="form-check-label" for="flexRadioDefault2">
              b
            </label>
        </div>

10 | Page 13 May 2023


Artificial Intelligence and Machine Learning

          <!-- <input type="text" name="gender" placeholder="enter gender"> --


>
          <br>

          <div class="form-group">
            <input type="text" class = 'form-control' name="A2" id=""
placeholder="Enter value for Feature A2">
        </div>

        <div class="form-group">
            <input type="text" class = 'form-control' name="A3" id=""
placeholder="Enter value for Feature A3">
        </div>

          <div>
            <select class="form-select" name = 'A4' aria-label="Default select
example">
                <option selected>Select value for Feature A4</option>
                <option value="u">u</option>
                <option value="y">y</option>
                <option value="l">l</option>
                <option value="t">t</option>

            </select>
          </div>
          <br>

          <div>
            <select class="form-select" name = 'A5' aria-label="Default select
example">
                <option selected>Select value of feature A5</option>
                <option value="g">g</option>
                <option value="p">p</option>
                <option value="gg">gg</option>
            </select>
          </div>
          <br>

          <div>
            <select class="form-select" name = 'A6' aria-label="Default select
example">
                <option selected>Select value of feature A6</option>
                <option value="c">c</option>
                <option value="d">d</option>
                <option value="cc">cc</option>
                <option value="i">i</option>
                <option value="j">j</option>
                <option value="k">k</option>

11 | Page 13 May 2023


Artificial Intelligence and Machine Learning

                <option value="m">m</option>
                <option value="r">r</option>
                <option value="q">q</option>
                <option value="w">w</option>
                <option value="x">x</option>
                <option value="e">e</option>
                <option value="aa">aa</option>
                <option value="ff">ff</option>

            </select>
          </div>
          <br>
          <div>
            <select class="form-select" name = 'A7' aria-label="Default select
example">
                <option selected>Select value of feature A7</option>
                <option value="v">v</option>
                <option value="h">h</option>
                <option value="bb">bb</option>
                <option value="j">j</option>
                <option value="n">n</option>
                <option value="z">z</option>
                <option value="dd">dd</option>
                <option value="ff">ff</option>
                <option value="o">o</option>
            </select>
          </div>
          <br>
          <div class="form-group">
            <input type="text" class = 'form-control' name="A8" id=""
placeholder="Enter value for Feature A8">
        </div>

        <div>
            <select class="form-select" name = 'A9' aria-label="Default select
example">
                <option selected>Select value of feature A9</option>
                <option value="t">t</option>
                <option value="f">f</option>
            </select>
          </div>
          <br>

          <div>
            <select class="form-select" name = 'A10' aria-label="Default
select example">
                <option selected>Select value of feature A10</option>
                <option value="t">t</option>

12 | Page 13 May 2023


Artificial Intelligence and Machine Learning

                <option value="f">f</option>
            </select>
          </div>
          <br>

        <div class="form-group">
            <input type="text" class = 'form-control' name="A11" id=""
placeholder="Enter value for Feature A11">
        </div>

        <div>
            <select class="form-select" name = 'A12' aria-label="Default
select example">
                <option selected>Select value of feature A12</option>
                <option value="t">t</option>
                <option value="f">f</option>
            </select>
          </div>
          <br>

        <div>
            <select class="form-select" name = 'A13' aria-label="Default
select example">
                <option selected>Select value of feature A13</option>
                <option value="g">g</option>
                <option value="p">p</option>
                <option value="s">s</option>

            </select>
          </div>

          <div class="form-group">
            <input type="text" class = 'form-control' name="A14" id=""
placeholder="Enter value for Feature A14">
        </div>

        <div class="form-group">
            <input type="text" class = 'form-control' name="A15" id=""
placeholder="Enter value for Feature A15">
        </div>
        <br>

          <input type="submit" class="btn btn-primary btn-sm btn-block"


value="Predict">
       
    </form>  
</body>
</html>

13 | Page 13 May 2023


Artificial Intelligence and Machine Learning

9.3. Create route for index page


In app.py, let’s add our index.html page in the route. To do that you need to import
render_template function from flask. And then change the route.

from flask import Flask,render_template

Route for index page


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

9.4. View index page in browser


Save the file and refresh your browser.

14 | Page 13 May 2023


Artificial Intelligence and Machine Learning

10. Get input from form


10.1. Set form action and method
Our page displays as expected in browser. Now get inputs from form fields. To do that, it is
required to specify action and method properties of the form element. It is already
specified in the index.html page for this project.

10.2. Create route


Now we need to define new route ‘/predict’ in app.py as defined in action
properties of the form element. Since we are getting data from user, you can erase the
x_sample created in step 8, one that is marked below.

After erasing above code, create route


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

10.3. Get data from form field


Inside the prediction() function, you need to get input from user. For this task, you need to
import request from flask.

15 | Page 13 May 2023


Artificial Intelligence and Machine Learning

Now you can use request to get data from form inputs from user. The code is shown below.
@app.route("/predict",methods=['POST'])
def prediction():
    if request.method == 'POST':
        A1 = request.form['A1']
        A2 = float(request.form['A2'])
        A3 = float(request.form['A3'])
        A4 = request.form['A4']
        A5 = request.form['A5']
        A6 = request.form['A6']
        A7 = request.form['A7']
        A8 = float(request.form['A8'])
        A9 = request.form['A9']
        A10 = request.form['A10']
        A11 = float(request.form['A11'])
        A12 = request.form['A12']
        A13 = request.form['A13']
        A14 = float(request.form['A14'])
        A15 = float(request.form['A15'])

        x_sample = [[A1,A2,A3,A4,A5,A6,A7,A8,A9,A10,A11,A12,A13,A14,A15]]
        X = pd.DataFrame(x_sample,columns=cols)

        result = model.predict(X)
        return render_template("output.html",value=result)

In the code shown above, create pandas dataframe from retrieved data. Then use your model
to make prediction on data retrieved from user. Then the prediction output is stored in
variable result and it is passed to output.html page as variable value. Create
output.html with following content.

10.4. output.html page


11.<!DOCTYPE html>
12.<html lang="en">
13.<head>
14.    <meta charset="UTF-8">
15.    <meta http-equiv="X-UA-Compatible" content="IE=edge">
16.    <meta name="viewport" content="width=device-width, initial-
scale=1.0">
17.    <title>Document</title>
18.</head>
19.<body>
20.    {{value[0]}}
21.   
22.</body>

16 | Page 13 May 2023


Artificial Intelligence and Machine Learning

23.</html>

11. Test your app


Now, refresh browser and enter all the fields of the form and click on predict button.
When you click on predict button, it should redirect to “/predict” route and get result +
or -. If positive, it means that your credit card will be approved.

Output:

To get result in output.html, jinja is used. To get more useful result, you may edit the
jinja code using if else condition. After adding if condition, try predicting again.
<body>
    {% if value[0] == "+"%}
        <p>Congratulation!!!, Your Credit card is approved.</p>
    {% else %}
        <p>Sorry, Your Credit card is not approved.</p>
    {% endif %}
</body>

17 | Page 13 May 2023


Artificial Intelligence and Machine Learning

Output

THANK YOU 

18 | Page 13 May 2023

You might also like