Skip to content
Snippets Groups Projects
Commit 8af32522 authored by Syed Haque's avatar Syed Haque
Browse files

all added

parent f79e4c3b
No related branches found
No related tags found
No related merge requests found
womens-diabetics-prediction-system
\ No newline at end of file **Members:**
Member 1: Haque, Syed Wassi Ul 22108223
<br/><br/>
Member 2: Mahir, Wasik , 00817406
<br/><br/>
**Title:** Women Diabetes Prediction System
<br/><br/>
**MyGit Repository Link: https://mygit.th-deg.de/sh13223/womens-diabetics-prediction-system**
**MyGit Wiki Repository Link:__**
<br/><br/>
**Project description:**
A machine learning model designed to predict diabetes in female patients.
This project uses SVM(Support Vector Machine) Algorithm to train on a given dataset.
Interactive GUI is developed using PyQt6 and css.
**Prerequisites:**
1. Pycharm or Vscode or any types of IDE.
2. Creating a virtual environment.
3. Libraries to be installed in virtual environment:
- PyQt6 = 6.6.1
- Pyqtgraph = 0.13.3
- Python = 3.11.7
- Numpy = 1.26.3
- Matplotlib = 3.8.2
- Pandas = 2.1.4
- Scikit-learn = 1.3.2
4. Diabetes Dataset(Source: Kaggle):
Link to download the data: (https://www.kaggle.com/code/sandragracenelson/diabetes-prediction/input)
**Installation:**
- Create and run a virtual environment
- Clone the git repository with the dataset file.
- Install necessary packages from requirement.txt file.
- Run main_diabetics.py.
**Basic Usage:**
1. Run the main_diabetics.py in any IDE.
2. Upon execution, a window will prompt the user to input their Glucose level, Blood Pressure, Age, Insulin, BMI, and Pregnancy status using sliding buttons. For Pregnancy status, use a tick button to indicate if applicable.
3. After inputting all details, click the "Predict" button to determine diabetic status."
4. To exit the widget, simply press the cross button in the top right corner of the widget.
**Implementation of the Requests:**
1. A Desktop App with PyQT6 has been developed.
2. A requirements.txt file is added with the necessary python libraries.
3. A README.md file is created with the structure description.
4. Virtual environment (venv) is created and used.
5. A free data source has been from Kaggle(Link has given above).
6. Data has been imported using csv format. (File name: diabetes_clean_03042021.csv) and can be seen from the terminal after running the app.
7. The data must be analyzed with Pandas methods, so that a user gets an overview.
8. The following functions have been used to get the overview of the data: dataframe.info(), dataframe.describe(),dataframe.corr(), dataframe.head(), dataframe.tail().
9. Three input widgets have been created.
10. Model has been trained using Scikit training model algorithm.( for our case we used SVM model algorithm)
11. Two output canvas have been for data visualization.
12. The app is reacting interactively according to the change of input parameter with a new prediction.
<br/><br/>
**Contribution List:**
1. Syed Wassi Ul Haque:
- Worked on Collection and Preprocessing of Dataset using Pandas.
- Modifying and Preparing Data with use of numpy arrays.
- Bug solving and creating Main window Graph to visualize the data on app using matplotlib.pyplot.
- Creating Histogram window Interface using PyQt6.
- Designing the app using css stylesheet.
2. Wasik Mahir:
- Creating a GUI Interface using PyQt6( Main window, Plot graph window)
- Getting User-Inputs using different GUI elements or creating widgets.
- Training and working Scikit-learn SVM Model.
- Integrating or connecting Scikit learn model with pyqt6 in order to get predictions in the app.
- Designing the app using css stylesheet.
chart-medium.png

548 B

This diff is collapsed.
health.png

5.35 KiB

image.jpg 0 → 100644
image.jpg

2.04 MiB

import sys
from PyQt6 import QtWidgets,QtGui
from pyqtgraph import PlotWidget, plot
import pyqtgraph as pg
from PyQt6.QtWidgets import QWidget,QHBoxLayout, QApplication,QSlider, QMainWindow,QLabel, QPushButton,QHBoxLayout, QVBoxLayout, QGridLayout, QCheckBox
from PyQt6.QtCore import Qt
from PyQt6.QtGui import QAction, QIcon,QPalette, QColor
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib
import matplotlib.pyplot as plt
from matplotlib.backends.backend_qtagg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.figure import Figure
matplotlib.use('Qt5Agg')
from sklearn.preprocessing import StandardScaler
from sklearn.model_selection import train_test_split
from sklearn import svm
from sklearn.metrics import accuracy_score
from PyQt6 import QtGui
diabetes = pd.read_csv('diabetes_clean_03042021.csv')
# highest correlation ---- x=age y=blood pressure
class MplCanvas(FigureCanvas):
def __init__(self, parent=None, width=5, height=2, dpi=100):
self.figure = Figure(figsize=(width, height), dpi=dpi)
self.axes = self.figure.add_subplot(111)
super(MplCanvas, self).__init__(self.figure)
class secondWindow(QMainWindow):
def __init__(self):
super().__init__()
# use global data
global diabetes
widget_histogram = QWidget()
# Vertical Layout
histogram_layout = QVBoxLayout()
# Create a new Canvas
self.histogram_screen = MplCanvas(self, width=5, height=2, dpi=100)
diabetes.hist(ax=self.histogram_screen.axes)
histogram_layout.addWidget(self.histogram_screen)
self.setCentralWidget(widget_histogram)
widget_histogram.setLayout(histogram_layout)
self.setMinimumSize(1500, 1000)
class thirdWindow(QMainWindow):
def __init__(self):
super().__init__()
global diabetes
self.graphWidget = pg.PlotWidget()
self.setCentralWidget(self.graphWidget)
self.x = diabetes["BMI"]
self.y = diabetes["Outcome"]
self.graphWidget.setBackground('w')
self.graphWidget.setLabel("left", "Diabetic Or Not Diabetic")
self.graphWidget.setLabel("bottom", "BMI")
pen = pg.mkPen(color=(255, 0, 0))
self.data_line = self.graphWidget.plot(self.x, self.y, pen=pen)
self.setMinimumSize(800, 400)
class MainWindow(QMainWindow):
def design(self):
layout3 = QHBoxLayout()
MainLayout = QHBoxLayout()
leftVerticalLayout = QVBoxLayout()
RightVerticalLayout = QVBoxLayout()
# setting window icon
self.setWindowIcon(QtGui.QIcon('health.png'))
#setting screen min size
self.setMinimumSize(1200, 800)
mainLabel = QLabel(" Women Diabetics Prediction System")
leftVerticalLayout.addWidget(mainLabel)
# checkbox button pregnancies
pregnanciesLabel = QLabel("Pregnancies", alignment=Qt.AlignmentFlag.AlignCenter)
pregnant_instruction = QLabel("Please click the box if Pregnant.", alignment=Qt.AlignmentFlag.AlignCenter)
leftVerticalLayout.addWidget(pregnanciesLabel)
leftVerticalLayout.addWidget(pregnant_instruction)
self.pregnancies_checkbox = QCheckBox(text="Not Pregnant")
leftVerticalLayout.addWidget(self.pregnancies_checkbox)
self.pregnancies_checkbox.stateChanged.connect(self.Pregnancies_onStateChanged)
# Silder button glucose
self.Glucose = QSlider(Qt.Orientation.Horizontal)
self.Glucose.setMinimum(30)
self.Glucose.setMaximum(200)
self.Glucose.valueChanged.connect(self.updateSlider_Glucose)
self.Glucose.setGeometry(5, 3, 20, 20)
self.selectedValue_glucose = QLabel(self)
self.selectedValue_glucose.setText(str(30))
glocoseLabel = QLabel("Glucose [30 - 200]", alignment=Qt.AlignmentFlag.AlignCenter)
leftVerticalLayout.addWidget(glocoseLabel)
leftVerticalLayout.addWidget(self.Glucose)
leftVerticalLayout.addWidget(self.selectedValue_glucose)
# Silder button blood pressure
self.BloodPressure = QSlider(Qt.Orientation.Horizontal)
self.BloodPressure.setMinimum(30)
self.BloodPressure.setMaximum(120)
self.BloodPressure.valueChanged.connect(self.updateSlider_BloodPressure)
self.BloodPressure.setGeometry(5, 3, 20, 20)
self.selectedValue_blood = QLabel(self)
self.selectedValue_blood.setText(str(30))
bloodpressureLabel = QLabel("Blood Pressure [30 - 120]", alignment=Qt.AlignmentFlag.AlignCenter)
leftVerticalLayout.addWidget(bloodpressureLabel)
leftVerticalLayout.addWidget(self.BloodPressure)
leftVerticalLayout.addWidget(self.selectedValue_blood)
# Silder button skin thickness
self.SkinThickness = QSlider(Qt.Orientation.Horizontal)
self.SkinThickness.setMinimum(0)
self.SkinThickness.setMaximum(100)
self.SkinThickness.valueChanged.connect(self.updateSlider_skinThickness)
self.SkinThickness.setGeometry(5, 3, 20, 20)
self.selectedValue_skin = QLabel(self)
self.selectedValue_skin.setText(str(0))
skinThicknessLabel = QLabel("Skin Thickness[0 - 100]", alignment=Qt.AlignmentFlag.AlignCenter)
leftVerticalLayout.addWidget(skinThicknessLabel)
leftVerticalLayout.addWidget(self.SkinThickness)
leftVerticalLayout.addWidget(self.selectedValue_skin)
# Silder button Insulin
self.Insulin = QSlider(Qt.Orientation.Horizontal)
self.Insulin.setMinimum(5)
self.Insulin.setMaximum(700)
self.Insulin.valueChanged.connect(self.updateSlider_insulin)
self.Insulin.setGeometry(5, 3, 20, 20)
self.selectedValue_insulin = QLabel(self)
self.selectedValue_insulin.setText(str(5))
insulinLabel = QLabel("Insulin [5 - 700]", alignment=Qt.AlignmentFlag.AlignCenter)
leftVerticalLayout.addWidget(insulinLabel)
leftVerticalLayout.addWidget(self.Insulin)
leftVerticalLayout.addWidget(self.selectedValue_insulin)
# Silder button BMI
self.BMI = QSlider(Qt.Orientation.Horizontal)
self.BMI.setMinimum(10)
self.BMI.setMaximum(80)
self.BMI.valueChanged.connect(self.updateSlider_BMI)
self.BMI.setGeometry(5, 3, 20, 20)
self.selectedValue_BMI = QLabel(self)
self.selectedValue_BMI.setText(str(10))
bmiLabel = QLabel("BMI [10 - 80]", alignment=Qt.AlignmentFlag.AlignCenter)
leftVerticalLayout.addWidget(bmiLabel)
leftVerticalLayout.addWidget(self.BMI)
leftVerticalLayout.addWidget(self.selectedValue_BMI)
# Silder button DiabetesPredegreeFunction
self.DiabetesPredegreeFunction = QSlider(Qt.Orientation.Horizontal)
self.DiabetesPredegreeFunction.setMinimum(0)
self.DiabetesPredegreeFunction.setMaximum(4)
self.DiabetesPredegreeFunction.setTickInterval(4)
self.DiabetesPredegreeFunction.valueChanged.connect(self.updateSlider_dibeticsPredegree)
self.DiabetesPredegreeFunction.setGeometry(5, 3, 20, 20)
self.selectedValue_predegree = QLabel(self)
self.selectedValue_predegree.setText(str(0))
label7 = QLabel("Diabetes Predegree Func [0 - 4]", alignment=Qt.AlignmentFlag.AlignCenter)
leftVerticalLayout.addWidget(label7)
leftVerticalLayout.addWidget(self.DiabetesPredegreeFunction)
leftVerticalLayout.addWidget(self.selectedValue_predegree)
# Silder button Age
self.age = QSlider(Qt.Orientation.Horizontal)
self.age.setMinimum(18)
self.age.setMaximum(150)
self.age.valueChanged.connect(self.updateSlider_Age)
self.age.setGeometry(5, 3, 20, 20)
self.selectedValue_age = QLabel(self)
self.selectedValue_age.setText(str(18))
label8 = QLabel("Age [18 - 150]", alignment=Qt.AlignmentFlag.AlignCenter)
leftVerticalLayout.addWidget(label8)
leftVerticalLayout.addWidget(self.age)
leftVerticalLayout.addWidget(self.selectedValue_age)
# Push button Predict
self.predict = QPushButton("Predict")
leftVerticalLayout.addWidget(self.predict)
self.predict.clicked.connect(self.predictiveSystem)
self.predictedValue = QLabel(" Prediction: None", self)
leftVerticalLayout.addWidget(self.predictedValue)
####----------------Main Window Graph ------------
self.setWindowTitle('Women Diabetics Prediction')
x = diabetes["Age"]
y = diabetes["Glucose"]
fig = Figure()
ax =fig.add_subplot(111)
ax.set_title('Glucose Levels Across Age:Predicting Diabetes Risk.')
x_label= ax.set_xlabel('Age')
y_label = ax.set_ylabel('Glucose')
#ax.bar(x,y)
ax.bar(x,y)
graph =FigureCanvas(fig)
###--------Connecting (all the buttons to left vertical layout) & (graph to the right vertical layout)
RightVerticalLayout.addWidget(graph)
MainLayout.addLayout(leftVerticalLayout)
MainLayout.addLayout(RightVerticalLayout)
mainWidget = QWidget()
mainWidget.setLayout(MainLayout)
self.setCentralWidget(mainWidget)
# menu
# action 1 from menu
self.window2 = None
histogram_action = QAction(QIcon("chart-medium.png"), "Histogram", self)
histogram_action.setStatusTip("View Histogram.")
histogram_action.triggered.connect(self.show_hist_window)
# action 2 from menu
self.window3 = None
plot_action = QAction(QIcon("plot.png"), "Plot Graph", self)
plot_action.setStatusTip("Real Time Graph")
plot_action.triggered.connect(self.show_realTime_window)
menu = self.menuBar()
file_menu = menu.addMenu("&Menu")
file_menu.addAction(histogram_action)
file_menu.addAction(plot_action)
def Pregnancies_onStateChanged(self):
if self.pregnancies_checkbox.isChecked():
self.pregnancies_checkbox.setText("Pregnant")
else:
self.pregnancies_checkbox.setText("Not Pregnant")
def updateSlider_pregnancies(self):
val = self.pregnancies.value()
self.selectedValue_preg.setText(str(val))
def updateSlider_Glucose(self):
val = self.Glucose.value()
self.selectedValue_glucose.setText(str(val))
def updateSlider_BloodPressure(self):
val = self.BloodPressure.value()
self.selectedValue_blood.setText(str(val))
def updateSlider_skinThickness(self):
val = self.SkinThickness.value()
self.selectedValue_skin.setText(str(val))
def updateSlider_insulin(self):
val = self.Insulin.value()
self.selectedValue_insulin.setText(str(val))
def updateSlider_BMI(self):
val = self.BMI.value()
self.selectedValue_BMI.setText(str(val))
def updateSlider_dibeticsPredegree(self):
val = self.DiabetesPredegreeFunction.value()
self.selectedValue_predegree.setText(str(val))
def updateSlider_Age(self):
val = self.age.value()
self.selectedValue_age.setText(str(val))
def show_hist_window(self):
if self.window2 is None:
self.window2 = secondWindow()
self.window2.show()
def show_realTime_window(self):
if self.window3 is None:
self.window3 = thirdWindow()
self.window3.show()
def generateData(self):
global diabetes
self.diabetes = pd.read_csv('diabetes_clean_03042021.csv')
print("self.diabetes.head(8):")
print(self.diabetes.head(10))
print("self.diabetes.tail(5): ")
print(self.diabetes.tail(5))
print("self.diabetes.info():")
print(self.diabetes.info())
# number of rows and columns
print("Rows: ", self.diabetes.shape[0])
print("Columns: ", self.diabetes.shape[1])
print("self.diabetes.describe(): ")
print(self.diabetes.describe())
print("Total Diabetic(1) and Non-diabetic(0) patient:", self.diabetes['Outcome'].value_counts())
print("[Mean] grouped by diabetic(1) and Non-diabetic(0) patient: ")
print(self.diabetes.groupby('Outcome').mean())
# ----------- Machine learning ------
print("-----Training data-----")
x = self.diabetes.drop(columns='Outcome', axis=1) # data
y = self.diabetes['Outcome'] # model
# Data Standardization
self.scaler = StandardScaler()
self.scaler.fit(x)
standardized_data = self.scaler.transform(x)
# print(standardized_data)
x = standardized_data # data
y = self.diabetes['Outcome'] # model
# Train Test Split
x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.20, random_state=42)
# test_size = 0.20 means 20% test data and 80% train data
# print(x.shape, x_train.shape, x_test.shape)
# Training The Model with SVM Algorithm
self. svm_classifier = svm.SVC(kernel='linear')
# training the support vector machine classifier
self.svm_classifier.fit(x_train, y_train)
# Accuracy Check
# Train Data
x_train_prediction = self.svm_classifier.predict(x_train)
training_data_accuracy = accuracy_score(x_train_prediction, y_train)
print("Accuracy Score of the training data: ", training_data_accuracy)
# Test data
x_test_prediction = self.svm_classifier.predict(x_test)
test_data_accuracy = accuracy_score(x_test_prediction, y_test)
print("Accuracy Score of the testing data: ", test_data_accuracy)
# correlation ---- highest x=age y=blood pressure
corr_matrix = self.diabetes.corr()
print("self.diabetes.corr(): ", corr_matrix)
if (x_test_prediction[0] == 0):
result = print("The person is not diabetic. ")
else:
result = print("The person is diabetic. ")
# calculating the values for the predictive System
def predictiveSystem(self):
global result
from random import randint
count = randint(0, 767)
# converting checkbox value into 0 or 1
if self.pregnancies_checkbox.isChecked() == True:
pregnancies_checkbox = 1
else:
pregnancies_checkbox = 0
Glucose = self.Glucose.value()
BloodPressure =self.BloodPressure.value()
SkinThickness = self.SkinThickness.value()
Insulin = self.Insulin.value()
bmi = self.BMI.value()
DiabetesPedigreeFunction = self.DiabetesPredegreeFunction.value()
Age = self.age.value()
# inputData = [value,1, 110, 92, 0, 0, 37.6,0.191, 30]
sampleData = [count, pregnancies_checkbox, Glucose, BloodPressure, SkinThickness, Insulin, bmi, DiabetesPedigreeFunction,
Age]
# change the input data to numpy array
sampleData_numpy = np.asarray(sampleData)
# reshaping array as we are predicting for one instance
reshaping = sampleData_numpy.reshape(1, -1)
# standardize the input data
standardize_sampleData = self.scaler.transform(reshaping)
# print(std_data)
prediction = self.svm_classifier.predict(standardize_sampleData)
print(prediction)
if (prediction[0] == 0):
self.predictedValue.setText("Prediction: The person is not diabetic. ")
else:
self.predictedValue.setText("Prediction: The person is diabetic. ")
if __name__ == '__main__':
app = QApplication(sys.argv)
with open("style.css", "r") as file:
app.setStyleSheet(file.read())
window = MainWindow()
#window.setFixedSize(1200,800)
window.design()
window.generateData()
window.show()
sys.exit(app.exec())
plot.png 0 → 100644
plot.png

9.05 KiB

QMainWindow {
background-color: #1e1f22;
border-radius: 5px;
background-image: url('image.jpg'); /* set the path to your image */
background-repeat: no-repeat; /* prevent the image from repeating */
background-position: center; /* position the image in the center */
}
QSlider::handle:horizontal {
background: #13fcec;
width: 10px;
margin: -5px -1px;
border-radius: 5px;
border: 1px solid #2a2a2a;
}
QSlider::groove:horizontal {
background: #ffffff6a;
height:2px;
border: 1px solid #2a2a2a;
}
QPushButton {
background-color: #1ffcd3; /* set the background color */
color: #0f3f33; /* set the text color */
border: 1px solid #0fe6b490; /* add a border */
padding: 5px 10px; /* add padding */
border-radius: 5px;
}
QLabel {
color: #ffffff; /* set the text color for labels */
font-size: 14px; /* set the font size for labels */
font-family: 'Courier New', Monospace; /* set the font family for labels */
font-weight: bold;
}
QCheckBox {
color: #ffffff; /* set the text color for labels */
font-size: 18px; /* set the font size for labels */
font-family: 'Courier New', Monospace; /* set the font family for labels */
font-weight: bold;
}
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment