The world’s leading publication for data science, AI, and ML professionals.

When Your Machine Learning model teams up with Django REST API, A successful deployment into…

A complete overview on how to build your machine learning model, and deploy it using Django REST API

Photo by SpaceX on Unsplash
Photo by SpaceX on Unsplash

Introduction

Let consider the following scenario: you have implemented an outstanding machine learning model that predicts if a patient is suffering or not from paludism. Then hospitals in your city want to integrate your model into their systems for general use. But those systems have been developed in completely different programming languages. Does it mean that they won’t be able to use your model anymore? The answer is No because, with RESTful services, your model can be made available to application developers, no matter which programming language they use.

This article has two sections:

  • Build a machine learning model that predicts if a given patient has diabetes or not.
  • Walkthrough the steps to REST-enable your machine learning model with Django REST APIs.

Section 1: Model building

The goal is not to have a fancy model, but to quickly have a model and serialize it in order to create the final REST API.

The following image describes how the model building project is structured.

Project structure by Author
Project structure by Author

Prerequisites

The purpose of this section is to install all the libraries required for the proper implementation of the classification model.

1- Create and activate the virtual environment

python3 -m venv mlAPIEnv   # Create the environment
source mlAPIEnv/bin/activate  # Activate the environment

2- Install pandas for data reading

pip install pandas

3- Install sklearn to import Machine Learning models

pip install -U scikit-learn

4- Install joblib to serialize the final model

pip install joblib

Content of each file

Once you run the following command you will get the image below showing: the first 7 rows, the last 7 rows, and the model performance from the classification report.

cd src # move to the scr folder
python3 run_training.py # Run the model training
head and tail of the data frame
head and tail of the data frame
classification report
classification report

Now, you should find a new file _diabete_detector_model.pkl under the model_ folder.

Your machine learning model is ready. Now it is time to REST-enable it with Django REST API.

Part 2: Implementation of the API

Prerequisites

The purpose of this section is to install all the libraries required for the proper implementation of the REST API.

1- Install Django

pip install django

2- Install Django REST framework

pip install djangorestframework

Django project and REST API

All the libraries are installed. The next step is to create a Django project and Django rest API.

1- Create your Django project from the root folder of the project.

django-admin startproject diabete_deployment

Running the previous instruction will create a new folder with the name diabete_deployment. Move into that folder and create your API.

2- Create your API folder

cd diabete_deployment # Move into the folder
django-admin startapp diabete_api # Create your API folder

From the image below, we can observe the previous additional folders with their corresponding files.

Project structure with additional folders by Author
Project structure with additional folders by Author

The files that are important to build our API are settings.py, _diabete_api/views.py, and diabete_deployment/urls.py._ We will then need to create additional files and folders later.

  • settings.py: used to register all the new apps/APIs that are part of the project. That new information is registered under the INSTALLED_APPS variable as highlighted below (diabete_api and rest_framework).
content of settings.py
content of settings.py

Every time the settings file is updated, it is important to make migrations, so that the changes are propagated in your database schema. Make sure you run the command under the diabetedeployment folder where the manage.py_ is located.

a- Run the migrations

python manage.py makemigrations

b- Migrate the changes

python manage.py migrate

Here is the output after running the migrate command

c- Run the server to check if everything is properly working so far

python manage.py runserver

The previous command generates the following information to access the URL which led to the Django interface, meaning that everything is working properly so far.

Watching for file changes with StatReloader
Performing system checks...
System check identified no issues (0 silenced).
November 29, 2021 - 03:47:18
Django version 3.2.9, using settings 'diabete_deployment.settings'
Starting development server at http://127.0.0.1:8000/
Django web interface, meaning the configuration was a success
Django web interface, meaning the configuration was a success
  • _diabete_api/views.py: used to implement all the functions that will be triggered when a specific route is called. In our case, the implementation will be on the prediction function. Our function will need to load the model in order to make predictions. To do so: we need to create a new folder static/model under the main diabete_deployment folder that will contain the serialized .pkl_ model.
  • Create a new file _diabete_api/urls.py_ with the following content
  • _diabete_deployment/urls.py_: used to link all the urls to their corresponding functions implemented in the views.py file.

    Now that all the important files have been updated and that new ones have been created, we are finally ready to relaunch the URL and make sure everything is working fine!

a- Run the server

python manage.py runserver

We can access the url generated by the previous command line.

System check identified no issues (0 silenced).
November 29, 2021 - 16:23:24
Django version 3.2.9, using settings 'diabete_deployment.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.

This is the screen we get and it points to the index page showing the information specified in the index function within the view file.

This page shows the HTTP 200 OK meaning that the request of the page was a success.

(Image by Author)
(Image by Author)

From that page, we can finally call the predict function by adding /predict to the URL.

(Image by Author)
(Image by Author)

From the previous page, we can emulate a prediction by pasting the following JSON data into the content section.

(Image by Author)
(Image by Author)

From the previous image, we observe the overall interaction, from request to prediction.

Test your awesome API with CURL

Here is the syntax for the post request we are making

curl -d "param1=val1&param2=val2...paramN=valN" [URL]/funct_to_call
  • param1: the first parameter and val1 is the corresponding value
  • param2: the second parameter and val2 is the corresponding value
  • etc.
  • URL: the URL to be used, in our case it is http://127.0.0.1:8000
  • _funct_to_call: the function to call for the request, in our case, it is /predict_

Adding up everything we get the following request:

curl -d  'pregnancies=6&glucose=148&bloodpressure=72&skinthickness=35&insulin=0&bmi=33.6&diabetespedigreefunction=0.627&age=50' http://127.0.0.1:8000/predict

Here is the result of the request:

{"info":"success","patient_status":1,"model_confidence_proba":63.36}

End of article

From this article, you have learned how to build your machine learning model and create a REST API using Django. You can now make your API available to hospitals of your city, and save lives 😃 .

Additional Ressources

Django REST framework

Testing REST API with Postman and curl

Bye for now 🏃🏾


Related Articles