-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathScikitLearn_Assignments.py
7004 lines (6482 loc) · 248 KB
/
ScikitLearn_Assignments.py
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
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
'''Hi there! My name is Reza Javadzadeh. Here is the whole codes of Machine Learning with Scikit-Learn module course
which is taught in https://www.koolac.org. You can purchase this course from https://koolac.org/product/machine-learning/
For more information like how to use this code or more projects, check out my Github account.
-- -- Github: https://github.com/Reza-Javadzadeh
-- -- LinkedIn: https://linkedin.com/in/reza-javadzadeh'''
'''P01-01-Terminology + Reading Data'''
## 03
# import numpy as np
# import matplotlib.pyplot as plt
# import pandas as pd
#
# #######################
# ## Reading File
# #######################
# ## Read and displaying:
# df=pd.read_csv(r'D:\Koolac\06- Machine Learning\P00-01-Datasets\01-Ad.csv')
# print(df.info())
# print(df.head())
#
# ## Defining x and y (input and output):
# x=df.iloc[:,3:-1].values # we use numeric feature yet, so we didn't add Gender and Type columns. For make it more simple in the process, we add ".values" method to turn it as numpy array.
# y=df.iloc[:,-1].values # 'Purchase' column as target value or label. For make it more simple in the process, we add ".values" method to turn it as numpy array.
#
# print('x:\n',x,end='\n\n')
# print('y:\n',y,end='\n\n')
#
'''P01-02-Scaling'''
# ##01
#
# ###############################################
# ## preprocessing
# ###############################################
#
# ## scaling:
# ##02 MinMaxScaler
#
# from sklearn.preprocessing import MinMaxScaler
#
# scaler=MinMaxScaler() # we bulit an object for doing MinMax scaling by MinMaxScaler class. the feature_scaling default value is in range [0,1], we can change it as our desire.
# xx=scaler.fit_transform(x)
# yy=scaler.fit_transform(y.reshape(-1,1)) # it should be 2D array , 1D array return error. so we must reshape it like: array.reshape(-1,1)
# print('x after preprocessing (i.e. MinMax scaling):\n',xx,end='\n\n')
# print('y after preprocessing (i.e. MinMax scaling):\n',yy,end='\n\n')
#
# # scaler=MinMaxScaler(feature_range=(2,5)) # we bulit an object for doing MinMax scaling by MinMaxScaler class. the feature_scaling has been changed to [2,5] interval. note that it should be in tuple form.
# # xx=scaler.fit_transform(x)
# # yy=scaler.fit_transform(y.reshape(-1,1)) # it should be 2D array , 1D array return error. so we must reshape it like: array.reshape(-1,1)
# # print('x after preprocessing (i.e. MinMax scaling):\n',xx,end='\n\n')
# # print('y after preprocessing (i.e. MinMax scaling):\n',yy,end='\n\n')
#
# ## 05 StandardScaler
#
# from sklearn.preprocessing import StandardScaler
#
# scaler=StandardScaler() # we bulit an object for doing Standard scaling by MinMaxScaler class.
# xx=scaler.fit_transform(x)
# yy=scaler.fit_transform(y.reshape(-1,1)) # it should be 2D array , 1D array return error. so we must reshape it like: array.reshape(-1,1)
# print('x after preprocessing (i.e. Standard scaling):\n',xx,end='\n\n')
# print('y after preprocessing (i.e. Standard scaling):\n',yy,end='\n\n')
#
#
# ## 07 ZScore
#
# ## if we tend to compute StandardScaling for whole society (i.e.: the complete sample space and ddof=0) , we utilize "sklearn.preprocessing.StandardScaling".
# ## else , (i.e.: apply it for some sample and ddof=1), we should utilize "scipy.stats.zscore". sklearn doesn't support ddof > 0 .
#
# from scipy.stats import zscore
#
# xx=zscore(x,ddof=1) # the default ddof is equaled to 0. so we should change it to ddof=1
# yy=zscore(y.reshape(-1,1),ddof=1)
# print('x after preprocessing (i.e. zscore):\n',xx,end='\n\n')
# print('y after preprocessing (i.e. zscore):\n',yy,end='\n\n')
# ##8 Scaling or Dataset
#
# # so as epilogue of this lesson, let's do what we have untill now all over again:
#
# import numpy as np
# import matplotlib.pyplot as plt
# import pandas as pd
#
# #######################
# ## Reading File
# #######################
#
# df=pd.read_csv(r'D:\Koolac\06- Machine Learning\P00-01-Datasets\01-Ad.csv')
# ## Read and displaying:
# print(df.info())
# print(df.head())
#
# ## Defining x and y (input and output):
# x=df.iloc[:,3:-1].values # we use numeric feature yet, so we didn't add Gender and Type columns. For make it more simple in the process, we add ".values" method to turn it as numpy array.
# y=df.iloc[:,-1].values # 'Purchase' column as target value or label. For make it more simple in the process, we add ".values" method to turn it as numpy array.
#
# print('x:\n',x,end='\n\n')
# print('y:\n',y,end='\n\n')
#
# # ###############################################
# # ## preprocessing
# # ###############################################
# #
# # ## scaling:
#
# from sklearn.preprocessing import MinMaxScaler,StandardScaler
# from scipy.stats import zscore
#
# scalerMINMAX=MinMaxScaler() #feature_range set to (0,1) as default
# scalerSTANDARD=StandardScaler()
#
# xx=scalerMINMAX.fit_transform(x)
# yy=scalerMINMAX.fit_transform(y.reshape(-1,1))
#
# print('x after preprocessing (i.e. MinMax scaling):\n',xx,end='\n\n')
# print('y after preprocessing (i.e. MinMax scaling):\n',yy,end='\n\n')
#
# xx=scalerSTANDARD.fit_transform(x)
# yy=scalerSTANDARD.fit_transform(y.reshape(-1,1))
#
# print('x after preprocessing (i.e. Standard scaling):\n',xx,end='\n\n')
# print('y after preprocessing (i.e. Standard scaling):\n',yy,end='\n\n')
#
# xx=zscore(x,ddof=1)
# yy=zscore(y.reshape(-1,1),ddof=1)
#
# print('x after preprocessing (i.e. zscore and ddof==1):\n',xx,end='\n\n')
# print('y after preprocessing (i.e. zscore and ddof==1):\n',yy,end='\n\n')
'''P02-01-KNN:'''
# ## 01 we are going to use K Nearest Neighbors model for learing in this section:
#
# import numpy as np
# import matplotlib.pyplot as plt
# import pandas as pd
# from sklearn.preprocessing import StandardScaler # we wanna scale our model as Standard one.
# from sklearn.neighbors import KNeighborsClassifier # our model is KNN in this chapter.
#
#
# ##################
# ## Reading Data:
# ##################
#
# df=pd.read_csv(r'D:\Koolac\06- Machine Learning\P00-01-Datasets\01-Ad.csv')
# print(df.info(),end='\n\n')
# print('DF Head:\n\n',df.head(),end='\n\n')
#
# ## Defining x and y as input and output:
#
# x=df.iloc[:,3:-1].values
# y=df.iloc[:,-1].values.reshape(-1,1)
#
# ##################
# ## Preprocessing:
# ##################
#
# ## Scaling with Standard shape:
# scaler=StandardScaler()
# x=scaler.fit_transform(x)
# # y=scaler.fit_transform(y) ## Seems the output shouldn't get normalize, otherwise return error! [ValueError: It shouldn't be 'countinious'.]
#
# ##################
# ## Building the model:
# ##################
#
# model=KNeighborsClassifier(n_neighbors=4)
# model.fit(x,y) ## Python Intepreter also return a Warning. [DataConversionWarning: A column-vector y was passed when a 1d array was expected. Please change the shape of y to (n_samples,), for example using ravel().]
'''P02-02-Prediction and Evaluation-Part 01'''
# ## 02 train test split-Python
#
# import numpy as np
# import pandas as pd
# import matplotlib.pyplot as plt
#
# #############
# ## reading data:
# #############
# df=pd.read_csv(r'D:\Koolac\06- Machine Learning\P00-01-Datasets\01-Ad.csv')
# print(df.info(),end='\n\n')
# print('DF Head: \n',df.head(),end='\n\n')
#
# x=df.iloc[:,3:-1].values #input
# y=df.iloc[:,-1].values #output
#
#
# ###############################
# ## preprocessing:
# ###############################
#
# ## train test split (from model selection):
# from sklearn.model_selection import train_test_split
# x_train,x_test,y_train,y_test=train_test_split(x,y,test_size=0.25) ## Note that we didn't stratify our data during splitting data to train and test.
#
# ## scaling:
# from sklearn.preprocessing import StandardScaler
# scaler=StandardScaler()
# x_train=scaler.fit_transform(x_train)
# x_test=scaler.transform(x_test) # '''We should only use transform(),because the TEST data should only transform from pattern of train data which has been trained and fitted.'''
#
# print(x_train.shape)
# print(x_test.shape)
#
# ###################
# ## Building the model:
# ###################
#
# from sklearn.neighbors import KNeighborsClassifier
# model=KNeighborsClassifier(n_neighbors=4)
# model.fit(x_train,y_train)
# ## 03 stratify:
#
# ## This time , we will keep stratify condition when we tend to split our data to test and train w.r.t. Y.
#
# import numpy as np
# import pandas as pd
# import matplotlib.pyplot as plt
#
# #############
# ## reading data:
# #############
# df=pd.read_csv(r'D:\Koolac\06- Machine Learning\P00-01-Datasets\01-Ad.csv')
# print(df.info(),end='\n\n')
# print('DF Head: \n',df.head(),end='\n\n')
#
# x=df.iloc[:,3:-1].values #input
# y=df.iloc[:,-1].values #output
#
#
# ###############################
# ## preprocessing:
# ###############################
#
# ## train test split:
# from sklearn.model_selection import train_test_split
# x_train,x_test,y_train,y_test=train_test_split(x,y,test_size=0.25,stratify=y) # we stratify our data during splitting
# print('x_train "before scaling"\n',x_train)
# print('x_test "before scaling"\n',x_test)
#
# ## scaling:
# from sklearn.preprocessing import StandardScaler
# scaler=StandardScaler()
# x_train=scaler.fit_transform(x_train)
# x_test=scaler.transform(x_test) # '''We should only use transform(),because the TEST data should only transform from pattern of train data which has been trained and fitted.'''
# print('x_train "after scaling"\n',x_train)
# print('x_test "after scaling"\n',x_test)
#
# #########################
# ## Building the model
# #########################
#
# from sklearn.neighbors import KNeighborsClassifier
# model=KNeighborsClassifier(n_neighbors=5)
# model.fit(x_train,y_train)
## 04 train test split (complementary)
'''NOTE : this video is about difference between "fit_transform" for trained data and "transform" for test data,which has been commented beside of codes in previous lesson. '''
# ## 05-prediction and accuracy (accuracy is just one of the Evaluation metrics )
#
# import numpy as np
# import pandas as pd
# import matplotlib.pyplot as plt
#
# ########################
# ## Reading Data
# ########################
#
# df=pd.read_csv(r'D:\Koolac\06- Machine Learning\P00-01-Datasets\01-Ad.csv')
# print(df.info(),end='\n\n')
# print('DF Shape:\n',df.shape,end='\n\n')
# print('DF Head:\n',df.head(),end='\n\n')
#
# x=df.iloc[:,3:-1].values #input
# y=df.iloc[:,-1].values #output
#
# ##################################
# ## Preprocessing:
# ##################################
#
# ## Train Test Splitting:
# from sklearn.model_selection import train_test_split
#
# x_train,x_test,y_train,y_test=train_test_split(x,y,test_size=0.25,stratify=y,random_state=40) # we stratifed our data and put seed==40 , as make it same with koolac.
#
# ## scaling:
# from sklearn.preprocessing import StandardScaler #Going to choose Standard normalization as our scaler
#
# scaler=StandardScaler()
# x_train=scaler.fit_transform(x_train)
# x_test=scaler.transform(x_test)
#
# ################################
# ## Building the model:
# ################################
# from sklearn.neighbors import KNeighborsClassifier # utilizing KNN as our model to training the data
#
# model=KNeighborsClassifier(n_neighbors=7)
# model.fit(x_train,y_train)
#
# ##################################
# ## Predicting and Evaluating:
# ##################################
#
# ## predicting:
# y_pred=model.predict(x_test)
#
# ## evaluating:
# from sklearn.metrics import accuracy_score # we use Accuracy metric to evaluate our model.
# ## ---- accuracy:
# acc=accuracy_score(y_test,y_pred)
# print(f'Our accuracy is {acc*100}%.')
## 06 accuracy shortcomings:
'''In this video we can conclude that the ACCURACY as an evaluating index, is not proper for biased outputed data (i.e.: oue labels,"y").
for example it's suitable for about 50%-50% unbiased output, not 90%-10% !!!'''
## 07 confusion matrix-concept:
'''Since may accuracy metric depends on unbiased or biased output have different efficiency, we should introduce and work with
another evaluation indices. one of them call "Confusion Matrix". '''
# import numpy as np
# import pandas as pd
# import matplotlib.pyplot as plt
#
# ########################
# ## Reading Data
# ########################
#
# df=pd.read_csv(r'D:\Koolac\06- Machine Learning\P00-01-Datasets\01-Ad.csv')
# print(df.info(),end='\n\n')
# print('DF Shape:\n',df.shape,end='\n\n')
# print('DF Head:\n',df.head(),end='\n\n')
#
# x=df.iloc[:,3:-1].values #input
# y=df.iloc[:,-1].values #output
#
# ##################################
# ## Preprocessing:
# ##################################
#
# ## Train Test Splitting:
# from sklearn.model_selection import train_test_split
#
# x_train,x_test,y_train,y_test=train_test_split(x,y,test_size=0.25,stratify=y,random_state=40) # we stratifed our data and put seed==40 , as make it same with koolac.
#
# ## scaling:
# from sklearn.preprocessing import StandardScaler #Going to choose Standard normalization as our scaler
#
# scaler=StandardScaler()
# x_train=scaler.fit_transform(x_train)
# x_test=scaler.transform(x_test)
#
# ################################
# ## Building the model:
# ################################
# from sklearn.neighbors import KNeighborsClassifier # utilizing KNN as our model to training the data
#
# model=KNeighborsClassifier(n_neighbors=7)
# model.fit(x_train,y_train)
#
# ##################################
# ## Predicting and Evaluating:
# ##################################
#
# ## predicting:
# y_pred=model.predict(x_test)
#
# ## evaluating:
#
# ## ---- accuracy:
# from sklearn.metrics import accuracy_score # we use Accuracy metric to evaluate our model.
# acc=accuracy_score(y_test,y_pred)
# print(f'Our accuracy is {acc*100}%.',end='\n\n')
# ## ------ confusion matrix:
# from sklearn.metrics import confusion_matrix
# label_orders=[0,1]
# cm=confusion_matrix(y_test,y_pred,labels=label_orders) #note that the default labels for CM is np.sort(<<<<y_test>>>>> or <<<<<y_pred>>>>>>) i.e.: it's ascending.which is equal to [0,1] here, so it wasn't nececery to mention that in code.
# print('The Confusion Matrix:\n',cm,end='\n\n')
#
# ## 09 confusion matrix-in data frame format
#
# '''We can use a Pandas DataFrame to visualize our confusion matrix better.
# So : '''
# labels_order=[0,1]
# cm_df=pd.DataFrame(cm,index=labels_order,columns=labels_order)
# print('The Confusion Matrix Dataframe:\n',cm_df,end='\n\n')
## 10 normalized confusion matrix
'''Confusion matrix has better comprehension to the users when describes as Normalized one. So we introduce Normalize Confusion Matrix:'''
# import numpy as np
# import pandas as pd
# import matplotlib.pyplot as plt
#
# ######################
# ## Reading Data:
# ######################
#
# df=pd.read_csv(r'D:\Koolac\06- Machine Learning\P00-01-Datasets\01-Ad.csv')
# print(df.info(),end='\n\n')
# print('DF Shape:\n',df.shape,end='\n\n')
# print('DF Head:\n',df.head(),end='\n\n')
#
# x=df.iloc[:,3:-1] #input
# y=df.iloc[:,-1] #output
#
# ##################################
# ## Preprocessing:
# ##################################
#
# ## train test splitting:
# from sklearn.model_selection import train_test_split
# x_train,x_test,y_train,y_test=train_test_split(x,y,test_size=0.25,stratify=y,random_state=40)
#
# ## scaling:
# from sklearn.preprocessing import StandardScaler
# scaler=StandardScaler()
# x_train=scaler.fit_transform(x_train)
# x_test=scaler.transform(x_test)
#
# ################################
# ## Building model:
# ################################
#
# ## KNN:
# from sklearn.neighbors import KNeighborsClassifier
# model=KNeighborsClassifier(n_neighbors=7)
# model.fit(x_train,y_train)
#
#
# ################################
# ## Predicting and Evaluating:
# ################################
#
# ##predicting:
# y_pred=model.predict(x_test)
#
# ##evaluating:
#
# ## ---- Accuracy:
# from sklearn.metrics import accuracy_score
# acc=accuracy_score(y_test,y_pred)
# print('The accuracy is {}%'.format(acc*100))
#
# ## ---- confusion matrix:
# from sklearn.metrics import confusion_matrix
# labels_order=[0,1]
# cm=confusion_matrix(y_test,y_pred,labels=labels_order)
# cm_df=pd.DataFrame(cm,index=labels_order,columns=labels_order)
# print('Confusion Matrix DF:\n',cm_df,end='\n\n')
#
# ## ---- Normalize Confusion Matrix:
# normalized_cm=np.round(cm/np.sum(cm,axis=1).reshape(-1,1),2)
# normalized_cm_df=pd.DataFrame(normalized_cm,index=labels_order,columns=labels_order)
# print('Normalized Confusion Matrix DF:\n',normalized_cm_df,end='\n\n')
## 11 heatmap for confusion matrix:
'''Now we are going to plot our (Normalized)CM. We should use Seaborn module beside matplotlib. the function that we use is heatmap,
i.e: sns.heatmap().'''
# import numpy as np
# import pandas as pd
# import matplotlib.pyplot as plt
#
# ######################
# ## Reading Data:
# ######################
#
# df=pd.read_csv(r'D:\Koolac\06- Machine Learning\P00-01-Datasets\01-Ad.csv')
# print(df.info(),end='\n\n')
# print('DF Shape:\n',df.shape,end='\n\n')
# print('DF Head:\n',df.head(),end='\n\n')
#
# x=df.iloc[:,3:-1] #input
# y=df.iloc[:,-1] #output
#
# ##################################
# ## Preprocessing:
# ##################################
#
# ## train test splitting:
# from sklearn.model_selection import train_test_split
# x_train,x_test,y_train,y_test=train_test_split(x,y,test_size=0.25,stratify=y,random_state=40)
#
# ## scaling:
# from sklearn.preprocessing import StandardScaler
# scaler=StandardScaler()
# x_train=scaler.fit_transform(x_train)
# x_test=scaler.transform(x_test)
#
# ################################
# ## Building model:
# ################################
#
# ## KNN:
# from sklearn.neighbors import KNeighborsClassifier
# model=KNeighborsClassifier(n_neighbors=7)
# model.fit(x_train,y_train)
#
#
# ################################
# ## Predicting and Evaluating:
# ################################
#
# ##predicting:
# y_pred=model.predict(x_test)
#
# ##evaluating:
#
# ## ---- Accuracy:
# from sklearn.metrics import accuracy_score
# acc=accuracy_score(y_test,y_pred)
# print('The accuracy is {}%'.format(acc*100))
#
# ## ---- confusion matrix:
# from sklearn.metrics import confusion_matrix
# labels_order=[0,1]
# cm=confusion_matrix(y_test,y_pred,labels=labels_order)
# cm_df=pd.DataFrame(cm,index=labels_order,columns=labels_order)
# print('Confusion Matrix DF:\n',cm_df,end='\n\n')
#
# ## ---- Normalized Confusion Matrix:
# normalized_cm=np.round(cm/np.sum(cm,axis=1).reshape(-1,1),2)
# normalized_cm_df=pd.DataFrame(normalized_cm,index=labels_order,columns=labels_order)
# print('Normalized Confusion Matrix DF:\n',normalized_cm_df,end='\n\n')
#
# ## ---- ---- confusion matrix heatmap:
# import seaborn as sns
#
# sns.heatmap(normalized_cm,cmap='Greens',annot=True,fmt='0.2f',xticklabels=labels_order,yticklabels=labels_order,cbar_kws={'label':'Color Bar','orientation':'vertical'}) #we can also put cm_df(i.e: a Dataframe).
# # "annot" means the numbers must show in middle of heatmap. "fmt" means how many digits after floating point should be previewed.
# # for instance, fmt='0.2f' implies that 2 number of floating and it should be FIXED.(i.e: also the number was an integer it should preview the rest of it
# # Exmpl: 34.00). we can use "cbar_kws" as configuring the color bar.the color bar default orientation is vertical.
# plt.title('Normalized Confusion Matrix')
# plt.xlabel('Predicted')
# plt.ylabel('Actual')
# plt.show()
#
# ## ---- ---- normalized confusion matrix heatmap:
# sns.heatmap(cm,cmap='Greens',annot=True,fmt='0.2f',xticklabels=labels_order,yticklabels=labels_order,cbar_kws={'label':'Color Bar','orientation':'vertical'}) #we can also put cm_df
# plt.title('Confusion Matrix')
# plt.xlabel('Predicted')
# plt.ylabel('Actual')
# plt.show()
'''P02-02-Prediction and Evaluation-Part 02'''
## 12 recall, precision, specificity-theory
'''in this video, explained about Recall(Sensitivity) and Precision as important indices which has Plug&Play function in sklearn. the another index, the
Specification doesn't have a function or module in python. so we should compute it with our handwritten code.'''
## 13 recall, precision, specificity-Python
'''let's apply these indices to our confusion matrix.'''
# import numpy as np
# import pandas as pd
# import matplotlib.pyplot as plt
#
# ################################
# ## Reading Data:
# ################################
#
# df=pd.read_csv(r'D:\Koolac\06- Machine Learning\P00-01-Datasets\01-Ad.csv')
# print(df.info(),end='\n\n')
# print('DF Shape:\n',df.shape,end='\n\n')
# print('DF Head:\n',df.head(),end='\n\n')
#
# x=df.iloc[:,3:-1] #input
# y=df.iloc[:,-1] #output
#
# #########################
# ## Preprocessing:
# #########################
#
# ## Train Test Splitting:
# from sklearn.model_selection import train_test_split
# x_train,x_test,y_train,y_test=train_test_split(x,y,test_size=0.25,stratify=y,random_state=40)
#
# ## Scaling:
# ## -- Standard Scaling:
# from sklearn.preprocessing import StandardScaler
# scaler=StandardScaler()
# x_train=scaler.fit_transform(x_train)
# x_test=scaler.transform(x_test)
#
#
# ########################
# ## Building our model:
# ########################
# ## KNN:
# from sklearn.neighbors import KNeighborsClassifier
# model=KNeighborsClassifier(n_neighbors=7)
# model.fit(x_train,y_train)
#
# ########################
# ## Prediction and Evaluation:
# ########################
#
# ## Prediction:
# y_pred=model.predict(x_test)
#
# ## Evaluation:
# ## ---- accuracy:
# from sklearn.metrics import accuracy_score
# acc=accuracy_score(y_test,y_pred)
# print(f'The Accuracy is {acc*100}%',end='\n\n')
# ## ---- Confusion Matrix:
# from sklearn.metrics import confusion_matrix
# labels_order=[0,1]
# cm=confusion_matrix(y_test,y_pred,labels=labels_order)
# cm_df=pd.DataFrame(cm,index=labels_order,columns=labels_order)
# print('CM DF: \n',cm_df,end='\n\n')
#
#
# ## ---- ---- Confusion Matrix Recall(Sensitivity),Precision and Specificity:
# ## Recall:
# from sklearn.metrics import recall_score
# recall=recall_score(y_test,y_pred,labels=labels_order)
# print('Recall: ',recall,end='\n\n')
#
# ## Precision:
# from sklearn.metrics import precision_score
# precision=precision_score(y_test,y_pred,labels=labels_order)
# print('Precision: ',precision,end='\n\n')
#
# ## Specificity:
# specificity=cm[0,0]/np.sum(cm[0,:])
# print('Specificity: ',specificity,end='\n\n')
#
#
# ## ---- ---- Confusion Matrix Heatmap:
# import seaborn as sns
# plt.figure('Confusion Matrix')
# sns.heatmap(cm_df,cmap='Greens',fmt='0.2f',annot=True,xticklabels=labels_order,yticklabels=labels_order,cbar_kws={'label':'Color Bar',"orientation":"vertical"})
# plt.title('Confusion Matrix')
# plt.xlabel('Predicted')
# plt.ylabel('Actual')
# plt.tight_layout()
#
#
# ## ---- Normalized Confusion Matrix:
# normalized_cm=cm/np.sum(cm,axis=1).reshape(-1,1)
# normalized_cm_df=pd.DataFrame(normalized_cm,index=labels_order,columns=labels_order)
# print('Normalized Confusion Matrix: \n',normalized_cm_df,end='\n\n')
#
# ## ---- ----Normalized Confusion Matrix Heatmap:
# import seaborn as sns
# plt.figure('Normalized Confusion Matrix')
# sns.heatmap(normalized_cm_df,cmap='Greens',fmt='0.2f',annot=True,xticklabels=labels_order,yticklabels=labels_order,cbar_kws={'label':'Color Bar',"orientation":"vertical"})
# plt.title('Normalized Confusion Matrix')
# plt.xlabel('Predicted')
# plt.ylabel('Actual')
# plt.tight_layout()
# # plt.show()
## 14 recall, precision, specificity-shortcomings
'''In this video we understood that we should never persist on only one kind of Confusion matrix property, we should chech CM along to all indeices like
Recall score, Prcision score, specificity score and F1 Score; which F1 Score will be discussed into the next video.'''
## 15 f1 score
'''F1 Score or F1 Measure is Harmonic Mean of Recall score and Precision score.[ i.e.: (2)/((1/Recall)+(1/Precision)) ] and is used to give us a general
report of recall an precision indices at once. general formula of Harmonic Mean is : n/Sigma_i_to_n(1/x_i) '''
''' we can calculate it like below:'''
# from sklearn.metrics import f1_score
# f1=f1_score(y_test,y_pred,labels=labels_order)
# print('F1 Score: \n',f1,end='\n\n')
#
# plt.show() ## from above section! not ##15 section.
## 16 harmonic mean:
'''this video was a description of Harmonic Mean and its applicable .'''
## 17 ROC (theory):
'''' In this video talked about TP Rate (TPR) [which is our Recall score.] and FPR (i.e.: FP/TN+FP). they lead us to plot ROC diagram ;
which is TPR w.r.t. FPR and both of axes are earned from a cut-off or Threshold that we set during modeling.
prediction is not only <<<y_pred=model.predict(x_test)>>> ;but also <<<y_pred_prob=model.predict_proba(x_test)>>>; where return a (-1,2)-shaped array,
which its first column implies (if assume as default, our label order is [0,1], i.e.: being negative or being positive) probablity of being negative
and second column correspond to being positive. if we set a threshold or a cut-off to one of this column,(one column is enoguh for analysing) the mapped
answer will produce a FPR and a TPR,and predicted y values would be changed. if we change our range of cut-off in a set of desired value,
it would return us a range of FPR and TPR and we can plot it as ROC diagram. '''
## 18-ROC (Python)
'''this video represent ROC plotting and computation with 3 method , AUC ( area of under curve ) and etc.'''
# import numpy as np
# import pandas as pd
# import matplotlib.pyplot as plt
#
# ################################
# ## Reading Data:
# ################################
#
# df=pd.read_csv(r'D:\Koolac\06- Machine Learning\P00-01-Datasets\01-Ad.csv')
# print(df.info(),end='\n\n')
# print('DF Shape:\n',df.shape,end='\n\n')
# print('DF Head:\n',df.head(),end='\n\n')
#
# x=df.iloc[:,3:-1] #input
# y=df.iloc[:,-1] #output
#
# #########################
# ## Preprocessing:
# #########################
#
# ## Train Test Splitting:
# from sklearn.model_selection import train_test_split
# x_train,x_test,y_train,y_test=train_test_split(x,y,test_size=0.25,stratify=y,random_state=40)
#
# ## Scaling:
# ## -- Standard Scaling:
# from sklearn.preprocessing import StandardScaler
# scaler=StandardScaler()
# x_train=scaler.fit_transform(x_train)
# x_test=scaler.transform(x_test)
#
#
# ########################
# ## Building our model:
# ########################
# ## KNN:
# from sklearn.neighbors import KNeighborsClassifier
# model=KNeighborsClassifier(n_neighbors=7)
# model.fit(x_train,y_train)
#
# ########################
# ## Prediction and Evaluation:
# ########################
#
# ## Prediction:
# y_pred=model.predict(x_test)
# y_pred_prob=model.predict_proba(x_test) ## it will produce a 2D array which tell us how much it's possible label (w.r.t. how we define label order) be negative or positive.
#
# ## Evaluation:
# ## ---- accuracy:
# from sklearn.metrics import accuracy_score
# acc=accuracy_score(y_test,y_pred)
# print(f'The Accuracy is {acc*100}%',end='\n\n')
# ## ---- Confusion Matrix:
# from sklearn.metrics import confusion_matrix
# labels_order=[0,1]
# cm=confusion_matrix(y_test,y_pred,labels=labels_order)
# cm_df=pd.DataFrame(cm,index=labels_order,columns=labels_order)
# print('CM DF: \n',cm_df,end='\n\n')
#
#
# ## ---- ---- Confusion Matrix Recall(Sensitivity),Precision and Specificity:
# ## Recall:
# from sklearn.metrics import recall_score
# recall=recall_score(y_test,y_pred,labels=labels_order)
# print('Recall: ',recall,end='\n\n')
#
# ## Precision:
# from sklearn.metrics import precision_score
# precision=precision_score(y_test,y_pred,labels=labels_order)
# print('Precision: ',precision,end='\n\n')
#
# ## Specificity:
# specificity=cm[0,0]/np.sum(cm[0,:])
# print('Specificity: ',specificity,end='\n\n')
#
# ## F1 Score:
# from sklearn.metrics import f1_score
# f1=f1_score(y_test,y_pred,labels=labels_order)
# print('F1 Score: \n',f1,end='\n\n')
#
# ## ROC (Reciever Operating Characterictic Curve):
# ##--method (1): <<<<from_predictions>>>
# from sklearn.metrics import RocCurveDisplay
# # plt.figure('ROC_Method_1')
# RocCurveDisplay.from_predictions(y_true=y_test,y_pred=y_pred_prob[:,1]) ## we should insert y_pred_prob[:,1] as y_pred argument. the 1st column ( [:,1] )here represent probablity of being positive.
# plt.title('ROC: Method(1)')
# plt.tight_layout()
#
#
# ##--method (2): <<<from_estimator>>>
# from sklearn.metrics import RocCurveDisplay
# # plt.figure('ROC_Method2')
# RocCurveDisplay.from_estimator(estimator=model,X=x_test,y=y_test) ## we insert our estimator model (here is KNeighborClassifier(n_neighbors=7)) and our true test data x and y.
# plt.title('ROC: Method(2)')
# plt.tight_layout()
#
# ##--method (3): """the best and recommend way"""
# from sklearn.metrics import roc_curve
# fpr,tpr,threshold=roc_curve(y_true=y_test,y_score=y_pred_prob[:,1]) ## this function return FPR,TPR and Cut-off (threshold)
# plt.figure('ROC_Method3')
# plt.plot(fpr,tpr,c='blueviolet',label='ROC w.r.t. FPR-TPR')
# plt.legend()
# plt.title('ROC: Method(3)')
# plt.xlabel('FPR')
# plt.ylabel('TPR')
# plt.tight_layout()
#
# ##AUC (Area Under Curve):
# from sklearn.metrics import roc_auc_score
# auc=roc_auc_score(y_true=y_test,y_score=y_pred_prob[:,1])
# print('AUC: \n',auc,end='\n\n')
#
#
#
# ## ---- ---- Confusion Matrix Heatmap:
# import seaborn as sns
# plt.figure('Confusion Matrix')
# sns.heatmap(cm_df,cmap='Greens',fmt='0.2f',annot=True,xticklabels=labels_order,yticklabels=labels_order,cbar_kws={'label':'Color Bar',"orientation":"vertical"})
# plt.title('Confusion Matrix')
# plt.xlabel('Predicted')
# plt.ylabel('Actual')
# plt.tight_layout()
#
#
# ## ---- Normalized Confusion Matrix:
# normalized_cm=cm/np.sum(cm,axis=1).reshape(-1,1)
# normalized_cm_df=pd.DataFrame(normalized_cm,index=labels_order,columns=labels_order)
# print('Normalized Confusion Matrix: \n',normalized_cm_df,end='\n\n')
#
# ## ---- ----Normalized Confusion Matrix Heatmap:
# import seaborn as sns
# plt.figure('Normalized Confusion Matrix')
# sns.heatmap(normalized_cm_df,cmap='Greens',fmt='0.2f',annot=True,xticklabels=labels_order,yticklabels=labels_order,cbar_kws={'label':'Color Bar',"orientation":"vertical"})
# plt.title('Normalized Confusion Matrix')
# plt.xlabel('Predicted')
# plt.ylabel('Actual')
# plt.tight_layout()
# plt.show()
#
#
#
# ## 19 visualization of the model decision boundaries:
#
# '''this video talk about how to visualize our model (e.g.: KNN) yo shown decision boundaries. it is usful for datasets which their
# entangled features for learning process are 2 or 3 at last. this give us a 2D or 3D diagram. this video showed that KNN model
# has a non-linear region and it is not only a single line which divide the area by two. it could be divide area to multiple sectors
# which gonna correspond being 0 (Negative) or 1 (Positive).'''
#
# ## 20 visualization of the model decision boundaries-complementary
# '''Now let's visualize the decision boundaries of our KNN model which has 2 Feature in this issue, so we can easely visualize it because of being 2D. '''
#
#
# ######################################################
# # vizualization of the model's decision boundries
# ######################################################
# model_name="KNN"
# is_scaled=True
#
# # --- train
# from matplotlib.colors import ListedColormap
# cmap=ListedColormap(["red","green"])
#
# x_set,y_set=x_train,y_train
#
# x1,x2=np.meshgrid(np.arange(start=x_set[:,0].min()-1,stop=x_set[:,0].max()+1,step=0.01),
# np.arange(start=x_set[:,1].min()-1,stop=x_set[:,1].max()+1,step=0.01))
# plt.scatter(x1.ravel(),x2.ravel())
# plt.show()
# plt.contourf(x1,x2,model.predict(np.array([x1.ravel(),x2.ravel()]).T).reshape(x1.shape),alpha=0.25,cmap=cmap)
# plt.xlim(x1.min(),x1.max())
# plt.ylim(x2.min(),x2.max())
# for i, j in enumerate(np.unique(y_set)):
# plt.scatter(x_set[y_set==j,0],x_set[y_set==j,1], s=20, color=cmap(i), label=j)
# plt.title(f"{model_name} (Training set)")
# plt.xlabel("Age (Scaled)" if is_scaled else "Age")
# plt.ylabel("Estimated Salary (Scaled)" if is_scaled else "Estimated Salary")
# plt.legend()
# plt.show()
#
# # --- test
# from matplotlib.colors import ListedColormap
# cmap=ListedColormap(["red","green"])
#
# x_set,y_set=x_test,y_test
#
# x1,x2=np.meshgrid(np.arange(start=x_set[:,0].min()-1,stop=x_set[:,0].max()+1,step=0.01),
# np.arange(start=x_set[:,1].min()-1,stop=x_set[:,1].max()+1,step=0.01))
#
# plt.contourf(x1,x2,model.predict(np.array([x1.ravel(),x2.ravel()]).T).reshape(x1.shape),alpha=0.25,cmap=cmap)
# plt.xlim(x1.min(),x1.max())
# plt.ylim(x2.min(),x2.max())
# for i, j in enumerate(np.unique(y_set)):
# plt.scatter(x_set[y_set==j,0],x_set[y_set==j,1], s=20, color=cmap(i), label=j)
# plt.title(f"{model_name} (Test set)")
# plt.xlabel("Age (Scaled)" if is_scaled else "Age")
# plt.ylabel("Estimated Salary (Scaled)" if is_scaled else "Estimated Salary")
# plt.legend()
# plt.show()
## 21 cleaning the codes:
'''as the last video of this chapter, let's clean our code. '''
# import numpy as np
# import pandas as pd
# import matplotlib.pyplot as plt
#
# ########################
# ## Reading Data:
# ########################
#
# df=pd.read_csv(r'D:\Koolac\06- Machine Learning\P00-01-Datasets\01-Ad.csv')
# print(df.info(),end='\n\n')
# print('DF Head:\n',df.head(),end='\n\n')
# print('DF Shape:\n',df.shape,end='\n\n')
#
# x=df.iloc[:,3:-1] #input
# y=df.iloc[:,-1] #output
#
# ###########################
# ## Preprocessing:
# ###########################
#
# ##Train Test Splitting
# from sklearn.model_selection import train_test_split
#
# x_train,x_test,y_train,y_test=train_test_split(x,y,test_size=0.25,stratify=y,random_state=None) ##random state==40 correspond to Koolac.org
#
# ## Scaling:
# from sklearn.preprocessing import StandardScaler
#
# scaler=StandardScaler()
# x_train=scaler.fit_transform(x_train)
# x_test=scaler.transform(x_test)
#
# ###############################
# ## Building The Model:
# ###############################
# ## KNN:
# from sklearn.neighbors import KNeighborsClassifier
#
# model=KNeighborsClassifier(n_neighbors=7) #KNN model with N==7
# model.fit(x_train,y_train)
#
# ################################
# ## Prediction and Evalusation:
# ################################
# ## Prediction:
# y_pred=model.predict(x_test) #predicted target values
# y_pred_prob=model.predict_proba(x_test) # and (x_test.shape[0] x 2) array of probablity of being Zero (Negative) or One (Positive)
#
#
#
# ## Evaluation:
#
# label_order=[0,1]
#
# ## --- Confusion Matrix:
# from sklearn.metrics import confusion_matrix
# cm=confusion_matrix(y_true=y_test,y_pred=y_pred,labels=label_order)
# cm_df=pd.DataFrame(cm,index=label_order,columns=label_order)
# print('CM DF:\n',cm_df,end='\n\n')
#
# ## --- Normalized Confusion Matrix: