Machine Learning Heart Disease Prediction Project in Django
Last Updated :
21 Mar, 2024
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 %}
<!DOCTYPE html>
< html lang = "en" >
< head >
< meta charset = "utf-8" />
< meta name = "viewport" content = "width=device-width, initial-scale=1, shrink-to-fit=no" />
integrity = "sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin = "anonymous" />
< title >Disease Predictor</ title >
< link rel = "stylesheet" href = "{% static 'css/style.css' %}" >
</ 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 >
</ div >
</ div >
</ section >
</ body >
</ html >
|
Output:
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 %}
<!DOCTYPE html>
< html lang = "en" >
< head >
< meta charset = "utf-8" />
< meta name = "viewport" content = "width=device-width, initial-scale=1, shrink-to-fit=no" />
< title >{{title}}</ title >
</ head >
< body class = "{{background}}" >
{% block content %} {% endblock %}
</ body >
</ html >
|
Output:
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' %}
{% block content %}
< 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 %}
< 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' %}" >
{% csrf_token %}
{{ form }}
< 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 %}
|
Output:
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),
path(' ', include(' predictor.urls '))] # Include URLs from the ' predictor' app
+ static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT)
|
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’]
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):
age = forms.FloatField(label = 'Age' , widget = forms.NumberInput(attrs = { 'class' : 'form-control' }))
sex = forms.FloatField(label = 'Sex' , widget = forms.NumberInput(attrs = { 'class' : 'form-control' }))
cp = forms.FloatField(label = 'CP' , widget = forms.NumberInput(attrs = { 'class' : 'form-control' }))
trestbps = forms.FloatField(label = 'TRESTBPS' , widget = forms.NumberInput(attrs = { 'class' : 'form-control' }))
chol = forms.FloatField(label = 'CHOL' , widget = forms.NumberInput(attrs = { 'class' : 'form-control' }))
fbs = forms.FloatField(label = 'FBS' , widget = forms.NumberInput(attrs = { 'class' : 'form-control' }))
restecg = forms.FloatField(label = 'RESTECG' , widget = forms.NumberInput(attrs = { 'class' : 'form-control' }))
thalach = forms.FloatField(label = 'THALACH' , widget = forms.NumberInput(attrs = { 'class' : 'form-control' }))
exang = forms.FloatField(label = 'EXANG' , widget = forms.NumberInput(attrs = { 'class' : 'form-control' }))
oldpeak = forms.FloatField(label = 'OLDPEAK' , widget = forms.NumberInput(attrs = { 'class' : 'form-control' }))
slope = forms.FloatField(label = 'SLOPE' , widget = forms.NumberInput(attrs = { 'class' : 'form-control' }))
ca = forms.FloatField(label = 'CA' , widget = forms.NumberInput(attrs = { 'class' : 'form-control' }))
thal = forms.FloatField(label = 'THAL' , widget = forms.NumberInput(attrs = { 'class' : 'form-control' }))
|
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):
df = pd.read_csv( 'static/Heart_train.csv' )
data = df.values
X = data[:, : - 1 ]
Y = data[:, - 1 :]
value = ''
if request.method = = 'POST' :
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' ])
user_data = np.array(
(age,
sex,
cp,
trestbps,
chol,
fbs,
restecg,
thalach,
exang,
oldpeak,
slope,
ca,
thal)
).reshape( 1 , 13 )
rf = RandomForestClassifier(
n_estimators = 16 ,
criterion = 'entropy' ,
max_depth = 9
)
rf.fit(np.nan_to_num(X), Y)
rf.score(np.nan_to_num(X), Y)
predictions = rf.predict(user_data)
if int (predictions[ 0 ]) = = 1 :
value = 'have'
elif int (predictions[ 0 ]) = = 0 :
value = "don\'t have"
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
Share your thoughts in the comments
Please Login to comment...