Skip to content
Snippets Groups Projects
main_diabetics.py 15.8 KiB
Newer Older
Syed Haque's avatar
Syed Haque committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451
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())