Open In App

Machine Learning Diabetes Prediction Project in Django

Last Updated : 21 Mar, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we will create  Diabetes Prediction Project using the Django framework using Python. In this project, we are using a logistic regression algorithm of Python machine learning to predict Diabetes diseases in a person by observing the input values filled by the person according to their health.

Diabetes Prediction Project in Django

Basically, we will convert a Diabetes prediction code into a web system by using the Django framework Django is a Python framework that we use to convert a Python project into a web system and we will use the Diabetes Prediction dataset as the backend with the use of this system we can predict the person has Diabetes or not. We need to predict Diabetes diseases and after filling in the input values we need to click on predict button through which we can see the result which we display on the same page a flash massage.

Prerequisites

First, create a new folder and open that folder in vs studio and open the terminal and first run the following command for creating a virtual environment. Now we need to install Django which runs the command.

pip install django

Create a new project in Django by using the following command or running the following command in the terminal.

django-admin startproject DiabetesPrediction

File structure:

Django- Machiene Learning Diabetes Prediction Project

file structure

Templates Folder 

After that, we will make a template folder in which we create two files predict.html and home.html for making the frontend part of our Placement prediction system.

home.html: 

In this file, we create a simple home page in which we write a simple heading massage welcome to Diabetes prediction System and add one button to redirect to the form page which is the second page of our Diabetes prediction or redirect one page to another page we are using a form action tag which we write the function name home which we create view.py file and we added a render_templates for redirect to predict page. you can download the whole code of this project by click here.

HTML




{% load static %}
<!DOCTYPE html>
<html lang="en">
  
<head>
    <meta charset="UTF-8">
    <title>Home</title>
    <style type=text/css>
        div {
            color: 'white';
        }
  
        h2 {
            color: white;
            font-family: arial, sans-serif;
            font-size: 40px;
            font-weight: bold;
            margin-top: 200px;
            transform: 2s;
        }
  
  
        body {
            background-color: black;
            background-image: url(https://i.ibb.co/PNSXdwC/img4-3.jpg);
            background-size: cover;
            background-repeat: no-repeat;
  
  
        }
  
        input {
            background-color: #FFA500;
            border: 2px;
            color: white;
            padding: 16px 32px;
            font-size: 20px;
            font-weight: bold;
            cursor: pointer;
            margin-top: 15px;
            border: 2px solid white;
            border-radius: 10px;
  
        }
        input:hover{
            background-color: white;
            color: #FFA500;
            border: 2px solid #FFA500;
        }
  
        .gfg {
            color: green;
            background-color: white;
            padding: 6px 12px;
            width: 15%;
            border-radius: 10px;
            font-size: 30px;
        }
  
    </style>
</head>
  
<body>
    <div align='center'>
  
        <h2><em>
                <h1 class="gfg">GeeksForGeeks </h1>
                WELCOME TO DIABETES PREDICTION SYSTEM
            </em>
        </h2>
        <form action="predict">
            <input type="submit" value="Lets get started">
        </form>
  
    </div>
</body>
  
</html>


Output :

Django- Machiene Learning Diabetes Prediction Project

hme.html file

predict.html:

In this file, we created a simple form in which we need to fill in some input like health details like pregnancy, age, BMI,   and many other details which is a form required for predicting diabetes in person and also we added a predict button when we click on button it will show the result as a flash message on same display screen like person have diabetes or not flash massage for perform all operations in our prediction system we created a two function predict and result through which we connected all the files separated and display result.

HTML




{%load static%}
<!DOCTYPE html>
<html lang="en">
  
<head>
    <meta charset="UTF=8">
    <title> Prediction page</title>
    <style>
        td {
            font-size: 17px;
        }
  
        body {
            background-color: black;
            background-image: url(https://i.ibb.co/jZvBMgg/img4-4.jpg);
            background-size: cover;
            background-repeat: no-repeat;
  
        }
  
        .main {
              
            top: 80px;
            left: 110px;
            width: 550px;
            margin-left: 7%;
            background-color: white;
            border-radius: 15px;
            height: 110vh;
            align-items: center;
  
        }
  
        .main:hover {
            box-shadow: 50px 0px 20px 0px rgba(0, 0, 0, 0.2);
  
        }
  
        h1 {
            font-family: Times New Roman;
            margin: 20px, 0;
            color: #F6465B;
            font-size: 30px;
            font-weight: bold;
            animation-delay: 3.5s;
        }
  
        input[type=submit] {
            background-color: #FFA500;
            border: 2px;
            color: white;
            font-size: 15px;
            font-weight: bold;
            padding: 10px 16px;
            cursor: pointer;
            margin-top: 15px;
            border-radius: 10px;
        }
  
        input {
            padding: 20px, 0;
            margin: 20px, 0;
        }
  
        p {
            color: #ffffff;
        }
  
        .row em {
            color: #BF0A30;
  
        }
  
        .gfg {
            color: green;
            font-size: 30px;
        }
    </style>
</head>
  
<body>
    <p><em>WELCOME TO THE PREDICT PAGE</em></P>
    <div align='center' class="main">
        <h1 class="gfg">GeeksForGeeks </h1>
        <h1>It's just a prediction; do consult with a Doctor ????</h1> <br />
        <form action="result">
            <table>
                <tr>
                    <td align="right"> <strong>Pregnancies:</strong> </td>
                    <td align="left"><input type="text" name="n1"></td>
                </tr>
                <tr>
                    <td align="right"> <strong>Glucose:</strong> </td>
                    <td align="left"><input type="text" name="n2"></td>
                </tr>
                <tr>
                    <td align="right"> <strong>Blood Pressure:</strong> </td>
                    <td align="left"><input type="text" name="n3"></td>
                </tr>
                <tr>
                    <td align="right"> <strong>Skin Thickness:</strong> </td>
                    <td align="left"><input type="text" name="n4"></td>
                </tr>
                <tr>
                    <td align="right"> <strong>Insulin:</strong> </td>
                    <td align="left"><input type="text" name="n5"></td>
                </tr>
                <tr>
                    <td align="right"> <strong>BMI:</strong> </td>
                    <td align="left"><input type="text" name="n6"></td>
                </tr>
                <tr>
                    <td align="right"><strong>Diabetes Pedigree Function:</strong> </td>
                    <td align="left"><input type="text" name="n7"></td>
                </tr>
                <tr>
                    <td align="right"> <strong>Age:</strong> </td>
                    <td align="left"><input type="text" name="n8"></td>
                </tr>
            </table>
            <input type="submit" value="PREDICT">
        </form>
        <div class="row">
            <h2><em>{{result2}}</em></h2>
        </div>
    </div>
</body>
  
</html>


Output:

Django- Machiene Learning Diabetes Prediction Project

Predict.html file 

urls.py  

In this file, we must add all paths, import the py file via Django, and call each template one by one using the URLs functionality, as well as connect all files via the path method.

Python3




# code
from operator import index
from . import views
from django.contrib import admin
from django.urls import path
  
  
urlpatterns = [
    path('admin/', admin.site.urls),
    path("", views.home),
    path("predict/", views.predict),
    path("predict/result", views.result),
]


setting .py 

In this file, we import os and connect templates to the folder by using the following type of os.path joins code, for connecting the templates folder.

‘DIRS’: [os.path.join(BASE_DIR, ‘templates’)]

Setting.py file 

view.py

This is the main file of our project in which we will machine learning logistic regression algorithm to perform the operation of whether a person has Diabetes or not for which first we imported some library, first we imported  Django and pandas and used sklearn library to train our data and for use logistic regression we also imported logistic regression and also the accuracy_score

#import all library
from django.shortcuts import render
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score

We create three functions first for the home page, second for the display input form page, and third for the display result in which first we read our dataset by using pd.read, and then we train our dataset using train_ and train_Y and then we model our dataset and after that, we created 13  input using float and for fill person health details and after that, we use if and else condition like if our target is one its means Person have Diabetes prediction else Person doesn’t have Diabetes prediction which depends on the input values which is filled by according person report.

Python3




# code
from django.shortcuts import render
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score
  
# for call home.html
def home(request):
    return render(request, 'home.html')
  
# for call predict.html
def predict(request):
    return render(request, 'predict.html')
  
# for display result on same page
def result(request):
    data = pd.read_csv(r"diabetes.csv")
    X = data.drop("Outcome", axis=1)
    Y = data["Outcome"]
  
    X_train, X_test, Y_train, Y_test = train_test_split
                            (X, Y, test_size=0.2)
  
    model = LogisticRegression()
    model.fit(X_train, Y_train)
  
    val1 = float(request.GET['n1'])
    val2 = float(request.GET['n2'])
    val3 = float(request.GET['n3'])
    val4 = float(request.GET['n4'])
    val5 = float(request.GET['n5'])
    val6 = float(request.GET['n6'])
    val7 = float(request.GET['n7'])
    val8 = float(request.GET['n8'])
  
    pred = model.predict([[val1, val2, val3, 
                           val4, val5, val6, val7, val8]])
  
    result1 = ""
    if pred == [1]:
        result1 = "Oops! You have DIABETES ????."
    else:
        result1 = "Great! You DON'T have diabetes ????."
  
    return render(request, "predict.html", {"result2": result1})


Output:

Run the following command in the terminal

Python3




# code
from django.shortcuts import render
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score
  
# for call home.html
def home(request):
    return render(request, 'home.html')
  
# for call predict.html
def predict(request):
    return render(request, 'predict.html')
  
# for display result on same page
def result(request):
    data = pd.read_csv(r"diabetes.csv")
    X = data.drop("Outcome", axis=1)
    Y = data["Outcome"]
  
    X_train, X_test, Y_train, Y_test = train_test_split
    (X, Y, test_size=0.2)
  
    model = LogisticRegression()
    model.fit(X_train, Y_train)
  
    val1 = float(request.GET['n1'])
    val2 = float(request.GET['n2'])
    val3 = float(request.GET['n3'])
    val4 = float(request.GET['n4'])
    val5 = float(request.GET['n5'])
    val6 = float(request.GET['n6'])
    val7 = float(request.GET['n7'])
    val8 = float(request.GET['n8'])
  
    pred = model.predict([[val1, val2, val3,
                           val4, val5, val6, val7, val8]])
  
    result1 = ""
    if pred == [1]:
        result1 = "Oops! You have DIABETES ????."
    else:
        result1 = "Great! You DON'T have diabetes ????."
  
    return render(request, "predict.html", {"result2": result1})


python manage.py runserver

The accuracy of the prediction system is 80 % according to the logistic regression algorithm.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads