Mar-31-2020, 07:23 AM
Quote:I am working on a project called heart disease predictor.When i click the button predict heart disease.The below error is coming.But clf is defined global.Help me out asap.
Thank you.
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 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 |
import tkinter #importing tkinter library for GUI creation from tkinter import * from PIL import Image, ImageTk import tkinter.messagebox from tkinter import filedialog #import mysql.connector #from keras.models import Sequential #from keras.layers import Dense import pandas as pnd # importing pandas data analysis toolkit import numpy as np # importing numpy library for array operations from time import time # importing time library for time calculations from sklearn.model_selection import train_test_split # importing module model_classification from scikit-learn library print ( "hello" ) header_row = [ 'age' , 'sex' , 'pain' , 'BP' , 'chol' , 'fbs' , 'ecg' , 'maxhr' , 'eiang' , 'eist' , 'slope' , 'vessels' , 'thal' , 'diagnosis' ] # Declaring the header row for getting data from the dataset files # filter to only those diagnosed with heart disease def cardiac(): global master master = Tk() # Defining the Tkinter widget master.wm_title( "Heart Disease Prediction" ) master.geometry( '1500x600' ) image = Image. open ( 'c3.jpg' ) image = image.resize(( 1500 , 600 )) photo_image = ImageTk.PhotoImage(image) label = Label(master, image = photo_image) label.place(x = 0 ,y = 0 ) import sklearn # Importing scikit-learn functions #Lab=Label(master,text=" Automatic Heart Disease Detection ") # Adding Label to the Tkinter widget #Lab.place(x=600,y=50) # Packing the label data to the tkinter widget in user defined rows and columns # Changing dimensions of the Label #Lab=Label(master,text="") #Lab.grid(row=2,column=5,columnspan=2) #Lab1=Label(master,text="Classification Report") #Lab1.place(x=170,y=330) #Lab2=Label(master,text="Confusion Matrix") #Lab2.place(x=930,y=330) T = Text(master, height = 6 , width = 40 ,font = ( "bold" , 10 ),highlightthickness = 2 ,bg = "white" ,relief = SUNKEN) # Declaring Text Widget for Result Displaying T.place(x = 55 ,y = 350 ) T1 = Text(master, height = 6 , width = 35 ,font = ( "bold" , 10 ),highlightthickness = 2 ,bg = "white" ,relief = SUNKEN) T1.place(x = 1000 ,y = 350 ) var = StringVar(master) var. set ( "Select Dataset" ) # initial value option = OptionMenu(master, var, "Cleveland" , "Hungarian" , "VA" , "all" ) # Declaring the OptionMenu (Drop-Down list) widget option.config(bg = "violet" ) option.config(fg = "black" ) option.config(font = ( 'algerian' , 10 , 'bold' )) option.config(width = 12 ) option.place(x = 500 ,y = 80 ) '''field1="Age" # Defining the field names which user has to input for heart disease detection field2="Sex" field3="Pain" field4="BP" field5="Chol" field6="FBS" field7="ECG" field8="Maxhr" field9="Eiang" field10="Eist" field11="Slope" field12="Vessels" field13="Thal"''' '''L1=Label(master,text=field1) L1.grid(row = 4, column = 0, sticky='nsew') L1.configure(width=14) L2=Label(master,text=field2) L2.grid(row = 4, column = 1, sticky='nsew') L2.configure(width=14) L3=Label(master,text=field3) L3.grid(row = 4, column = 2, sticky='nsew') L3.configure(width=14) L4=Label(master,text=field4) L4.grid(row = 4, column = 3, sticky='nsew') L4.configure(width=14) L5=Label(master,text=field5) L5.grid(row = 4, column = 4, sticky='nsew') L5.configure(width=14) L6=Label(master,text=field6, ) L6.grid(row = 4, column = 5, sticky='nsew') L6.configure(width=14) L7=Label(master,text=field7) L7.grid(row = 4, column = 6, sticky='nsew') L7.configure(width=14) L8=Label(master,text=field8) L8.grid(row = 4, column = 7, sticky='nsew') L8.configure(width=14) L9=Label(master,text=field9) L9.grid(row = 4, column = 8, sticky='nsew') L9.configure(width=14) L10=Label(master,text=field10) L10.grid(row = 4, column = 9, sticky='nsew') L10.configure(width=14) L11=Label(master,text=field11) L11.grid(row = 4, column = 10, sticky='nsew') L11.configure(width=14) L12=Label(master,text=field12) L12.grid(row = 4, column = 11, sticky='nsew') L12.configure(width=14) L13=Label(master,text=field13) L13.grid(row = 4, column = 12, sticky='nsew') L13.configure(width=14)''' E1 = Entry(master,width = 8 ,font = ( "bold" , 10 ),highlightthickness = 2 ,bg = "WHITE" ,relief = SUNKEN) E1.place(x = 0 , y = 220 ) E2 = Entry(master,width = 8 ,font = ( "bold" , 10 ),highlightthickness = 2 ,bg = "WHITE" ,relief = SUNKEN) E2.place(x = 90 , y = 220 ) E3 = Entry(master,width = 8 ,font = ( "bold" , 10 ),highlightthickness = 2 ,bg = "WHITE" ,relief = SUNKEN) E3.place(x = 180 , y = 220 ) E4 = Entry(master,width = 8 ,font = ( "bold" , 10 ),highlightthickness = 2 ,bg = "WHITE" ,relief = SUNKEN) E4.place(x = 280 , y = 220 ) E5 = Entry(master,width = 8 ,font = ( "bold" , 10 ),highlightthickness = 2 ,bg = "WHITE" ,relief = SUNKEN) E5.place(x = 370 , y = 220 ) E6 = Entry(master,width = 8 ,font = ( "bold" , 10 ),highlightthickness = 2 ,bg = "WHITE" ,relief = SUNKEN) E6.place(x = 470 , y = 220 ) E7 = Entry(master,width = 8 ,font = ( "bold" , 10 ),highlightthickness = 2 ,bg = "WHITE" ,relief = SUNKEN) E7.place(x = 550 , y = 220 ) E8 = Entry(master,width = 8 ,font = ( "bold" , 10 ),highlightthickness = 2 ,bg = "WHITE" ,relief = SUNKEN) E8.place(x = 650 , y = 220 ) E9 = Entry(master,width = 10 ,font = ( "bold" , 10 ),highlightthickness = 2 ,bg = "WHITE" ,relief = SUNKEN) E9.place(x = 770 , y = 220 ) E10 = Entry(master,width = 10 ,font = ( "bold" , 10 ),highlightthickness = 2 ,bg = "WHITE" ,relief = SUNKEN) E10.place(x = 880 , y = 220 ) E11 = Entry(master,width = 10 ,font = ( "bold" , 10 ),highlightthickness = 2 ,bg = "WHITE" ,relief = SUNKEN) E11.place(x = 980 , y = 220 ) E12 = Entry(master,width = 10 ,font = ( "bold" , 10 ),highlightthickness = 2 ,bg = "WHITE" ,relief = SUNKEN) E12.place(x = 1100 , y = 220 ) E13 = Entry(master,width = 10 ,font = ( "bold" , 10 ),highlightthickness = 2 ,bg = "WHITE" ,relief = SUNKEN) E13.place(x = 1220 , y = 220 ) lb1 = Label(master, text = "patient" ,font = ( 'algerian' , 15 , 'bold' ),fg = "BLACK" ,anchor = 'w' ) lb1.place(x = 0 , y = 150 ) E0 = Entry(master,width = 10 ,font = ( "bold" , 15 ),highlightthickness = 2 ,bg = "WHITE" ,relief = SUNKEN) E0.place(x = 120 , y = 150 ) '''Labx=Label(master,text="") Labx.grid(row=21,column=4,columnspan=4) Labx.visible=False''' #T3 = Text(master, height=2, width=30) # Declaring Text Widget for Displaying Prediction #T3.grid(row=23,column=4, columnspan=4, sticky= 'nsew') def train_classifier(x_train,x_test,y_train,y_test,string): # Declaring the function for training classifiers and classification analysis global clf # Declaring clf as a Global Variable for using throughot the code global outclass global a1,a2,a3 from sklearn.metrics import classification_report from sklearn.metrics import confusion_matrix T.delete( 1.0 ,END) # Deleting the text in the Text Widget T1.delete( 1.0 ,END) if string = = "CNN" : from keras.models import Sequential from keras.layers import Dense import matplotlib.pyplot as plt1 #import pandas as pnd # importing pandas data analysis toolkit #import numpy as np t1 = time() clf = Sequential() #initial creation clf.add(Dense( 13 , input_dim = 13 , init = 'uniform' , activation = 'relu' )) #first hidden layer clf.add(Dense( 10 , init = 'uniform' , activation = 'relu' )) #model.add(Dense(8, init='uniform', activation='relu')) #model.add(Dense(6, init='uniform', activation='relu')) clf.add(Dense( 1 , init = 'uniform' , activation = 'sigmoid' )) #output layer # compile the model clf. compile (loss = 'binary_crossentropy' , optimizer = 'adam' , metrics = [ 'accuracy' ]) # fitting data to model clf.fit(x_train, y_train, validation_data = (x_test, y_test), epochs = 200 , batch_size = 5 , verbose = 0 ) # evaluate the model scores = clf.evaluate(x_test, y_test) #printing accuracy print ( "Accuracy: %.2f%%" % (scores[ 1 ] * 100 )) #p1=model.predict(Xv) #print(p1) a1 = (scores[ 1 ] * 100 ) T.insert(END, "Accuracy" ) T.insert(END, " " ) T.insert(END,(scores[ 1 ] * 100 ) ) y_pred = clf.predict(x_test) print (y_pred) l1 = list () for i in y_pred: if i<. 49 : l1.append( 0 ) else : l1.append( 1 ) print (l1) count1 = y_test.count() l2 = list ( range ( 1 ,count1 + 1 , 1 )) print (count1) print (y_test.count()) #print(count(l1)) colormap = np.array([ 'lime' , 'red' ]) plt1.subplot( 1 , 2 , 1 ) plt1.scatter(l2,y_test,c = colormap[y_test]) plt1.suptitle( "CNN Algorihm" ) plt1.xlabel( "X values" ) plt1.ylabel( "y tests values" ) plt1.title( "true Values" ) plt1.subplot( 1 , 2 , 2 ) plt1.scatter(l2,l1,c = colormap[l1]) plt1.suptitle( "CNN Algorihm" ) plt1.xlabel( "X values" ) plt1.ylabel( "Predictions" ) plt1.title( "Predictions" ) plt1.show() # Predict Results for Test Data #title = "Learning Curves (SVM)" #print(y_train) #geterror(x_train,y_train,clf,title); t = time() - t1 T.insert(END, "Accuracy" ) T.insert(END, " " ) T.insert(END,(scores[ 1 ] * 100 ) ) print ( "Training Complete" ) elif string = = "Naive Bayes" : from sklearn.naive_bayes import GaussianNB import matplotlib.pyplot as plt2 t2 = time() clf = GaussianNB() # Initializing the Naive Bayes Classifier clf.partial_fit(x_train, y_train, np.unique(y_train)) # Fitting the classifier to the training and testing the Naive Bayes Classifier y_pred = clf.predict(x_test) print (y_pred) t = time() - t2 title = "Learning Curves (Naive Bayes)" #geterror(x_train,y_train,clf,title); classre = classification_report(y_test,y_pred) # Generating Classification Report T.insert(END,classre[ 1 : 5 ] + classre[ 1 : 32 ] + classre[ 1 : 13 ] + classre[ 60 : 90 ] + classre[ 1 : 11 ] + classre[ 1 : 2 ] + classre[ 115 : 140 ] + classre[ 1 : 7 ] + classre[ 161 : 195 ]) # Printing Precision and Recall Results print (classre) confmat = confusion_matrix(y_test,y_pred) # Calculating the Confusion Matrix for the classification T1.insert(END, confmat) T.insert(END, classre[ 1 : 9 ]) T.insert(END, "Accuracy" ) T.insert(END, classre[ 1 : 5 ]) T.insert(END, int ( float ((y_test = = y_pred). sum ()) / len (y_test.T) * 100 )) T.insert(END, "%" ) T.insert(END, classre[ 1 : 10 ] + classre[ 1 : 10 ]) T.insert(END, "Class. Time" ) T.insert(END, classre[ 1 : 8 ]) #T.insert(END, t[0:4]+" sec") a2 = int ( float ((y_test = = y_pred). sum ()) / len (y_test.T) * 100 ) count2 = y_test.count() l3 = list ( range ( 1 ,count2 + 1 , 1 )) print (count2) print (y_test.count()) #print(count(l1)) colormap = np.array([ 'lime' , 'red' ]) plt2.subplot( 1 , 2 , 1 ) plt2.scatter(l3,y_test,c = colormap[y_test]) plt2.suptitle( "Naviee Bayesian Algorihm" ) plt2.xlabel( "X values" ) plt2.ylabel( "y tests values" ) plt2.title( "true Values" ) plt2.subplot( 1 , 2 , 2 ) plt2.scatter(l3,y_pred,c = colormap[y_pred]) plt2.suptitle( "Naviee Bayesian Algorihm" ) plt2.xlabel( "X values" ) plt2.ylabel( "Predictions" ) plt2.title( "Predictions" ) plt2.show() print ( "Training Complete" ) elif string = = "K-Nearesr Neighbour" : from sklearn.neighbors import KNeighborsClassifier import matplotlib.pyplot as plt3 clf = KNeighborsClassifier(n_neighbors = 5 ) clf.fit(x_train, y_train) y_pred = clf.predict(x_test) print (y_pred) print (y_test) classre = classification_report(y_test,y_pred) # Generating Classification Report T.insert(END,classre[ 1 : 5 ] + classre[ 1 : 32 ] + classre[ 1 : 13 ] + classre[ 60 : 90 ] + classre[ 1 : 11 ] + classre[ 1 : 2 ] + classre[ 115 : 140 ] + classre[ 1 : 7 ] + classre[ 161 : 195 ]) # Printing Precision and Recall Results print (classre) confmat = confusion_matrix(y_test,y_pred) # Calculating the Confusion Matrix for the classification T1.insert(END, confmat) T.insert(END, classre[ 1 : 9 ]) T.insert(END, "Accuracy" ) T.insert(END, classre[ 1 : 5 ]) T.insert(END, int ( float ((y_test = = y_pred). sum ()) / len (y_test.T) * 100 )) T.insert(END, "%" ) T.insert(END, classre[ 1 : 10 ] + classre[ 1 : 10 ]) #T.insert(END, "Class. Time") #T.insert(END, classre[1:8]) #T.insert(END, t[0:4]+" sec") a3 = int ( float ((y_test = = y_pred). sum ()) / len (y_test.T) * 100 ) count3 = y_test.count() l4 = list ( range ( 1 ,count3 + 1 , 1 )) print (count3) print (a1) print (a2) print (a3) #plot_bar_x(a1,a2,a3); print (y_test.count()) #print(count(l1)) colormap = np.array([ 'lime' , 'red' ]) plt3.subplot( 1 , 2 , 1 ) plt3.scatter(l4,y_test,c = colormap[y_test]) plt3.suptitle( "K Nearest Neighbour Algorihm" ) plt3.xlabel( "X values" ) plt3.ylabel( "Y tests values" ) plt3.title( "True Values" ) plt3.subplot( 1 , 2 , 2 ) plt3.scatter(l4,y_pred,c = colormap[y_pred]) plt3.suptitle( "K Nearest Neighbour Algorihm" ) plt3.xlabel( "X values" ) plt3.ylabel( "Predictions" ) plt3.title( "Predictions" ) plt3.show() #print(a1) #print(a2) #print(a3) plot_bar_x(a1,a2,a3) print ( "Training Complete" ) '''elif string=="Logistic Regression": from sklearn.linear_model import LogisticRegression t3=time() clf=LogisticRegression(penalty='l2', dual=False, tol=0.0001, C=1.0, fit_intercept=True, intercept_scaling=1, solver='liblinear', max_iter=100, verbose=0, warm_start=False, n_jobs=1) # Initializing the Logistic Regression Classifier clf.fit(x_train,y_train) y_pred = clf.predict(x_test) print(y_pred) t = time() - t3 title = "Learning Curves (Logistic Regression)" # geterror(x_train,y_train,clf,title); print("Training Complete") t=str(t)''' '''print(y_test) classre=classification_report(y_test,y_pred) # Generating Classification Report T.insert(END,classre[1:5]+classre[1:32]+classre[1:13]+classre[60:90]+classre[1:11]+classre[1:2]+classre[115:140]+classre[1:7]+classre[161:195]) # Printing Precision and Recall Results print(classre) confmat=confusion_matrix(y_test,y_pred) # Calculating the Confusion Matrix for the classification T1.insert(END, confmat) T.insert(END, classre[1:9]) T.insert(END, "Accuracy") T.insert(END, classre[1:5]) T.insert(END, int(float((y_test==y_pred).sum())/len(y_test.T)*100)) T.insert(END, "%") T.insert(END, classre[1:10]+classre[1:10]) T.insert(END, "Class. Time") T.insert(END, classre[1:8]) T.insert(END, t[0:4]+" sec") import matplotlib.pyplot as plt''' def plot_bar_x(a1,a2,a3): import matplotlib.pyplot as pltu import numpy as np print (a1) print (a2) print (a3) label = [ 'CNN' , 'NAIVE BAYESIAN' , 'KNN' ] no_movies = [a1,a2,a3] # this is for plotting purpose index = np.arange( len (label)) pltu.bar(index, no_movies) pltu.xlabel( 'Algorithms' , fontsize = 15 ) pltu.ylabel( 'Accuracies' , fontsize = 15 ) pltu.xticks(index, label, fontsize = 15 , rotation = 30 ) pltu.title( 'Comparison of different algorithms used' ) pltu.show() def process_dataset(string): if string = = "Cleveland" : heart = pnd.read_csv( 'processed.cleveland.data' , names = header_row) # Reading the dataset file in .data format using Pandas library function read_csv() print ( "Unprocessed Cleveland Dataset" ) print ( "************************************************************************" ) print (heart.loc[:, 'age' : 'diagnosis' ]) print ( "************************************************************************" ) import numpy as np has_hd_check = heart[ 'diagnosis' ] > 0 # Getting the indices of individuals having heart disease has_hd_patients = heart[has_hd_check] heart[ 'vessels' ] = heart[ 'vessels' ]. apply ( lambda vessels: 0.0 if vessels = = "?" else vessels) # Replacing the unknown values in the dataset with float heart[ 'vessels' ] = heart[ 'vessels' ].astype( float ) heart[ 'thal' ] = heart[ 'thal' ]. apply ( lambda thal: 0.0 if thal = = "?" else thal) heart[ 'thal' ] = heart[ 'thal' ].astype( float ) heart[ 'diag_int' ] = has_hd_check.astype( int ) ind1 = np.where((heart[ 'diagnosis' ] = = 1 )|(heart[ 'diagnosis' ] = = 2 )); ind2 = np.where((heart[ 'diagnosis' ] = = 3 )|(heart[ 'diagnosis' ] = = 4 )); temp = heart[ 'diagnosis' ]; temp.ix[ ind1 ] = 1 ; temp.ix[ ind2 ] = 2 ; heart[ 'diagnosis' ] = temp; global x_train global y_train global x_test global y_test x_train, x_test, y_train, y_test = train_test_split(heart.loc[:, 'age' : 'thal' ], heart.loc[:, 'diagnosis' ], # Splitting the processed data into training data and testing data test_size = 0.20 , random_state = 42 ) # test_size = percent of data used for testing, # random_state = for initializing the random number generator print ( "Processed Cleveland Dataset" ) print ( "************************************************************************" ) print (heart.loc[:, 'age' : 'diagnosis' ]) print ( "************************************************************************" ) elif string = = "VA" : import numpy as np heart_va = pnd.read_csv( 'processed.va.data' , names = header_row) print ( "Unprocessed VA Dataset" ) print ( "************************************************************************" ) print (heart_va.loc[:, 'age' : 'diagnosis' ]) print ( "************************************************************************" ) has_hd_check = heart_va[ 'diagnosis' ] > 0 heart_va[ 'diag_int' ] = has_hd_check.astype( int ) heart_va = heart_va.replace(to_replace = '?' , value = 0.0 ) heart_va[ 'diag_int' ] = has_hd_check.astype( int ) ind1 = np.where((heart_va[ 'diagnosis' ] = = 1 )|(heart_va[ 'diagnosis' ] = = 2 )); ind2 = np.where((heart_va[ 'diagnosis' ] = = 3 )|(heart_va[ 'diagnosis' ] = = 4 )); temp = heart_va[ 'diagnosis' ]; temp.ix[ ind1 ] = 1 ; temp.ix[ ind2 ] = 2 ; heart_va[ 'diagnosis' ] = temp; print ( "Processed VA Dataset" ) print ( "************************************************************************" ) print (heart_va.loc[:, 'age' : 'diagnosis' ]) print ( "************************************************************************" ) x_train, x_test, y_train, y_test = train_test_split(heart_va.loc[:, 'age' : 'thal' ], heart_va.loc[:, 'diagnosis' ], test_size = 0.30 , random_state = 42 ) elif string = = "Hungarian" : import numpy as np heart_hu = pnd.read_csv( 'processed.hungarian.data' , names = header_row) print ( "Unprocessed Hungarian Dataset" ) print ( "************************************************************************" ) print (heart_hu.loc[:, 'age' : 'diagnosis' ]) print ( "************************************************************************" ) has_hd_check = heart_hu[ 'diagnosis' ] > 0 heart_hu[ 'diag_int' ] = has_hd_check.astype( int ) heart_hu = heart_hu.replace(to_replace = '?' , value = 0.0 ) ind1 = np.where((heart_hu[ 'diagnosis' ] = = 1 )|(heart_hu[ 'diagnosis' ] = = 2 )); ind2 = np.where((heart_hu[ 'diagnosis' ] = = 3 )|(heart_hu[ 'diagnosis' ] = = 4 )); temp = heart_hu[ 'diagnosis' ]; temp.ix[ ind1 ] = 1 ; temp.ix[ ind2 ] = 2 ; heart_hu[ 'diagnosis' ] = temp; print ( "Processed Hungarian Dataset" ) print ( "************************************************************************" ) print (heart_hu.loc[:, 'age' : 'diagnosis' ]) print ( "************************************************************************" ) heart_hu[ 'diag_int' ] = has_hd_check.astype( int ) x_train, x_test, y_train, y_test = train_test_split(heart_hu.loc[:, 'age' : 'thal' ], heart_hu.loc[:, 'diagnosis' ], test_size = 0.30 , random_state = 42 ) elif string = = "all" : import numpy as np heart_cl = pnd.read_csv( 'processed.cleveland.data' , names = header_row) print ( "Unprocessed Cleveland Dataset" ) print ( "************************************************************************" ) print (heart_cl.loc[:, 'age' : 'diagnosis' ]) print ( "************************************************************************" ) has_hd_check = heart_cl[ 'diagnosis' ] > 0 has_hd_patients = heart_cl[has_hd_check] heart_cl[ 'diag_int' ] = has_hd_check.astype( int ) heart_cl[ 'vessels' ] = heart_cl[ 'vessels' ]. apply ( lambda vessels: 0.0 if vessels = = "?" else vessels) heart_cl[ 'vessels' ] = heart_cl[ 'vessels' ].astype( float ) heart_cl[ 'thal' ] = heart_cl[ 'thal' ]. apply ( lambda thal: 0.0 if thal = = "?" else thal) heart_cl[ 'thal' ] = heart_cl[ 'thal' ].astype( float ) ind1 = np.where((heart_cl[ 'diagnosis' ] = = 1 )|(heart_cl[ 'diagnosis' ] = = 2 )); ind2 = np.where((heart_cl[ 'diagnosis' ] = = 3 )|(heart_cl[ 'diagnosis' ] = = 4 )); temp = heart_cl[ 'diagnosis' ]; temp.ix[ ind1 ] = 1 ; temp.ix[ ind2 ] = 2 ; heart_cl[ 'diagnosis' ] = temp; heart_va = pnd.read_csv( 'processed.va.data' , names = header_row) print ( "Unprocessed VA Dataset" ) print ( "************************************************************************" ) print (heart_va.loc[:, 'age' : 'diagnosis' ]) print ( "************************************************************************" ) has_hd_check = heart_va[ 'diagnosis' ] > 0 heart_va[ 'diag_int' ] = has_hd_check.astype( int ) heart_va = heart_va.replace(to_replace = '?' , value = 0.0 ) ind1 = np.where((heart_va[ 'diagnosis' ] = = 1 )|(heart_va[ 'diagnosis' ] = = 2 )); ind2 = np.where((heart_va[ 'diagnosis' ] = = 3 )|(heart_va[ 'diagnosis' ] = = 4 )); temp = heart_va[ 'diagnosis' ]; temp.ix[ ind1 ] = 1 ; temp.ix[ ind2 ] = 2 ; heart_va[ 'diagnosis' ] = temp; print ( "Processed VA Dataset" ) print ( "************************************************************************" ) print (heart_va.loc[:, 'age' : 'diagnosis' ]) print ( "************************************************************************" ) heart_hu = pnd.read_csv( 'processed.hungarian.data' , names = header_row) print ( "Unprocessed Hungarian Dataset" ) print ( "************************************************************************" ) print (heart_hu.loc[:, 'age' : 'diagnosis' ]) print ( "************************************************************************" ) has_hd_check = heart_hu[ 'diagnosis' ] > 0 heart_hu[ 'diag_int' ] = has_hd_check.astype( int ) heart_hu = heart_hu.replace(to_replace = '?' , value = 0.0 ) ind1 = np.where((heart_hu[ 'diagnosis' ] = = 1 )|(heart_hu[ 'diagnosis' ] = = 2 )); ind2 = np.where((heart_hu[ 'diagnosis' ] = = 3 )|(heart_hu[ 'diagnosis' ] = = 4 )); temp = heart_hu[ 'diagnosis' ]; temp.ix[ ind1 ] = 1 ; temp.ix[ ind2 ] = 2 ; heart_hu[ 'diagnosis' ] = temp; print ( "Processed Hungarian Dataset" ) print ( "************************************************************************" ) print (heart_hu.loc[:, 'age' : 'diagnosis' ]) print ( "************************************************************************" ) x_train1, x_test1, y_train1, y_test1 = train_test_split(heart_cl.loc[:, 'age' : 'thal' ], heart_cl.loc[:, 'diagnosis' ], test_size = 0.30 , random_state = 42 ) x_train2, x_test2, y_train2, y_test2 = train_test_split(heart_va.loc[:, 'age' : 'thal' ], heart_va.loc[:, 'diagnosis' ], test_size = 0.30 , random_state = 42 ) x_train3, x_test3, y_train3, y_test3 = train_test_split(heart_hu.loc[:, 'age' : 'thal' ], heart_hu.loc[:, 'diagnosis' ], test_size = 0.30 , random_state = 42 ) # Combining the dataset for Cleveland, VA and Hungarian Dataset x_train4 = x_train1.append(x_train2); x_train = x_train4.append(x_train3); y_train4 = y_train1.append(y_train2); y_train = y_train4.append(y_train3); x_test4 = x_test1.append(x_test2); x_test = x_test4.append(x_test3) y_test4 = y_test1.append(y_test2); y_test = y_test4.append(y_test3); button = Button(master, text = "Process Dataset" ,height = 1 ,fg = "black" ,font = ( 'algerian' , 13 , 'bold' ),bg = "violet" ,justify = 'center' , command = lambda : process_dataset(var.get())) #Defining the button in the Tkinter Widget button.place(x = 700 ,y = 80 ) var1 = StringVar(master) var1. set ( "Select Classifier" ) # initial value option1 = OptionMenu(master, var1, "CNN" , "Naive Bayes" , "K-Nearesr Neighbour" ) option1.place(x = 500 ,y = 120 ) option1.config(bg = "violet" ) option1.config(fg = "black" ) option1.config(font = ( 'algerian' , 10 , 'bold' )) option1.config(width = 12 ) #option.place ( relx=0.5, rely=0.1) button1 = Button(master, text = " Train Classifier" ,height = 1 ,fg = "black" ,font = ( 'algerian' , 13 , 'bold' ),bg = "violet" ,justify = 'center' , command = lambda : train_classifier(x_train,x_test,y_train,y_test,var1.get())) button1.place(x = 700 ,y = 120 ) #e1.bind('<Button-1>',e1.delete(0,END)) def predres(clf): # Defining function to predict the result from the user input data E14 = E10.get() # Converting the Eist data according to sign and decimal point if len (E14) = = 3 or len (E14) = = 4 : E15 = float (E14) else : E16 = E14 + '.0' E15 = float (E16) test = [ float (E1.get() + '.0' ), float (E2.get() + '.0' ), float (E3.get() + '.0' ), float (E4.get() + '.0' ), float (E5.get() + '.0' ), float (E6.get() + '.0' ), float (E7.get() + '.0' ), float (E8.get() + '.0' ), float (E9.get() + '.0' ),E15, float (E11.get()), float (E12.get() + '.0' ), float (E13.get() + '.0' )] test = np.reshape(test,( 1 , - 1 )) #print(test) print (clf) print (clf.predict(test)) if clf.predict(test) < 0.49 : res = "The Person does not have heart Disease" Labx1 = Label(master,text = "The Person does not have heart Disease" , bg = 'green' ) Labx1.visible = False Labx1.place(x = 600 ,y = 430 ) Labx1.visible = True #T3.insert(END,"The Person has Heart Disease") elif clf.predict(test) = = 2 : res = "The Person has Severe heart Disease" Labx1 = Label(master,text = "The Person has Severe heart Disease" , bg = 'red' ) Labx1.visible = False Labx1.place(x = 600 ,y = 430 ) Labx1.visible = True else : res = "The Person has heart Disease" Labx1 = Label(master,text = "The Person has heart Disease " , bg = 'red' ) Labx1.visible = False Labx1.place(x = 600 ,y = 430 ) Labx1.visible = True #T3.insert(END,"The Person does not have Heart Disease") age = E1.get() sex = E2.get() pai = E3.get() bp = E4.get() chol = E5.get() fbs = E6.get() ecg = E7.get() maxhr = E8.get() eiang = E9.get() eist = E10.get() slope = E11.get() vessels = E12.get() thal = E13.get() pana = E0.get() aa = mysql.connector.connect(host = 'localhost' , port = 3306 , user = "root" , passwd = "root" , db = "cardiac" ) mm = aa.cursor() mm.execute( """INSERT INTO cardiac1 VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)""" , (age,sex,pai,bp,chol,fbs,ecg,maxhr,eiang,eist,slope,vessels,thal,pana,res)) aa.commit() #con.close() def geterror(x_train,y_train,clf,title): #global clf #global outclass import matplotlib.pyplot as plt from sklearn.model_selection import learning_curve from sklearn.model_selection import ShuffleSplit clas = []; def plot_learning_curve(estimator, title, X, y, ylim = None , cv = None , n_jobs = 1 , train_sizes = np.linspace(. 1 , 1.0 , 5 )): plt.figure() plt.title(title) if ylim is not None : plt.ylim( * ylim) plt.xlabel( "Training examples" ) plt.ylabel( "Score" ) train_sizes, train_scores, test_scores = learning_curve( estimator, X, y, cv = cv, n_jobs = n_jobs, train_sizes = train_sizes) train_scores_mean = np.mean(train_scores, axis = 1 ) train_scores_std = np.std(train_scores, axis = 1 ) test_scores_mean = np.mean(test_scores, axis = 1 ) test_scores_std = np.std(test_scores, axis = 1 ) plt.grid() plt.fill_between(train_sizes, train_scores_mean - train_scores_std, train_scores_mean + train_scores_std, alpha = 0.1 , color = "r" ) plt.fill_between(train_sizes, test_scores_mean - test_scores_std, test_scores_mean + test_scores_std, alpha = 0.1 , color = "g" ) plt.plot(train_sizes, train_scores_mean, 'o-' , color = "r" , label = "Training score" ) plt.plot(train_sizes, test_scores_mean, 'o-' , color = "g" , label = "Cross-validation score" ) plt.legend(loc = "best" ) plt.axis([ 0 , len (y), 0 , 1.1 ]) return plt for index in range ( len (y_train)): #x_train1=np.reshape(x_train.iloc[index:],(1,-1)); x_train1 = x_train.iloc[index].values.reshape( 1 , - 1 ); outclass = clf.predict(x_train1); clas.append(outclass[ 0 ]); ind3 = np.where((clas = = y_train)); ind4 = np.where((clas ! = y_train)); l = 0 m = 0 cv = ShuffleSplit(n_splits = 4 , test_size = 0.2 , random_state = 0 ) plot_learning_curve(clf, title, x_train, y_train, ( 0.7 , 1.01 ), cv = cv, n_jobs = 1 ) plt.show() button2 = Button(master, text = " Predict Heart Disease " ,width = 20 ,height = 1 ,fg = "black" ,font = ( 'algerian' , 13 , 'bold' ),bg = "violet" ,justify = 'center' ,command = lambda :predres(clf)) button2.place(x = 600 ,y = 300 ) btn6 = Button(master,text = "LOGOUT" ,width = 8 ,height = 1 ,fg = "black" ,font = ( 'algerian' , 15 , 'bold' ),bg = "SKYBLUE" ,justify = 'center' ,command = cardes) btn6.place(x = 1100 ,y = 80 ) #button2.configure(width=14) #button1.place(relx=0.1,rely=0.2) master.mainloop() def adminlogin(): def adminlogininto(): usernames = e1.get() passwords = e2.get() if e1.get() = = " " or e2.get() == " ": tkinter.messagebox.showinfo( "sorry" , "Please complete the required field" ) elif e1.get() = = "admin" and e2.get() = = "admin" : #tkMessageBox.showinfo("yeh","logged in") admindes() else : tkinter.messagebox.showinfo( "Sorry" , "Wrong Password" ) global window1 window1 = Tk() window1.title( "LOGIN PAGE" ) window1.geometry( '700x500' ) image = Image. open ( 'photo.png' ) image = image.resize(( 700 , 600 )) photo_image = ImageTk.PhotoImage(image) label = Label(window1, image = photo_image) label.place(x = 0 ,y = 0 ) '''lb1=Label(window1,text="USERNAME",font=('algerian',25,'bold'),fg="BLACK",anchor='w') lb1.place(x=150,y=400)''' e1 = Entry(window1,width = 10 ,font = ( "bold" , 17 ),highlightthickness = 2 ,bg = "WHITE" ,relief = SUNKEN) e1.place(x = 250 ,y = 150 ) '''lb2=Label(window1,text="PASSWORD",font=('algerian',25,'bold'),fg="BLACK",anchor='w') lb2.place(x=150,y=450)''' e2 = Entry(window1,width = 10 ,show = "*" ,font = ( "bold" , 17 ),highlightthickness = 2 ,bg = "WHITE" ,relief = SUNKEN) e2.place(x = 250 ,y = 200 ) btn6 = Button(window1,text = "LOGIN" ,width = 8 ,height = 1 ,fg = "black" ,font = ( 'algerian' , 15 , 'bold' ),bg = "SKYBLUE" ,justify = 'center' ,command = adminlogininto) btn6.place(x = 270 ,y = 300 ) window1.mainloop() def admindes(): window1.destroy() cardiac() def cardes(): master.destroy() adminlogin() if __name__ = = "__main__" : adminlogin() |
Error:Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Users\Dell\AppData\Local\Programs\Python\Python37\lib\tkinter\__init__.py", line 1705, in __call__
return self.func(*args)
File "C:\Users\Dell\Desktop\finalproject\heartfinal.py", line 755, in <lambda>
button2 = Button(master, text=" Predict Heart Disease ",width=20,height=1,fg="black",font=('algerian',13,'bold'),bg="violet",justify='center',command=lambda:predres(clf))
NameError: name 'clf' is not defined