Open In App

Machine Learning Heart Disease Prediction Project in Django

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

Introduction-

In this article, we will implement a Machine Learning Heart disease Prediction Project using the Django framework using Python. Here, we will convert the code of the heart diseases prediction into a web form with the help of the Django framework basically we will create a form by using the Django framework and add the dataset of heart disease as a backend and we can predict then the heart diseases in any person by filling the form which we need to fill according to our health we will use the random classifier algorithm in Python for predict the heart diseases in any person.

Prerequisites

First, we create the virtual environment, then we will install Django.

pip install django

Then we created the project folder by using the following command.

django-admin startproject core

File structure:

Then we created some files and folders in our core folder the structure of the files like shown below,

file structure 

In the above file structure, we created the first core name project and in the same place, we created the predictor name in another folder in which we copy our _init_/py file and also created three files forms.py, urls.py, and views.py which are using for connect dataset and HTML code with each other and then 

Templates folder

We created our templates folder in which we created three HTML files for our frontend part design and we also created one static folder in which we saved our heart diseases dataset.please set all files like the above file structure and then start coding.

home.html 

In this file, we created a heading geeks for geeks by using Bootstrap and also one button on which click you can redirect to another page that has a form by filling those forms you can check whether you have diabetes or not we connected all files by using urls.py file by adding the path of all file in urls.py file.

HTML




{% load static %}  <!-- Load static files -->
  
<!DOCTYPE html>
<html lang="en">
  
<head>
  <!-- Required meta tags -->
  <meta charset="utf-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no" />
  <!-- Bootstrap CSS -->
    integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous" />
  <title>Disease Predictor</title>
  <link rel="stylesheet" href="{% static 'css/style.css' %}"<!-- Include custom CSS file -->
  
</head>
<style>
  .ok{
    color: green;
    font-size: 30px;
  }
</style>
  
<body>
  <br></br>
  <div class="container">
    <div class="card-body">
      <h5 class="card-title text-muted text-uppercase text-center">
        <strong  class="ok"> GEEKSFORGEEKS </strong><br> HEART DISEASES PREDICTION
      </h5>
      <a href="{% url 'heart' %}" class="btn btn-block btn-danger text-uppercase">KNOW HEART HEALTH STATUS</a<!-- Link to the 'heart' view -->
    </div>
  </div>
  </section>
</body>
  
</html>


Output:

Heart Disease Prediction Project.

home.html

base.html

in this file, we added only an HTML meta tag and add Bootstrap to design our form in which we need to feel our health details for predicting heart diseases in a person. or check person is affected by heart disease or not. and also we added the title by using the Django command as you can see in the code.

HTML




{% load static %}  <!-- Load static files -->
  
<!DOCTYPE html>
<html lang="en">
  
<head>
  <!-- Required meta tags -->
  <meta charset="utf-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no" />
  <!-- Bootstrap CSS -->
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous" />
  <title>{{title}}</title<!-- Set the page title dynamically using the 'title' variable -->
</head>
<body class="{{background}}"<!-- Set the body class dynamically using the 'background' variable -->
  {% block content %} {% endblock %}  <!-- Define a content block to be overridden in child templates -->
</body>
  
</html>


Output:

Heart Disease Prediction Project.

base.html

heart.html

In this file, we loaded our base.html file and only we added some bootstrap for design our form also the page we added one submit button and by using this file we call our base.html file and also we added flashing messages by using the Django command as you can see in code and these flashing message will show when we feel our health data and click on submit button and the flashing message will be shown like, you have heart diseases, or you don’t have heart diseases like that.

HTML




{% extends 'base.html' %}  <!-- Extend the 'base.html' template -->
  
{% block content %}  <!-- Define the content block to override -->
  
<style>
    .ok{
        color: green;
        font-size: 50px;
    }
</style>
  
<div class="container">
    <div class="display-4 my-2 text-center"><strong  class="ok"> GeeksForGeeks </strong> <br> Heart Disease Prediction</div>
    <hr />
  
    {% if context %}  <!-- Check if 'context' variable exists -->
    <div class="h1 my-2 text-center">
        You {{ context }} heart disease.
    </div>
    {% endif %}
  
    <div class="col-md-4">
        <form class="" method="POST" action="{% url 'heart' %}"<!-- Form to submit user data to 'heart' view -->
            {% csrf_token %}  <!-- Add CSRF token for form submission security -->
            {{ form }}  <!-- Render the HeartDiseaseForm object fields -->
  
            <div class="mt-4">
                <button type="submit" class="btn-lg btn-block btn btn-outline-danger mb-5">
                    Submit
                </button>
            </div>
        </form>
    </div>
</div>
  
{% endblock %}  <!-- End of content block -->


Output:

Heart Disease Prediction Project.

display result after  filling in data and click on submit button 

urls.py 

in this file, we added the path of predictor.urls file and imported some library which is imported for performing redirect operations from one page to another

Python3




from django.contrib import admin
from django.urls import path, include
from django.conf.urls.static import static
from django.conf import settings
  
urlpatterns = [
    path('admin/', admin.site.urls),  # URL pattern for the admin interface
    path('', include('predictor.urls'))]  # Include URLs from the 'predictor' app
    + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)  # Serve media files during development


setting .py 

In the setting.py file, we imported the first OS by using the import OS command and joint our templates folder with the settings.py file by using a one-line code.

‘DIRS’: [‘templates’]

Heart Disease Prediction Project.

forms.py

In this file, we created some parameters by using the Python form functionality we imported first Django, and then we created the heart disease form name class in which we define parameters and also add their meaning by using the label in Python and set all parameters by using the python widget= forms input functionality and make the same class for all parameter which name is form-control. we need to fill in all data to successfully predict heart diseases in a person.

Python3




from django import forms
  
class HeartDiseaseForm(forms.Form):
    # Define form fields for heart disease prediction
  
    age = forms.FloatField(label='Age', widget=forms.NumberInput(attrs={'class': 'form-control'}))
    # Field for age, represented as a float input widget
  
    sex = forms.FloatField(label='Sex', widget=forms.NumberInput(attrs={'class': 'form-control'}))
    # Field for sex, represented as a float input widget
  
    cp = forms.FloatField(label='CP', widget=forms.NumberInput(attrs={'class': 'form-control'}))
    # Field for chest pain type (CP), represented as a float input widget
  
    trestbps = forms.FloatField(label='TRESTBPS', widget=forms.NumberInput(attrs={'class': 'form-control'}))
    # Field for resting blood pressure (TRESTBPS), represented as a float input widget
  
    chol = forms.FloatField(label='CHOL', widget=forms.NumberInput(attrs={'class': 'form-control'}))
    # Field for serum cholesterol level (CHOL), represented as a float input widget
  
    fbs = forms.FloatField(label='FBS', widget=forms.NumberInput(attrs={'class': 'form-control'}))
    # Field for fasting blood sugar (FBS), represented as a float input widget
  
    restecg = forms.FloatField(label='RESTECG', widget=forms.NumberInput(attrs={'class': 'form-control'}))
    # Field for resting electrocardiographic results (RESTECG), represented as a float input widget
  
    thalach = forms.FloatField(label='THALACH', widget=forms.NumberInput(attrs={'class': 'form-control'}))
    # Field for maximum heart rate achieved (THALACH), represented as a float input widget
  
    exang = forms.FloatField(label='EXANG', widget=forms.NumberInput(attrs={'class': 'form-control'}))
    # Field for exercise-induced angina (EXANG), represented as a float input widget
  
    oldpeak = forms.FloatField(label='OLDPEAK', widget=forms.NumberInput(attrs={'class': 'form-control'}))
    # Field for ST depression induced by exercise relative to rest (OLDPEAK), represented as a float input widget
  
    slope = forms.FloatField(label='SLOPE', widget=forms.NumberInput(attrs={'class': 'form-control'}))
    # Field for the slope of the peak exercise ST segment (SLOPE), represented as a float input widget
  
    ca = forms.FloatField(label='CA', widget=forms.NumberInput(attrs={'class': 'form-control'}))
    # Field for the number of major vessels colored by fluoroscopy (CA), represented as a float input widget
  
    thal = forms.FloatField(label='THAL', widget=forms.NumberInput(attrs={'class': 'form-control'}))
    # Field for thalassemia (THAL), represented as a float input widget


urls.py

In this file, we imported Django and our vies.py file and we simply added the path of the heart and home files by using their name. 

Python3




from django.urls import path
from . import views
  
urlpatterns = [
    path('heart', views.heart, name="heart"),
    path('', views.home, name="home"),
]


views.py

In this file, we import first all libraries which e need to predict heart diseases like Django, Numpy, and Pandas for the read-out dataset and also the Sklearn random classifier which algorithm we used to predict heart diseases in person also imported the predictor.form means we connect our form to this file.

#imported all library
from django.shortcuts import render
import numpy as np
import pandas as pd
from sklearn.ensemble import RandomForestClassifier
from predictor.forms import HeartDiseaseForm

After importing the library we created a functioning heart in which we read our dataset which we saved in a static folder. Here we define the all value parameter for predicting heart diseases we set the floating value for all parameters and then we created an array for all parameters then we apply a random classifier for predicting heart diseases in person and then we added the if and else condition like if are prediction equal to zero the person doesn’t have heart disease and if our prediction is equal to one then the person has heart disease. These types of massage will display on our display screen Lastly we added one more function for the home.html file.

Python3




from django.shortcuts import render
import numpy as np
import pandas as pd
from sklearn.ensemble import RandomForestClassifier
  
from predictor.forms import HeartDiseaseForm
  
  
def heart(request):
    # Read the heart disease training data from a CSV file
    df = pd.read_csv('static/Heart_train.csv')
    data = df.values
    X = data[:, :-1# Input features (all columns except the last one)
    Y = data[:, -1:]  # Target variable (last column)
  
  
    value = ''
  
    if request.method == 'POST':
        # Retrieve the user input from the form
        age = float(request.POST['age'])
        sex = float(request.POST['sex'])
        cp = float(request.POST['cp'])
        trestbps = float(request.POST['trestbps'])
        chol = float(request.POST['chol'])
        fbs = float(request.POST['fbs'])
        restecg = float(request.POST['restecg'])
        thalach = float(request.POST['thalach'])
        exang = float(request.POST['exang'])
        oldpeak = float(request.POST['oldpeak'])
        slope = float(request.POST['slope'])
        ca = float(request.POST['ca'])
        thal = float(request.POST['thal'])
  
        # Create a numpy array with the user's data
        user_data = np.array(
            (age,
             sex,
             cp,
             trestbps,
             chol,
             fbs,
             restecg,
             thalach,
             exang,
             oldpeak,
             slope,
             ca,
             thal)
        ).reshape(1, 13)
  
        # Create and train a Random Forest Classifier model
        rf = RandomForestClassifier(
            n_estimators=16,
            criterion='entropy',
            max_depth=9
        )
  
        rf.fit(np.nan_to_num(X), Y)  # Train the model using the training data
        rf.score(np.nan_to_num(X), Y)  # Evaluate the model's accuracy
        predictions = rf.predict(user_data)  # Make predictions on the user's data
  
        if int(predictions[0]) == 1:
            value = 'have'  # User is predicted to have heart disease
        elif int(predictions[0]) == 0:
            value = "don\'t have"  # User is predicted to not have heart disease
  
    return render(request,
                  'heart.html',
                  {
                      'context': value,
                      'title': 'Heart Disease Prediction',
                      'active': 'btn btn-success peach-gradient text-white',
                      'heart': True,
                      'form': HeartDiseaseForm(),
                  })
  
  
def home(request):
    return render(request,
                  'home.html')


Output:

To run the Django project run the following command in your terminal and open the browser:

python manage.py runserver

The accuracy of a random classifier for heart disease prediction is 78 % percent.



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads