-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path4_functions.py
2620 lines (2214 loc) · 111 KB
/
4_functions.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
# CSP ML Algorithm
# CSP = Categorical - Similarity - Probability
# This function makes the full model (with all data) and the train model (with partial data : split train-test) and evaluates the train model.
def csp():
# Create the train, test and full sets.
# The train set (X_train) is df without the x% test rows extracted. X_train contains the values to be predicted (last column).
# The test set (X_test) is a random extract of x% of df rows. X_test does not contain the values to be predicted (last column removed).
# The full train set (X_full_train) is full df, used to make the model with all data. X_full_train contains the values to be predicted (last column).
# The full test set (X_full_test) is full df, used to make the model with all data. X_full_test does not contain the values to be predicted (last column removed).
X_full_train = deepcopy(df)
X_full_test = deepcopy(df)
X_train = deepcopy(df)
X_test = []
# Feed X_test by extracting from X_train
rows_qty_to_extract = round(len(df) * 0.005)
for i in range(0, rows_qty_to_extract):
random_index = random.randint(0, len(X_train)-1)
X_test.append(X_train[random_index])
del X_train[random_index]
# Split X_test into X_test and y_test
y_test = []
for tab in X_test:
y_test.append(tab[-1])
del tab[-1]
# Split X_full_test into X_full_test and y_full_test
y_full_test = []
for tab in X_full_test:
y_full_test.append(tab[-1])
del tab[-1]
# --------------------
# Make Model for splitted data
print("Making Model (for splitted data)...")
csp_model_maker(X_train, "train")
# Evaluate model for splitted data
# Predict on test data
y_pred = ask_csp(X_test, "train")
# Compute evaluation metrics
evaluation_metrics = evaluate_model(y_test, y_pred)
# --------------------
# # Make Model for full data
# print(LINE_UP, end=LINE_CLEAR)
# print("Making Model (for full data)...")
# csp_model_maker(X_full_train, "full")
# # Evaluate model for full data
# # Predict on test data
# y_full_pred = ask_csp(X_full_test, "full")
# # Compute evaluation metrics
# evaluation_metrics = evaluate_model(y_full_test, y_full_pred)
# --------------------
return [
evaluation_metrics
]
# Function to make the csp models.
# Input X_train : data to work with, either full or just a train part.
# Input mode : "full" (all data) or "train" (partial data).
def csp_model_maker(X_train, mode):
# ------------------------------
X_train_rows = len(X_train)
X_train_columns = len(X_train[0])
X_train_max_index = X_train_columns - 1
# ------------------------------
# Create model_rows_root
# ------------------------------
# Create a model associating to each possible row, its possible predicted values with their quantities observed in X_train.
# Ex: string_row_x => pv1 => 2
# => pv5 => 3
model_rows_root = {}
for r in range(0, X_train_rows):
list_row = deepcopy(X_train[r])
list_row.pop()
# Stringify the row
# "@@@" is the separator between values
row = ""
for val in list_row:
row += str(val) + "@@@"
# If the row already exists in the model.
if row in model_rows_root:
# Get the pv of the row.
pv_to_append = X_train[r][X_train_max_index]
# If the pv is in mrr for the row.
if pv_to_append in model_rows_root[row]:
# Increment the pv value for this row in mrr.
model_rows_root[row][pv_to_append] += 1
# Else, create a new key-value to add the pv for this row in mrr.
else:
new_key_value = {pv_to_append:1}
model_rows_root[row].update(new_key_value)
# Else, create a new key-value to add the row to mrr with its pv.
else:
new_key_value = {row:{}}
model_rows_root.update(new_key_value)
pv_to_append = X_train[r][X_train_max_index]
new_key_value = {pv_to_append:1}
model_rows_root[row].update(new_key_value)
# ------------------------------
# Create model_complete and model_reducted
# ------------------------------
# Explode X_train in many parts, each part corresponding to a possible value to predict (Y) and containing the rows associated to this value.
df_ex = {}
predict_values = []
for r in range(0, X_train_rows):
predict_value = X_train[r][X_train_max_index]
if predict_value in predict_values:
row_to_append = deepcopy(X_train[r])
row_to_append.pop()
df_ex[predict_value].append(row_to_append)
else:
predict_values.append(predict_value)
new_key_value = {predict_value:[]}
df_ex.update(new_key_value)
row_to_append = deepcopy(X_train[r])
row_to_append.pop()
df_ex[predict_value].append(row_to_append)
# ------------------------------
# Retrieve the values appearing for each predictor field.
# Ex : {1, 3}{2, 3} => predicted_value_1
# Each {} contains the possible values of a predictor field that are present in the data for the value to be predicted currently being processed.
# Associate the percentage of presence with each value of the super key (the total number of occurrences is the number of occurrences for the value to be predicted currently being processed).
# Ex : {1:0.3, 3:0.1}{2:0.45, 3:0.1} => predicted_value_1
# So, a complete model with 3 pvs would look like this :
# {1:0.3, 3:0.1}{2:0.45, 3:0.1} => predicted_value_1
# {3:0.1}{1:0.2, 2:0.5} => predicted_value_2
# {2:0.1}{3:0.7} => predicted_value_3
# ------------------------------
# Number of possible predict values.
n_pv = len(df_ex)
model_complete = {}
for key in df_ex:
# Number of rows for this pv.
n_pv_rows = len(df_ex[key])
# --------------------
# Calculation of the percent_value, which is the base value that will be added to the associated model values.
# 1st Version => Abandoned
# --------------------
# percent_value = 1/n_pv_rows
# --------------------
# 2nd Version => TOP
# --------------------
# coef = (n_pv_rows/X_train_rows)
# percent_value = ((1/n_pv_rows) + ((1+coef)/X_train_rows))
# --------------------
# 2nd Version Simplified
# --------------------
percent_value = (1/n_pv_rows) + (1/X_train_rows) + (n_pv_rows/X_train_rows**2)
# --------------------
# This formula means that at the end of the model, each value is associated with: its probability for the pv to which it belongs plus its number of occurrences for the pv relative to the population size of the global data plus its number of occurrences for the pv multiplied by the population size of the pv and relative to the squared population size of the global data.
# More simply, in fine in the model, each value is associated with: its probability for the pv plus its number of occurrences coefficient for the pv relative to the population size of the global data.
# --------------------
# 3rd Version => TOP
# --------------------
# coef = (n_pv_rows/X_train_rows)
# percent_value = (((1+coef)/n_pv_rows) + (1/X_train_rows))
# --------------------
# 3rd Version Simplified
# --------------------
# percent_value = (1/n_pv_rows) + (2/X_train_rows)
# --------------------
# This formula means that in the model, each value is associated with: its probability for the pv to which it belongs, plus twice its number of occurrences for the pv and relative to the population size of the global data.
# In other words, each value in the model is associated with: its coefficient probability for the pv to which it belongs plus its number of occurrences for the pv and relative to the population size of the global data.
# --------------------
# 4th Version => Abandoned
# --------------------
# percent_value = (1/n_pv_rows) * (2/X_train_rows)
# --------------------
# 5th Version => Abandoned
# --------------------
# percent_value = (1/n_pv_rows) * (1/X_train_rows) * (n_pv_rows/X_train_rows**2)
# --------------------
# Add pair key_value to model_complete.
new_key_value = {key:{}}
model_complete.update(new_key_value)
# Go through this pv rows.
for row in range(0, n_pv_rows):
for column in range(0, X_train_columns-1):
if row == 0:
new_key_value = {column:{}}
model_complete[key].update(new_key_value)
column_value = df_ex[key][row][column]
if column_value in model_complete[key][column]:
model_complete[key][column][column_value] += percent_value
else:
new_key_value = {column_value:percent_value}
model_complete[key][column].update(new_key_value)
# ------------------------------
# Calculate the reduced model by removing from the full model all values with a presence percentage < reduc_value
reduc_value = 0.1
model_reducted = deepcopy(model_complete)
for key in model_complete:
for column in model_complete[key]:
for value in model_complete[key][column]:
if model_complete[key][column][value] < reduc_value:
del model_reducted[key][column][value]
# ------------------------------
# Save models for future queries using ask_csp()
if mode == "train":
with open('Outputs\csp_model_complete_train.pkl', 'wb') as file_cmc:
pickle.dump(model_complete, file_cmc)
with open('Outputs\csp_model_reducted_train.pkl', 'wb') as file_cmr:
pickle.dump(model_reducted, file_cmr)
with open('Outputs\csp_model_rows_root_train.pkl', 'wb') as file_cmrr:
pickle.dump(model_rows_root, file_cmrr)
elif mode == "full":
with open('Outputs\csp_model_complete_full.pkl', 'wb') as file_cmc:
pickle.dump(model_complete, file_cmc)
with open('Outputs\csp_model_reducted_full.pkl', 'wb') as file_cmr:
pickle.dump(model_reducted, file_cmr)
with open('Outputs\csp_model_rows_root_full.pkl', 'wb') as file_cmrr:
pickle.dump(model_rows_root, file_cmrr)
# ------------------------------
# Function to ask the csp() models, previously saved in files.
# Input rows : rows to be predicted (without the prediction column).
# Input mode : "train" or "full" so that the function works on the full model or on the train model.
# Output : predictions associated to each input row.
def ask_csp(rows, mode):
# ------------------------------
# Load models from files
model_complete = {}
model_reducted = {}
model_rows_root = {}
if mode == "train":
with open('Outputs\csp_model_complete_train.pkl', 'rb') as file_cmc:
model_complete = pickle.load(file_cmc)
with open('Outputs\csp_model_reducted_train.pkl', 'rb') as file_cmr:
model_reducted = pickle.load(file_cmr)
with open('Outputs\csp_model_rows_root_train.pkl', 'rb') as file_cmrr:
model_rows_root = pickle.load(file_cmrr)
elif mode == "full":
with open('Outputs\csp_model_complete_full.pkl', 'rb') as file_cmc:
model_complete = pickle.load(file_cmc)
with open('Outputs\csp_model_reducted_full.pkl', 'rb') as file_cmr:
model_reducted = pickle.load(file_cmr)
with open('Outputs\csp_model_rows_root_full.pkl', 'rb') as file_cmrr:
model_rows_root = pickle.load(file_cmrr)
# ------------------------------
# We will get predictions using mrr on one hand and mc_mr on the other hand.
# We will compare predictions between mrr and mc_mr (respectively stored in results_mrr and results_mc_mr). Depending on the comparison we will add final predictions to results.
results = []
results_mrr = []
results_mc_mr = []
# For each row to predict.
for row in range(0, len(rows)):
# Prints
print(LINE_UP, end=LINE_CLEAR)
print("Asking For Row " + colored(row+1, 'yellow') + "/" + str(len(rows)))
# Get the row to predict
to_predict = rows[row]
s_row_split = to_predict
# The array to save predicted values having the same max val
pvs_from_mrr = []
# ------------------------------
# Ask model_rows_root (mrr)
# ------------------------------
# Calculation of similarity percentages between row and model_rows_root rows.
# We keep the model rows having the best similarity percentage above or equal to posim%.
# The mrr results are then determined according to these mrr rows.
posim = 0.8
sim_results = {}
best_sim_score = 0
# Compare the row to predict to each row in mrr in order to determine the similarity score
for mrr_row in model_rows_root:
# Prepare the row.
mrr_row_split = mrr_row.split("@@@")
mrr_row_split.pop()
# Calculate similarity score.
sim_score = 0
for i in range (0, len(s_row_split)):
if s_row_split[i] == mrr_row_split[i]:
sim_score += 1/len(s_row_split)
sim_score = round(sim_score, 2)
# If the similarity score is >= posim and >= best similarity score, save the mrr_row in sim_results. Update the best similarity score if needed.
if sim_score >= posim:
if sim_score > best_sim_score:
# Update the best similarity score.
best_sim_score = sim_score
# Reset sim_results.
sim_results = {}
# Add the row to sim_results.
new_key_value = {mrr_row:sim_score}
sim_results.update(new_key_value)
elif sim_score == best_sim_score:
# Add the row to sim_results.
new_key_value = {mrr_row:sim_score}
sim_results.update(new_key_value)
# If at least one similar row has been found in model_rows_root.
if len(sim_results) >= 1:
# Agregate all sim_results pvs by summing their associated values.
pvs_fused = {}
for sim_row in sim_results:
for key in model_rows_root[sim_row]:
value = model_rows_root[sim_row][key]
if key not in pvs_fused:
new_key_value = {key:value}
pvs_fused.update(new_key_value)
else:
pvs_fused[key] += value
# If there is only one pv in pvs_fused, this pv is the final pv predicted for the row
if len(pvs_fused) == 1:
predicted_value = list(pvs_fused.keys())[0]
results_mrr.append([predicted_value])
# Otherwise, a decision must be made between several pvs, looking to see if several pvs share the maximum value.
else:
# Taking list of values in pvs_fused
v = list(pvs_fused.values())
# Taking list of keys in pvs_fused
k = list(pvs_fused.keys())
# Save max value from v and its index
max_val = max(v)
max_val_index = v.index(max(v))
# Delete max value from v
del v[max_val_index]
# If new max val from v is equal to the deleted one, it means that the max value in v was multiple.
# If max_val is not multiple, the associated pv is the final predicted pv for the row.
if max(v) < max_val:
# predicted_value is the key having the unique max value
predicted_value = k[max_val_index]
results_mrr.append([predicted_value])
# Else, max val from v is multiple so we save all pvs having the max val in pvs_from_mrr.
else:
# Save the first pv discovered having the max val
pvs_from_mrr.append(k[max_val_index])
del k[max_val_index]
# As long as equal max val values are found, they are stored in pvs_from_mrr
while len(v)>0 and max(v) == max_val:
max_val_index = v.index(max(v))
pvs_from_mrr.append(k[max_val_index])
del v[max_val_index]
del k[max_val_index]
results_mrr.append(pvs_from_mrr)
# Else, no similar row has been found in model_rows_root so we append an empty array in mrr results. It will be used for the comparison step with mc_mr results.
else:
results_mrr.append([])
# --------------------------------------
# Ask model_complete and model_reducted
# --------------------------------------
# To query mc and mr, i.e. to find the prediction scores (sp) associated with each predicted_value for the current key "question" (row), we need to calculate, for each predicted_value, the following prediction scores (sp).
# Raw sp with full model.
# Raw similarity percentage between the "question" key and the predicted_value key, without considering the scores associated with the X values.
scores_brut_mc = {}
for pv in model_complete:
score = 0
for i in range(0, len(to_predict)):
if to_predict[i] in model_complete[pv][i]:
score += 1
score = score/len(to_predict)
new_key_value = {pv:score}
scores_brut_mc.update(new_key_value)
# Refined sp with full model.
# Average of the scores of the X values in correspondence between the "question" key and the predicted_value key.
scores_fine_mc = {}
for pv in model_complete:
score = 0
for i in range(0, len(to_predict)):
if to_predict[i] in model_complete[pv][i]:
score += model_complete[pv][i][to_predict[i]]
score = score/len(to_predict)
new_key_value = {pv:score}
scores_fine_mc.update(new_key_value)
# Raw sp with reduced model.
# Raw similarity percentage between the "question" key and the predicted_value key, without considering the scores associated with the X values.
scores_brut_mr = {}
for pv in model_reducted:
score = 0
for i in range(0, len(to_predict)):
if to_predict[i] in model_reducted[pv][i]:
score += 1
score = score/len(to_predict)
new_key_value = {pv:score}
scores_brut_mr.update(new_key_value)
# Refined sp with reduced model.
# Average of the scores of the X values in correspondence between the "question" key and the predicted_value key.
scores_fine_mr = {}
for pv in model_reducted:
score = 0
for i in range(0, len(to_predict)):
if to_predict[i] in model_reducted[pv][i]:
score += model_reducted[pv][i][to_predict[i]]
score = score/len(to_predict)
new_key_value = {pv:score}
scores_fine_mr.update(new_key_value)
# ----------------------------------
# Final predicted_value scores
# ----------------------------------
# sbmc = scores_brut_mc
# sfmc = scores_fine_mc
# sbmr = scores_brut_mr
# sfmr = scores_fine_mr
scores_final = {}
for pv in model_complete:
# --------------------
# Calculation method : Mean(sbmc, sfmc, sbmr, sfmr).
score = mean([
scores_brut_mc[pv],
scores_fine_mc[pv],
scores_brut_mr[pv],
scores_fine_mr[pv]
])
new_key_value = {pv:score}
scores_final.update(new_key_value)
# --------------------
"""
# Calculation method : Mean(sbmc, sfmc, sbmr) with coefficient on sbmc.
# => TOP
# => A high coefficient on sbmc increases accuracy by a few %.
coef = 1
score = mean([
coef*scores_brut_mc[pv],
scores_fine_mc[pv],
scores_brut_mr[pv]
])
new_key_value = {pv:score}
scores_final.update(new_key_value)
"""
# --------------------
"""
# Calculation method : Mean(sfmc, sbmc)
score = mean([
scores_fine_mc[pv],
scores_brut_mc[pv]
])
new_key_value = {pv:score}
scores_final.update(new_key_value)
"""
# --------------------
"""
# Calculation method : sfmc only
score = scores_fine_mc[pv]
new_key_value = {pv:score}
scores_final.update(new_key_value)
"""
# --------------------
"""
# Get the pv having the best score in scores_final and save it in results.
predicted_value = max(scores_final, key=scores_final.get)
results_mc_mr.append(predicted_value)
"""
# Retrieve some best pvs from scores_final, sorted in DESC order.
sorted_sf = sorted(scores_final.items(), key = lambda x:x[1], reverse = True)
bests = [sorted_sf[0][0], sorted_sf[1][0], sorted_sf[2][0]]
results_mc_mr.append(bests)
# Compare results_mrr and results_mc_mr to build final results.
for i in range(0, len(results_mc_mr)):
final_result_found = False
for x in range(0, len(results_mc_mr[i])):
if final_result_found == False:
# If the currently treated mc_mr result is in mrr results, it is the final result so it is added to results.
if results_mc_mr[i][x] in results_mrr[i]:
results.append(results_mc_mr[i][x])
final_result_found = True
# If no match was found in previous step.
if final_result_found == False:
# If there are no entries in mrr results, the final result is considered to be the first result from mc_mr. This result is added to results.
if len(results_mrr[i]) == 0:
results.append(results_mc_mr[i][0])
# Else, the final result is a random result from either mrr results or all results from mrr and mc_mr.
else:
# --------------------
# The final result is a random result from all results from mrr and mc_mr. This result is added to results.
# fused_results = results_mrr[i]
# fused_results.append(results_mc_mr[i][0])
# rand = random.randint(0, len(fused_results)-1)
# results.append(fused_results[rand])
# --------------------
# The final result is a random result from mrr results. This result is added to results.
rand = random.randint(0, len(results_mrr[i])-1)
results.append(results_mrr[i][rand])
# --------------------
print(LINE_UP, end=LINE_CLEAR)
return results
# Function to evaluate a ML model using various metrics.
# y_test : the array of correct classes associated to X_test.
# y_pred : the array of predicted classes, from the model, for X_test.
def evaluate_model(y_test, y_pred):
evaluation_metrics = {}
# accuracy_score
accuracy = accuracy_score(y_test, y_pred)
# print(LINE_UP, end=LINE_CLEAR)
print("Accuracy: " + colored(str(round(accuracy*100)), 'yellow') + "%")
new_key_value = {"accuracy":accuracy}
evaluation_metrics.update(new_key_value)
# balanced_accuracy_score
# The balanced accuracy in binary and multiclass classification problems to deal with imbalanced datasets. It is defined as the average of recall obtained on each class.
# The best value is 1 and the worst value is 0 when adjusted=False.
# balanced_accuracy = balanced_accuracy_score(y_test, y_pred)
# precision_score
# The precision is the ratio tp / (tp + fp) where tp is the number of true positives and fp the number of false positives. The precision is intuitively the ability of the classifier not to label as positive a sample that is negative.
# The best value is 1 and the worst value is 0.
# The average parameter is required for multiclass/multilabel targets. If None, the scores for each class are returned. Otherwise, this determines the type of averaging performed on the data:
# 'binary':
# Only report results for the class specified by pos_label. This is applicable only if targets (y_{true,pred}) are binary.
# 'micro':
# Calculate metrics globally by counting the total true positives, false negatives and false positives.
# 'macro':
# Calculate metrics for each label, and find their unweighted mean. This does not take label imbalance into account.
# 'weighted':
# Calculate metrics for each label, and find their average weighted by support (the number of true instances for each label). This alters ‘macro’ to account for label imbalance; it can result in an F-score that is not between precision and recall.
# 'samples':
# Calculate metrics for each instance, and find their average (only meaningful for multilabel classification where this differs from accuracy_score).
precision_micro = precision_score(y_test, y_pred, average='micro', zero_division=0)
precision_macro = precision_score(y_test, y_pred, average='macro', zero_division=0)
precision_weighted = precision_score(y_test, y_pred, average='weighted', zero_division=0)
new_key_value = {"precision_micro":precision_micro}
evaluation_metrics.update(new_key_value)
new_key_value = {"precision_macro":precision_macro}
evaluation_metrics.update(new_key_value)
new_key_value = {"precision_weighted":precision_weighted}
evaluation_metrics.update(new_key_value)
# f1_score
# Compute the F1 score, also known as balanced F-score or F-measure.
# The F1 score can be interpreted as a harmonic mean of the precision and recall, where an F1 score reaches its best value at 1 and worst score at 0. The relative contribution of precision and recall to the F1 score are equal. The formula for the F1 score is:
# F1 = 2 * (precision * recall) / (precision + recall)
# In the multi-class and multi-label case, this is the average of the F1 score of each class with weighting depending on the average parameter.
# The average parameter is required for multiclass/multilabel targets. If None, the scores for each class are returned. Otherwise, this determines the type of averaging performed on the data:
# 'binary':
# Only report results for the class specified by pos_label. This is applicable only if targets (y_{true,pred}) are binary.
# 'micro':
# Calculate metrics globally by counting the total true positives, false negatives and false positives.
# 'macro':
# Calculate metrics for each label, and find their unweighted mean. This does not take label imbalance into account.
# 'weighted':
# Calculate metrics for each label, and find their average weighted by support (the number of true instances for each label). This alters ‘macro’ to account for label imbalance; it can result in an F-score that is not between precision and recall.
# 'samples':
# Calculate metrics for each instance, and find their average (only meaningful for multilabel classification where this differs from accuracy_score).
f1_micro = f1_score(y_test, y_pred, average='micro', zero_division=0)
f1_macro = f1_score(y_test, y_pred, average='macro', zero_division=0)
f1_weighted = f1_score(y_test, y_pred, average='weighted', zero_division=0)
new_key_value = {"f1_micro":f1_micro}
evaluation_metrics.update(new_key_value)
new_key_value = {"f1_macro":f1_macro}
evaluation_metrics.update(new_key_value)
new_key_value = {"f1_weighted":f1_weighted}
evaluation_metrics.update(new_key_value)
# fbeta_score
# The F-beta score is the weighted harmonic mean of precision and recall, reaching its optimal value at 1 and its worst value at 0.
# The beta parameter represents the ratio of recall importance to precision importance. beta > 1 gives more weight to recall, while beta < 1 favors precision. For example, beta = 2 makes recall twice as important as precision, while beta = 0.5 does the opposite. Asymptotically, beta -> +inf considers only recall, and beta -> 0 only precision.
fbeta_micro = fbeta_score(y_test, y_pred, average='micro', beta=0.5, zero_division=0)
fbeta_macro = fbeta_score(y_test, y_pred, average='macro', beta=0.5, zero_division=0)
fbeta_weighted = fbeta_score(y_test, y_pred, average='weighted', beta=0.5, zero_division=0)
new_key_value = {"fbeta_micro":fbeta_micro}
evaluation_metrics.update(new_key_value)
new_key_value = {"fbeta_macro":fbeta_macro}
evaluation_metrics.update(new_key_value)
new_key_value = {"fbeta_weighted":fbeta_weighted}
evaluation_metrics.update(new_key_value)
# recall_score
# The recall is the ratio tp / (tp + fn) where tp is the number of true positives and fn the number of false negatives. The recall is intuitively the ability of the classifier to find all the positive samples.
# The best value is 1 and the worst value is 0.
recall_micro = recall_score(y_test, y_pred, average='micro', zero_division=0)
recall_macro = recall_score(y_test, y_pred, average='macro', zero_division=0)
recall_weighted = recall_score(y_test, y_pred, average='weighted', zero_division=0)
new_key_value = {"recall_micro":recall_micro}
evaluation_metrics.update(new_key_value)
new_key_value = {"recall_macro":recall_macro}
evaluation_metrics.update(new_key_value)
new_key_value = {"recall_weighted":recall_weighted}
evaluation_metrics.update(new_key_value)
# log_loss
# Log loss, aka logistic loss or cross-entropy loss.
# This is the loss function used in (multinomial) logistic regression and extensions of it such as neural networks, defined as the negative log-likelihood of a logistic model that returns y_pred probabilities for its training data y_true. The log loss is only defined for two or more labels.
# roc_auc_score
# Compute Area Under the Receiver Operating Characteristic Curve (ROC AUC) from prediction scores.
# Note: this implementation can be used with binary, multiclass and multilabel classification, but some restrictions apply (see Parameters).
# zero_one_loss
# brier_score_loss
# jaccard_score
# Jaccard similarity coefficient score.
# The Jaccard index [1], or Jaccard similarity coefficient, defined as the size of the intersection divided by the size of the union of two label sets, is used to compare set of predicted labels for a sample to the corresponding set of labels in y_true.
jaccard_micro = jaccard_score(y_test, y_pred, average='micro', zero_division=0)
jaccard_macro = jaccard_score(y_test, y_pred, average='macro', zero_division=0)
jaccard_weighted = jaccard_score(y_test, y_pred, average='weighted', zero_division=0)
new_key_value = {"jaccard_micro":jaccard_micro}
evaluation_metrics.update(new_key_value)
new_key_value = {"jaccard_macro":jaccard_macro}
evaluation_metrics.update(new_key_value)
new_key_value = {"jaccard_weighted":jaccard_weighted}
evaluation_metrics.update(new_key_value)
# cohen_kappa_score
# hinge_loss
# matthews_corrcoef
# Compute the Matthews correlation coefficient (MCC).
# The Matthews correlation coefficient is used in machine learning as a measure of the quality of binary and multiclass classifications. It takes into account true and false positives and negatives and is generally regarded as a balanced measure which can be used even if the classes are of very different sizes. The MCC is in essence a correlation coefficient value between -1 and +1. A coefficient of +1 represents a perfect prediction, 0 an average random prediction and -1 an inverse prediction. The statistic is also known as the phi coefficient. [source: Wikipedia]
# Binary and multiclass labels are supported. Only in the binary case does this relate to information about true and false positives and negatives.
matthews_cc = matthews_corrcoef(y_test, y_pred)
new_key_value = {"matthews_cc":matthews_cc}
evaluation_metrics.update(new_key_value)
# hamming_loss
# Compute the average Hamming loss.
# The Hamming loss is the fraction of labels that are incorrectly predicted.
# In multiclass classification, the Hamming loss corresponds to the Hamming distance between y_true and y_pred which is equivalent to the subset zero_one_loss function, when normalize parameter is set to True.
# In multilabel classification, the Hamming loss is different from the subset zero-one loss. The zero-one loss considers the entire set of labels for a given sample incorrect if it does not entirely match the true set of labels. Hamming loss is more forgiving in that it penalizes only the individual labels.
# The Hamming loss is upperbounded by the subset zero-one loss, when normalize parameter is set to True. It is always between 0 and 1, lower being better.
ham_loss = hamming_loss(y_test, y_pred)
new_key_value = {"ham_loss":ham_loss}
evaluation_metrics.update(new_key_value)
# confusion_matrix
# multilabel_confusion_matrix
# precision_recall_curve
# roc_curve
return evaluation_metrics
# Function to compute the mdps of a gaps array.
# It is called inside the mdps() function.
def compute_mdps(gaps):
gaps_qty = len(gaps)
gaps_mean = mean(gaps)
gaps_sigma = pstdev(gaps)
mdps = 0
if gaps_sigma > 0:
# MDPS Numerator
mdps_numerator = gaps_qty*(gaps_qty-1)
# MDPS Denominator
deno_part_1 = 0
deno_part_2 = 0
for n in range(0, gaps_qty):
for m in range(n+1, gaps_qty):
deno_part_1 += abs((gaps[n]-gaps[m])/gaps_sigma)
for n in range(0, gaps_qty):
deno_part_2 += abs((gaps[n]-gaps_mean)/gaps_sigma)
mdps_denominator = deno_part_1 * deno_part_2
# MDPS
mdps = mdps_numerator/mdps_denominator
# Contract MDPS value
mdps = round(mdps*100, 2)
return mdps
# Function to measure and explain the cross-referential (cross-dataset) predictive stability of a set of ML models.
# It is the call function.
def mdps():
# The path to the .sav ML models folder.
models_path = "Data\\MDPS_Models\\"
# The path to the datasets folder (Cross-referential system).
datasets_path = "Data\\MDPS_Datasets\\"
all_global_mdps = {}
all_features_mdps = {}
all_y_classes_mdps = {}
all_y_classes_gaps = {}
# For each model
for model_file in os.listdir(models_path):
# Load the model
model_path = models_path + model_file
with open(model_path, 'rb') as f:
model = pickle.load(f)
f.close()
global_mdps = {}
features_mdps = {}
y_classes_mdps = {}
y_classes_gaps = {}
all_pred = []
all_eval = []
all_acc_inter_feat = []
all_acc_inter_feat_max = []
all_acc_inter_feat_min = []
all_acc_intra_feat_max = []
all_acc_intra_feat_min = []
all_mean_feature_class_qty = []
all_each_feature_class_qty = []
all_each_feature_class_acc = []
all_each_feature_acc = []
all_each_y_class_acc = []
all_each_y_class_occ = []
all_dataset_y_class_mean_occ = []
all_dataset_y_class_mean_acc = []
all_each_feature_class_occurrences = []
# For each dataset, load it, predict with the model, do the MDPS measurements, do the visualisations, do the synthesis tables and generate the PDF.
for dataset in os.listdir(datasets_path):
# Load data
file_path = datasets_path + dataset
# Determining the number of columns in the dataset.
with open(file_path) as f:
n_cols = len(f.readline().split(";"))
f.close()
# Load
X = np.loadtxt(file_path, usecols=range(0,n_cols-1), delimiter=";", dtype='str')
y = np.loadtxt(file_path, usecols=n_cols-1, delimiter=";", dtype='str')
# Encode the categorical features
encoder = LabelEncoder()
X = np.transpose(X)
for row in range(0, len(X)):
X[row] = encoder.fit_transform(X[row])
X = np.transpose(X)
# Convert X to numeric values
X = X.astype(int)
# Convert y to numeric values
# y = y.astype(int)
# ------------------------------
# # Predict with handling errors for unseen categories.
# y_pred = []
# for row in X:
# try:
# pred_value = model.predict([row])[0]
# y_pred.append(pred_value)
# except:
# # Append a default "Unknown" prediction.
# y_pred.append("Unknown")
# ic(y_pred)
# evaluation_metrics = evaluate_model(y, y_pred)
# ic(evaluation_metrics)
# sys.exit()
# ------------------------------
# Predict on the dataset with the model
y_pred = model.predict(X)
# Save predictions
all_pred.append(y_pred)
# Evaluate the model
evaluation_metrics = evaluate_model(y, y_pred)
# Save evaluation metrics
all_eval.append(evaluation_metrics)
# Construct the dict containing feature_class accuracies
# feat_n => {class_0:accuracy, class_1:accuracy, ...}
features = {}
for col in range(0, len(X[0])):
feat = "feat_"+str(col)
new_key_value = {feat:{}}
features.update(new_key_value)
for row in range(0, len(X)):
class_ = "class_"+str(X[row][col])
# Check if the pred is right
wrong = 0
right = 0
if y[row] == y_pred[row]:
right = 1
else:
wrong = 1
# Add to features
if class_ in features[feat]:
features[feat][class_]["right"] += right
features[feat][class_]["wrong"] += wrong
features[feat][class_]["accuracy"] = features[feat][class_]["right"]/(features[feat][class_]["right"]+features[feat][class_]["wrong"])
else:
new_key_value = {class_:{}}
features[feat].update(new_key_value)
new_key_value = {"right":right}
features[feat][class_].update(new_key_value)
new_key_value = {"wrong":wrong}
features[feat][class_].update(new_key_value)
new_key_value = {"accuracy":right/(right+wrong)}
features[feat][class_].update(new_key_value)
# Construct the dict containing each feature class occurrences
each_feature_class_occ = {}
for feat in features:
new_key_value = {feat:{}}
each_feature_class_occ.update(new_key_value)
for class_ in features[feat]:
occ = features[feat][class_]["right"]+features[feat][class_]["wrong"]
new_key_value = {class_:occ}
each_feature_class_occ[feat].update(new_key_value)
all_each_feature_class_occurrences.append(each_feature_class_occ)
# Construct the dict containing each feature class accuracy
each_feature_class_acc = {}
for feat in features:
new_key_value = {feat:{}}
each_feature_class_acc.update(new_key_value)
for class_ in features[feat]:
acc = features[feat][class_]["accuracy"]
new_key_value = {class_:acc}
each_feature_class_acc[feat].update(new_key_value)
all_each_feature_class_acc.append(each_feature_class_acc)
# Construct the dict containing y classes accuracies
y_class_acc = {}
for col in range(0, len(y)):
y_class = y[col]
# Check if the pred is right
wrong = 0
right = 0
if y[col] == y_pred[col]:
right = 1
else:
wrong = 1
# Add to y_class_acc
if y_class in y_class_acc:
y_class_acc[y_class]["right"] += right
y_class_acc[y_class]["wrong"] += wrong
y_class_acc[y_class]["accuracy"] = y_class_acc[y_class]["right"]/(y_class_acc[y_class]["right"]+y_class_acc[y_class]["wrong"])
else:
new_key_value = {y_class:{}}
y_class_acc.update(new_key_value)
new_key_value = {"right":right}
y_class_acc[y_class].update(new_key_value)
new_key_value = {"wrong":wrong}
y_class_acc[y_class].update(new_key_value)
new_key_value = {"accuracy":right/(right+wrong)}
y_class_acc[y_class].update(new_key_value)
all_each_y_class_acc.append(y_class_acc)
# Construct the dict containing y classes occurrences
y_class_occ = {}
for class_ in y_class_acc:
occ = y_class_acc[class_]["right"] + y_class_acc[class_]["wrong"]
new_key_value = {class_:occ}
y_class_occ.update(new_key_value)
all_each_y_class_occ.append(y_class_occ)
# Compute current dataset mean y classes occurrences and add it to all_dataset_y_class_mean_occ.
mean_occ = mean(y_class_occ.values())
all_dataset_y_class_mean_occ.append(mean_occ)
# Compute current dataset mean y classes accuracy and add it to all_dataset_y_class_mean_acc.
mean_acc = 0
len_y_class_acc = len(y_class_acc)
for class_ in y_class_acc:
mean_acc += y_class_acc[class_]['accuracy']/len_y_class_acc
all_dataset_y_class_mean_acc.append(mean_acc)
# Construct the dict containing each feature mean accuracy.
features_acc = {}
for feat in features:
mean_acc = 0
class_qty = len(features[feat])
for class_ in features[feat]:
mean_acc += features[feat][class_]["accuracy"]/class_qty
new_key_value = {feat:mean_acc}
features_acc.update(new_key_value)
# Construct the dict containing each feature class quantity.
features_class_qty = {}
for feat in features:
class_qty = len(features[feat])
new_key_value = {feat:class_qty}
features_class_qty.update(new_key_value)
all_each_feature_class_qty.append(features_class_qty)
# Get Accuracy Inter-Features
acc_inter_feat = 0
feat_qty = len(features_acc)
for feat in features_acc:
acc_inter_feat += features_acc[feat]/feat_qty
all_acc_inter_feat.append(acc_inter_feat)
# Get Accuracy Inter-Features Max
acc_inter_feat_max = max(features_acc.values())
all_acc_inter_feat_max.append(acc_inter_feat_max)
# Get Accuracy Inter-Features Min
acc_inter_feat_min = min(features_acc.values())
all_acc_inter_feat_min.append(acc_inter_feat_min)
# Get Accuracy Intra-Features Max
acc_intra_feat_max = 0
for feat in features:
for class_ in features[feat]:
if features[feat][class_]["accuracy"] > acc_intra_feat_max:
acc_intra_feat_max = features[feat][class_]["accuracy"]
all_acc_intra_feat_max.append(acc_intra_feat_max)
# Get Accuracy Intra-Features Min
acc_intra_feat_min = 1
for feat in features:
for class_ in features[feat]:
if features[feat][class_]["accuracy"] < acc_intra_feat_min:
acc_intra_feat_min = features[feat][class_]["accuracy"]
all_acc_intra_feat_min.append(acc_intra_feat_min)
# Get Mean Feature_Class Quantity
mean_feature_class_qty = mean(features_class_qty.values())
all_mean_feature_class_qty.append(mean_feature_class_qty)
# Get Each Feature Accuracy
# => Just use features_acc
all_each_feature_acc.append(features_acc)
# For each combination predictions/predictions.
for i in range(0, len(all_pred)-1):
for j in range(i+1, len(all_pred)):
#--------------------
# Measure gaps.
#--------------------
gaps = []
# Les écarts de scoring prédictifs (accuracy, precision, F1, Recall, Jaccard, Matthews, Hamming et autres);
gap_accuracy = abs(all_eval[i]["accuracy"]-all_eval[j]["accuracy"])
gaps.append(gap_accuracy)
gap_f1_macro = abs(all_eval[i]["f1_macro"]-all_eval[j]["f1_macro"])
gaps.append(gap_f1_macro)
gap_f1_micro = abs(all_eval[i]["f1_micro"]-all_eval[j]["f1_micro"])
gaps.append(gap_f1_micro)
gap_f1_weighted = abs(all_eval[i]["f1_weighted"]-all_eval[j]["f1_weighted"])
gaps.append(gap_f1_weighted)
gap_fbeta_macro = abs(all_eval[i]["fbeta_macro"]-all_eval[j]["fbeta_macro"])
gaps.append(gap_fbeta_macro)
gap_fbeta_micro = abs(all_eval[i]["fbeta_micro"]-all_eval[j]["fbeta_micro"])
gaps.append(gap_fbeta_micro)
gap_fbeta_weighted = abs(all_eval[i]["fbeta_weighted"]-all_eval[j]["fbeta_weighted"])
gaps.append(gap_fbeta_weighted)
gap_ham_loss = abs(all_eval[i]["ham_loss"]-all_eval[j]["ham_loss"])
gaps.append(gap_ham_loss)
gap_jaccard_macro = abs(all_eval[i]["jaccard_macro"]-all_eval[j]["jaccard_macro"])
gaps.append(gap_jaccard_macro)
gap_jaccard_micro = abs(all_eval[i]["jaccard_micro"]-all_eval[j]["jaccard_micro"])
gaps.append(gap_jaccard_micro)
gap_jaccard_weighted = abs(all_eval[i]["jaccard_weighted"]-all_eval[j]["jaccard_weighted"])
gaps.append(gap_jaccard_weighted)
gap_matthews_cc = abs(all_eval[i]["matthews_cc"]-all_eval[j]["matthews_cc"])