Implement Machine Learning model in Django

It is amazing to create a machine learning model on your own but it will be more fascinating if others can use it as well. But the user may or may not be familiar with the technology or can be from a non technical field so how can they use it ? How to implement machine learning model? It is possible if we can deploy our machine learning model in an interactive web app which users might find easy to use.

Machine-Learning-Django

Django REST Framework is a robust and flexible toolkit for building Web APIs with the help of which we can deploy or implement Machine Learning models as well. In this blog, we will learn how to implement a Machine Learning model in Django Rest Framework, with the help of the Django REST framework, complex machine learning models can be easily used just by calling an API endpoint.

Django Machine Learning Implementation

Step 1. Save your model.

The first thing to do is save your model. If you had created your own model then saved it, I had to use pickle module here to save my model.

import pickle
with open("breast_cancer.pkl","wb+") as f:
    pickle.dump(model,f)


Step 2 . Save your Machine Learning model in the model folder.

We first need to create a Django project, after that create a path for the machine learning model in our django folder so that we can use it, for this we need to save our model in a folder inside the django folder.

1. Go to your Django folder.

2. Create new folder named as model (you can use whatever name you want )

3.  Now move your saved ml model in this folder.

Machine-Learning-Django :- model folder

Step 3. Implementing Machine Learning Model in Django

Till now we have added our ml model in our django folder now for using it we are first going to create an index page where we are going to take input from the user, for this we first need to create a path for our index page, then add its function in the views file.

1. In app > urls.py add the path for the main html page.

Urls.py

from django.urls import path,include
from . import views
urlpatterns = [
    path('',views.index, name="index"),
    path('predict',views.predict,name="predict")
]

2. In app > views.py add the function for the main page.

Views.py

from django.shortcuts import render
 # Create your views here.
def index(request):
    return render(request,'index.html')

3. Code of main index page Django folder > template > index.html

Index.html

<html>
<head>
 <title>Deploy Ml model</title>
</head>
<body>
 <form action="predict" method="post">
 {% csrf_token %}
 <span class="label-input100">Full Name :</span>
 <input class="input100" type="text" name="name" placeholder="Enter full name"><br><br>
 <span class="label-input100">Your Age :</span>
 <input class="input100" type="text" name="age" placeholder="Enter Your Age"><br><br>
 <span class="label-input100">Mean_Radius :</span>
 <input class="input100" type="text" name="radius" placeholder="Enter Mean Radius"><br><br>
 <span class="label-input100" style="left:-120px;">Mean_Texture :</span>
 <input class="input100" type="text" name="texture" placeholder="Enter Mean Texture"><br><br>
 <span class="label-input100" style="left:-130px;">Mean_Perimeter :</span>
 <input class="input100" type="text" name="perimeter" placeholder="Enter Mean Perimeter"><br><br>
 <span class="label-input100">Mean_Area :</span>
 <input class="input100" type="text" name="area" placeholder="Enter Mean Area"><br><br>
 <span class="label-input100" style="left:-150px;">Mean_Smoothness :</span>
 <input class="input100" type="text" name="smoothness" placeholder="Enter Mean Smoothness"><br><br>
 <button class="contact100-form-btn">Submit</button>
 </form>
</body>
</html>

Output :-

Machine-Learning-Django :- Output of Index HTML page

After adding a html page we now need to load the model, predict the output and print the result in html page. We are going to create a path for action attribute of our form of index page, which is going to take all the inputs and predict the output. We will first add the path of that action in urls.py.

4. In app > urls.py add the path for the submit button action.

Urls.py

from django.urls import path,include
from . import views
urlpatterns = [
    path('',views.index, name="index"),
    path('predict',views.predict,name="predict")
]

 We are then going to create a function for the action in views.py. Here we are first going to import all the essential modules. Pickle module will help us to load our model. Pandas module will help us to create a dataframe.

5. In app > views.py add the function to load the model, predict the value and return the result html page.

Views.py

import math
import pandas as pd
import pickle
model=pickle.load(open('./model/breast_cancer.pkl','rb+'))
def predict(request):
     if request.method=='POST':       
        temp={}
        temp['texture']=float(request.POST.get('texture'))  
        temp['radius']=float(request.POST.get('radius'))
        temp['perimeter']=float(request.POST.get('perimeter'))
        temp['smoothness']=float(request.POST.get('smoothness'))
        temp['area']=float(request.POST.get('area'))      
        testdata=pd.DataFrame({'x':temp}).transpose()
        scoreval=model.predict(testdata)[0]
        if scoreval==0:
            ans="Benign"
        else:
            ans="Malignant"
        return render(request,'result.html',{'result':ans})

6. Code for result html page Django Folder > template > result.html

Result.html

<html>
<head>
    <title>Deploy ML</title>
</head>
<body>
    <h1>According to our calculation we can predict that you have : {{result}}</h1>
</body>
</html>

Output :-

Machine-Learning-Django :- Output for Result HTML page.

Quick Revision

1. Save your model.

2. Move your ml model in the model folder of your django folder.

3. Create index html page in Django Folder > template >index.html.

4. Create a path for the index page in app > urls.py.

5. Make a function for the index page in app > views.py.

6. Create result html page in Django Folder > template >result.html.

7. Create a path for submit button action in app > urls.py.8. Create a function for prediction in app > views.py.

GitHub link :-

https://github.com/jaya2320/DeployML