Srikanth Technologies

Deploying Machine Learning Model

In this blog, I will show how to build and deploy a Machine Learning model so that it can be used with simple Python program as well as a Web Application developed using Django.

Required Software

The following software is used to build a machine learning model, deploy model and create web application to use model.

I assume you are familiar with the above mentioned software.

Build Machine Learning Model

We build a Regression model using Logistic Regression to predict the probability of a student getting admission into University based on his GRE, TOEFL and CGPA.

Here is the code to build and pickle the model. I assume file - admission.csv is present in the current directory. My current directory is c:\dev\admission. You can download this file from here.

Run the following program using Python interpreter that comes with Anaconda.

So, start Anaconda prompt using Anaconda3 -> Anaconda Prompt or Anaconda Powershell Prompt. Run the following program as shown below and it will build a model and pickle it to lr_model.pickle file in the current directory.

(base) PS C:\dev\admission> python build_model.py
Accuracy with train data : 0.81
Accuracy with test data :  0.76
(base) PS C:\dev\admission>

build_model.py

# Import required libraries 
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
from sklearn.metrics import r2_score 

# Read data from admission.csv 
df = pd.read_csv("admission.csv")

# Consider only 3 features - Gre, Toefl, and Cgpa
# Chance is label 

X = df[['Gre','Toefl','Cgpa']]
y = df['Chance']

# Split data into train and test 
X_train, X_test, y_train, y_test = train_test_split(X,y, test_size=0.2, random_state=0)

# Fit or Train the Model
lr_model = LinearRegression()
lr_model.fit(X_train,y_train)

score = lr_model.score(X_train,y_train)
print(f"Accuracy with train data : {score:0.2f}")

# Evaluate Model using test data 
y_pred =lr_model.predict(X_test)

# Find out accuracy with test data 
r2score = r2_score(y_test,y_pred)
print(f"Accuracy with test data :  {r2score:0.2f}")

# Pickle model
pd.to_pickle(lr_model,'lr_model.pickle')

Use model and predict

Once model is pickled, it can be unpickled and used in any Python program.

We need to make sure the Python interpreter used to run our unpickled model is associated with required libraries like Pandas and Sklearn.

So, run predict.py from Anaconda prompt. Make sure file lr_model.pickle is in the current directory.

predict.py

import pandas as pd

# Unpickle model 
model = pd.read_pickle('lr_model.pickle') 

# Take input from user
gre = int(input("Enter GRE    : "))
tof = int(input("Enter TOEFL  : "))
cgpa = float(input("Enter CGPA : "))

# Predict chances 
result = model.predict([[gre,tof,cgpa]])  # input must be 2D array
print(f"Chances are : {result[0] * 100:.2f}%")

Here is the screenshot of running predict.py program.

(base) PS C:\dev\admission> python predict.py
Enter GRE   : 320
Enter TOEFL : 120
Enter CGPA  : 8.5
Chances are : 76.03%
(base) PS C:\dev\admission>
Once you have access to model (that was pickled), you can use it to predict chances by passing required input.

Build Web Application to use Model

Take the following steps to build a web application using Django that uses the model built in previously.
  1. Install django using conda.

    c:\dev\admission>conda install django
    
  2. Create a new project using django-admin.

    c:\dev\admission>django-admin startproject web
    
  3. Create a new application after getting into web folder.

    c:\dev\admission\web>python manage.py startapp admission        
  4. We need to add our application and INSTALLED_APPS list in settings.py, which is in web folder within web folder.

    INSTALLED_APPS = [
        'admission',  # Our Application 
        'django.contrib.admin',
        'django.contrib.auth',
        'django.contrib.contenttypes',
        'django.contrib.sessions',
        'django.contrib.messages',
        'django.contrib.staticfiles',
    ]
    
  5. Create the following function views in admission\views.py module.

    from django.shortcuts import render
    from django.http import HttpResponse
    import pandas as pd
    
    
    def admission_client(request):
        return render(request, 'admission.html')
    
    
    def predict_chances(request):
        # Receive data from client
        gre = int(request.GET['gre'])
        toefl = int(request.GET['toefl'])
        cgpa = float(request.GET['cgpa'])
    
        model = pd.read_pickle(r"c:\dev\admission\lr_model.pickle")
        chances = model.predict([[gre, toefl, cgpa]])
        return HttpResponse(f"{chances[0] * 100:.2f}%")
    
  6. Create the following template - admission.html inadmission\templates folder.

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Predict Admission Chances</title>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
        <script>
            function predict_chances() {
               url = "http://localhost:8000/predict?gre=" + $("#gre_score").val() +
                     "&toefl=" + $("#toefl_score").val() +
                     "&cgpa=" + $("#cgpa").val();
    
               // Make AJAX request
               $.get(url,
                     null,
                     function(result) {
                        $("#chances").text(result);
                     }
               );
            }
        </script>
    </head>
    <body>
    
    <h1>Predict Admission Chances</h1>
    GRE Score <br/>
    <input type="number" id="gre_score"/>
    <p></p>
    
    TOEFL Score <br/>
    <input type="number" id="toefl_score"/>
    <p></p>
    
    CGPA <br/>
    <input type="number" id="cgpa"/>
    <p></p>
    <button onclick="predict_chances()">Predict Chances</button>
    
    <h2 id="chances"></h2>
    </body>
    </html>
            
  7. Add the following entries in urls.py in web\web folder.

    from django.contrib import admin
    from django.urls import path
    from admission import views
    
    urlpatterns = [
        path('admission/', views.admission_client),
        path('predict/', views.predict_chances)
    ]
            

Testing Web application

Run Django development server as follows:

c:\dev\admission\web>python manage.py runserver 
While server is running, go to browser and enter the following url:

http://localhost:8000/admission
The following page is displayed. Enter GRE, TOEFL and CGPA in the given text boxes and click on Predict Chances button. It will display chances of getting admission for the given details as shown below.