-
Notifications
You must be signed in to change notification settings - Fork 1
/
PyEDCR.py
1320 lines (1115 loc) · 72.1 KB
/
PyEDCR.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
from __future__ import annotations
import typing
import numpy as np
import warnings
import multiprocessing as mp
from tqdm.contrib.concurrent import thread_map, process_map
warnings.filterwarnings('ignore')
import utils
import data_preprocessing
import neural_metrics
import symbolic_metrics
import condition
import rule
import label
# import google_sheets_api
import granularity
class EDCR:
"""
Performs error detection and correction based on model predictions.
This class aims to identify and rectify errors in predictions made by a
specified neural network model. It utilizes prediction data from both
fine-grained and coarse-grained model runs to enhance its accuracy.
Attributes:
main_model_name (str): Name of the primary model used for predictions.
combined (bool): Whether combined features (coarse and fine) were used during training.
loss (str): Loss function used during training.
lr: Learning rate used during training.
epsilon: Value using for constraint in getting rules
"""
def __init__(self,
data_str: str,
main_model_name: str = None,
loss: str = None,
lr: typing.Union[str, float] = None,
combined: bool = None,
original_num_epochs: int = None,
epsilon: typing.Union[str, float] = None,
sheet_index: int = None,
K_train: typing.List[(int, int)] = None,
K_test: typing.List[(int, int)] = None,
include_inconsistency_constraint: bool = False,
secondary_model_name: str = None,
secondary_model_loss: str = None,
secondary_num_epochs: int = None,
secondary_lr: float = None,
lower_predictions_indices: typing.List[int] = [],
binary_l_strs: typing.List[str] = [],
binary_model_name: str = None,
binary_num_epochs: int = None,
binary_lr: typing.Union[str, float] = None,
num_train_images_per_class: int = None,
maximize_ratio: bool = True,
indices_of_fine_labels_to_take_out: typing.List[int] = [],
use_google_api: bool = True,
negated_conditions: bool = False):
self.data_str = data_str
self.preprocessor = data_preprocessing.FineCoarseDataPreprocessor(data_str=data_str)
self.main_model_name = main_model_name
self.combined = combined
self.loss = loss
self.lr = lr
self.original_num_epochs = original_num_epochs
self.epsilon = epsilon
self.sheet_index = 2 if self.epsilon is not None else (sheet_index + 3 if sheet_index is not None else None)
self.secondary_model_name = secondary_model_name
self.secondary_model_loss = secondary_model_loss
self.secondary_num_epochs = secondary_num_epochs
self.secondary_lr = secondary_lr if secondary_lr is not None else lr
self.lower_predictions_indices = lower_predictions_indices
self.binary_l_strs = binary_l_strs
self.binary_model_name = binary_model_name
self.binary_num_epochs = binary_num_epochs
self.binary_lr = binary_lr
self.num_train_images_per_class = num_train_images_per_class
self.maximize_ratio = maximize_ratio
self.indices_of_fine_labels_to_take_out = indices_of_fine_labels_to_take_out
self.indices_of_coarse_labels_to_take_out = []
self.negated_conditions = negated_conditions
# predictions data
self.pred_paths: typing.Dict[str, dict] = {
'test' if test else 'train': {g_str: data_preprocessing.get_filepath(data_str=data_str,
model_name=main_model_name,
combined=combined,
test=test,
granularity=g_str,
loss=loss,
lr=lr,
pred=True,
epoch=original_num_epochs)
for g_str in data_preprocessing.FineCoarseDataPreprocessor.granularities_str}
for test in [True, False]}
if isinstance(K_train, typing.List):
self.K_train = data_preprocessing.expand_ranges(K_train)
elif isinstance(K_train, np.ndarray):
self.K_train = K_train
else:
self.K_train = (
data_preprocessing.expand_ranges([(0, np.load(self.pred_paths['train']['fine']).shape[0] - 1)]))
if isinstance(K_test, typing.List):
self.K_test = data_preprocessing.expand_ranges(K_test)
elif isinstance(K_test, np.ndarray):
self.K_test = K_test
else:
self.K_test = data_preprocessing.expand_ranges([(0, np.load(self.pred_paths['test']['fine']).shape[0] - 1)])
self.T_train = np.load(self.pred_paths['train']['fine']).shape[0]
self.T_test = np.load(self.pred_paths['test']['fine']).shape[0]
print(f'Number of total train examples: {self.T_train}\n'
f'Number of total test examples: {self.T_test}')
self.pred_data = \
{test_or_train: {'original': {g: np.load(self.pred_paths[test_or_train][g.g_str])[
self.K_test if test_or_train == 'test' else self.K_train]
for g in
data_preprocessing.FineCoarseDataPreprocessor.granularities.values()},
'noisy': {g: np.load(self.pred_paths[test_or_train][g.g_str])[
self.K_test if test_or_train == 'test' else self.K_train]
for g in data_preprocessing.FineCoarseDataPreprocessor.granularities.values()},
'post_detection': {g: np.load(self.pred_paths[test_or_train][g.g_str])[
self.K_test if test_or_train == 'test' else self.K_train]
for g in
data_preprocessing.FineCoarseDataPreprocessor.granularities.values()},
'post_correction': {
g: np.load(self.pred_paths[test_or_train][g.g_str])[
self.K_test if test_or_train == 'test' else self.K_train]
for g in data_preprocessing.FineCoarseDataPreprocessor.granularities.values()}}
for test_or_train in ['test', 'train']}
self.noise_ratio = sum(self.preprocessor.get_num_of_train_fine_examples(fine_l_index=l_index)
for l_index in self.indices_of_fine_labels_to_take_out) / self.T_train
self.set_coarse_labels_to_take_out()
self.replace_labels_with_noise()
# conditions data
self.condition_datas = {}
# if self.maximize_ratio:
self.set_pred_conditions()
self.set_binary_conditions()
# else:
# if len(self.binary_l_strs) > 0:
# self.set_binary_conditions()
# else:
# self.set_pred_conditions()
self.set_secondary_conditions()
self.set_lower_prediction_conditions()
if include_inconsistency_constraint:
for g in data_preprocessing.FineCoarseDataPreprocessor.granularities.values():
self.condition_datas[g] = self.condition_datas[g].union(
{condition.InconsistencyCondition(preprocessor=self.preprocessor)})
self.all_conditions = sorted(set().union(*[
self.condition_datas[g] for g in data_preprocessing.FineCoarseDataPreprocessor.granularities.values()])
, key=lambda cond: str(cond))
self.CC_all = {g: set() for g in data_preprocessing.FineCoarseDataPreprocessor.granularities.values()}
self.num_predicted_l = {'original': {g: {}
for g in
data_preprocessing.FineCoarseDataPreprocessor.granularities.values()},
'post_detection': {g: {}
for g in
data_preprocessing.FineCoarseDataPreprocessor.granularities.values()},
'post_correction':
{g: {} for g in
data_preprocessing.FineCoarseDataPreprocessor.granularities.values()}}
for g in data_preprocessing.FineCoarseDataPreprocessor.granularities.values():
for l in self.preprocessor.get_labels(g).values():
self.num_predicted_l['original'][g][l] = np.sum(self.get_where_label_is_l(pred=True,
test=True,
l=l,
stage='original'))
# actual_test_examples_with_errors = set()
# for g in data_preprocessing.DataPreprocessor.granularities.values():
# actual_test_examples_with_errors = actual_test_examples_with_errors.union(set(
# np.where(self.get_where_predicted_incorrect(test=True, g=g) == 1)[0]))
#
# self.actual_examples_with_errors = np.array(list(actual_test_examples_with_errors))
self.error_detection_rules: typing.Dict[label.Label, rule.ErrorDetectionRule] = {}
self.error_correction_rules: typing.Dict[label.Label, rule.ErrorCorrectionRule] = {}
self.predicted_test_errors = np.zeros_like(self.pred_data['test']['original'][
self.preprocessor.granularities['fine']])
self.test_error_ground_truths = np.zeros_like(self.predicted_test_errors)
self.inconsistency_error_ground_truths = np.zeros_like(self.predicted_test_errors)
self.correction_model = None
self.original_test_inconsistencies = (
self.preprocessor.get_num_inconsistencies(
fine_labels=self.get_predictions(test=True,
g=data_preprocessing.FineCoarseDataPreprocessor.granularities['fine']),
coarse_labels=self.get_predictions(test=True,
g=data_preprocessing.FineCoarseDataPreprocessor.granularities[
'coarse'])))
print(f'Number of fine classes: {self.preprocessor.num_fine_grain_classes}')
print(f'Number of coarse classes: {self.preprocessor.num_coarse_grain_classes}')
print(utils.blue_text(
f"Number of fine conditions: "
f"{len(self.condition_datas[data_preprocessing.FineCoarseDataPreprocessor.granularities['fine']])}\n"
f"Number of coarse conditions: "
f"{len(self.condition_datas[data_preprocessing.FineCoarseDataPreprocessor.granularities['coarse']])}\n"))
# if use_google_api:
# self.sheet_tab_name = google_sheets_api.get_sheet_tab_name(main_model_name=main_model_name,
# data_str=data_str,
# secondary_model_name=secondary_model_name,
# binary=len(binary_l_strs) > 0)
# print(f'\nsheet_tab_name: {self.sheet_tab_name}\n')
self.recovered_constraints_recall = 0
self.recovered_constraints_precision = 0
self.all_possible_consistency_constraints = self.get_num_all_possible_constraint_can_recover_in_train()
def set_pred_conditions(self):
for g in data_preprocessing.FineCoarseDataPreprocessor.granularities.values():
fine = g.g_str == 'fine'
self.condition_datas[g] = set()
for l in self.preprocessor.get_labels(g).values():
if not ((fine and l.index in self.indices_of_fine_labels_to_take_out)
or (not fine and l.index in self.indices_of_coarse_labels_to_take_out)):
conditions_to_add = {condition.PredCondition(l=l)}
if self.negated_conditions:
conditions_to_add = conditions_to_add.union({condition.PredCondition(l=l, negated=True)})
self.condition_datas[g] = self.condition_datas[g].union(conditions_to_add)
def set_secondary_conditions(self):
if self.secondary_model_name is not None:
self.pred_paths['secondary_model'] = {
'test' if test else 'train': {g_str: data_preprocessing.get_filepath(data_str=self.data_str,
model_name=
self.secondary_model_name,
combined=self.combined,
test=test,
granularity=g_str,
loss=self.secondary_model_loss,
lr=self.secondary_lr,
pred=True,
epoch=self.secondary_num_epochs)
for g_str in
data_preprocessing.FineCoarseDataPreprocessor.granularities_str}
for test in [True, False]}
self.pred_data['secondary_model'] = \
{test_or_train: {g: np.load(self.pred_paths['secondary_model'][test_or_train][g.g_str])
for g in data_preprocessing.FineCoarseDataPreprocessor.granularities.values()}
for test_or_train in ['test', 'train']}
for g in data_preprocessing.FineCoarseDataPreprocessor.granularities.values():
fine = g.g_str == 'fine'
for l in self.preprocessor.get_labels(g).values():
if not ((fine and l.index in self.indices_of_fine_labels_to_take_out)
or (not fine and l.index in self.indices_of_coarse_labels_to_take_out)):
conditions_to_add = {condition.PredCondition(l=l,
secondary_model_name=self.secondary_model_name)}
if self.negated_conditions:
conditions_to_add = (
conditions_to_add.union({
condition.PredCondition(l=l,
secondary_model_name=self.secondary_model_name,
negated=True)}))
self.condition_datas[g] = self.condition_datas[g].union(conditions_to_add)
def set_lower_prediction_conditions(self):
for lower_prediction_index in self.lower_predictions_indices:
lower_prediction_key = f'lower_{lower_prediction_index}'
self.pred_paths[lower_prediction_key] = {
'test' if test else 'train':
{g_str: data_preprocessing.get_filepath(data_str=self.data_str,
model_name=self.main_model_name,
combined=self.combined,
test=test,
granularity=g_str,
loss=self.loss,
lr=self.lr,
pred=True,
epoch=self.original_num_epochs,
lower_prediction_index=lower_prediction_index)
for g_str in data_preprocessing.FineCoarseDataPreprocessor.granularities_str}
for test in [True, False]}
self.pred_data[lower_prediction_key] = \
{test_or_train: {g: np.load(self.pred_paths[lower_prediction_key][test_or_train][g.g_str])
for g in data_preprocessing.FineCoarseDataPreprocessor.granularities.values()}
for test_or_train in ['test', 'train']}
for g in data_preprocessing.FineCoarseDataPreprocessor.granularities.values():
self.condition_datas[g] = self.condition_datas[g].union(
{condition.PredCondition(l=l, lower_prediction_index=lower_prediction_index)
for l in self.preprocessor.get_labels(g).values()})
def set_binary_conditions(self):
self.pred_data['binary'] = {}
for l_str in self.binary_l_strs:
l = {**self.preprocessor.fine_grain_labels, **self.preprocessor.coarse_grain_labels}[l_str]
self.pred_paths[l] = {
'test' if test else 'train': data_preprocessing.get_filepath(data_str=self.data_str,
model_name=self.binary_model_name,
l=l,
test=test,
loss=self.loss,
lr=self.binary_lr,
pred=True,
epoch=self.binary_num_epochs)
for test in [True, False]}
self.pred_data['binary'][l] = \
{test_or_train: np.load(self.pred_paths[l][test_or_train])
for test_or_train in ['test', 'train']}
binary_conditions = {condition.PredCondition(l=l, binary=True)}
if self.negated_conditions:
binary_conditions = binary_conditions.union({condition.PredCondition(l=l, binary=True, negated=False)})
for g in self.preprocessor.granularities.values():
if g in self.condition_datas:
self.condition_datas[g] = self.condition_datas[g].union(binary_conditions)
else:
self.condition_datas[g] = {binary_conditions}
def set_coarse_labels_to_take_out(self):
g_coarse = self.preprocessor.granularities['coarse']
for coarse_label in self.preprocessor.get_labels(g_coarse).values():
fine_labels_of_curr_coarse_label = set(self.preprocessor.coarse_to_fine[coarse_label.l_str])
if fine_labels_of_curr_coarse_label.issubset(set(self.indices_of_fine_labels_to_take_out)):
self.indices_of_coarse_labels_to_take_out += [coarse_label.index]
def replace_labels_with_noise(self):
for g_str in ['fine', 'coarse']:
g = self.preprocessor.granularities['fine']
indices_of_labels_to_take_out = self.indices_of_fine_labels_to_take_out if g_str == 'fine' \
else self.indices_of_coarse_labels_to_take_out
if len(indices_of_labels_to_take_out):
all_labels_indices = set(range(len(self.preprocessor.get_labels(g))))
indices_of_labels_to_keep = list(all_labels_indices.difference(set(indices_of_labels_to_take_out)))
max_value = len(indices_of_labels_to_keep)
classes_str = self.preprocessor.fine_grain_classes_str if g_str == 'fine' \
else self.preprocessor.coarse_grain_classes_str
i = 0
for label_to_take_out_index in indices_of_labels_to_take_out:
next_true_label = indices_of_labels_to_keep[i % max_value]
train_true_indices_where_label_to_take_out = (
np.where(self.preprocessor.get_ground_truths(test=False, g=g) == label_to_take_out_index))[0]
if g_str == 'fine':
self.preprocessor.train_true_fine_data[train_true_indices_where_label_to_take_out] \
= next_true_label
else:
self.preprocessor.train_true_coarse_data[train_true_indices_where_label_to_take_out] \
= next_true_label
# indices_in_train_pred_where_label_to_take_out = (
# np.where(self.get_predictions(test=False, g=g) == label_to_take_out_index))[0]
# self.pred_data['train']['noisy'][g_str][indices_in_train_pred_where_label_to_take_out] \
# = next_pred_label
# indices_in_test_pred_where_label_to_take_out = (
# np.where(self.get_predictions(test=True, g=g) == label_to_take_out_index))[0]
# self.pred_data['test']['noisy'][g_str][indices_in_test_pred_where_label_to_take_out] \
# = next_pred_label
label_str = classes_str[label_to_take_out_index]
assert self.preprocessor.get_labels(g)[label_str].index == label_to_take_out_index
if label_str in self.binary_l_strs:
self.binary_l_strs.remove(label_str)
i += 1
assert all(len(np.where(self.preprocessor.get_ground_truths(test=False, g=g) ==
label_to_take_out_index)[0]) == 0
and classes_str[label_to_take_out_index] not in self.binary_l_strs
for label_to_take_out_index in indices_of_labels_to_take_out)
print(f'Removed classes {indices_of_labels_to_take_out} from {g_str} grain')
def set_error_detection_rules(self,
input_rules: typing.Dict[label.Label, {condition.Condition}]):
"""
Manually sets the error detection rule dictionary.
:params rules: A dictionary mapping label instances to error detection rule objects.
"""
error_detection_rules = {}
for label, DC_l in input_rules.items():
error_detection_rules[label] = rule.ErrorDetectionRule(l=label,
DC_l=DC_l,
preprocessor=self.preprocessor)
self.error_detection_rules = error_detection_rules
@staticmethod
def get_C_str(CC: set[condition.Condition]) -> str:
return '{' + ', '.join(str(obj) for obj in CC) + '}'
def get_predictions(self,
test: bool,
g: granularity.Granularity = None,
stage: str = 'original',
secondary: bool = False,
lower_predictions: bool = False,
binary: bool = False) -> typing.Union[np.array, tuple[np.array]]:
"""Retrieves prediction data based on specified test/train mode.
:param binary:
:param lower_predictions:
:param secondary:
:param stage:
:param g: The granularity level
:param test: whether to get data from train or test set
:return: Fine-grained and coarse-grained prediction data.
"""
test_str = 'test' if test else 'train'
if secondary:
pred_data = self.pred_data['secondary_model'][test_str]
elif lower_predictions:
pred_data = {g: {f'lower_{lower_prediction_index}': self.pred_data[
f'lower_{lower_prediction_index}'][test_str][g]
for lower_prediction_index in self.lower_predictions_indices}
for g in data_preprocessing.FineCoarseDataPreprocessor.granularities.values()}
elif binary:
pred_data = {l: self.pred_data['binary'][l][test_str] for l in self.pred_data['binary']} \
if 'binary' in self.pred_data else None
else:
pred_data = self.pred_data[test_str][stage]
pred_data: dict
if g is not None:
return pred_data[g]
elif binary:
return pred_data
pred_fine_data, pred_coarse_data = [pred_data[g]
for g in
data_preprocessing.FineCoarseDataPreprocessor.granularities.values()]
return pred_fine_data, pred_coarse_data
def get_where_label_is_l(self,
pred: bool,
test: bool,
l: label.Label,
stage: str = 'original',
secondary: bool = False) -> np.array:
""" Retrieves indices of instances where the specified label is present.
:param secondary:
:param stage:
:param pred: True for prediction, False for ground truth
:param test: whether to get data from train or test set
:param l: The label to search for.
:return: A boolean array indicating which instances have the given label.
"""
data = self.get_predictions(test=test, g=l.g, stage=stage, secondary=secondary) if pred \
else self.preprocessor.get_ground_truths(test=test, K=self.K_test if test else self.K_train, g=l.g)
ret = np.where(data == l.index, 1, 0)
return ret
@staticmethod
def get_where_label_is_l_in_data(l: label.Label,
test_pred_fine_data: np.array,
test_pred_coarse_data: np.array) -> np.array:
""" Retrieves indices of instances where the specified label is present.
:param test_pred_coarse_data:
:param test_pred_fine_data:
:param l: The label to search for.
:return: A boolean array indicating which instances have the given label.
"""
data = test_pred_fine_data if l.g == data_preprocessing.FineCoarseDataPreprocessor.granularities['fine'] \
else test_pred_coarse_data
where_label_is_l = np.where(data == l.index, 1, 0)
return where_label_is_l
def print_metrics(self,
split: str,
prior: bool = True,
print_inconsistencies: bool = True,
stage: str = 'original',
print_actual_errors_num: bool = False):
"""Prints performance metrics for given test/train data.
Calculates and prints various metrics (accuracy, precision, recall, etc.)
using appropriate true labels and prediction data based on the specified mode.
:param split:
:param print_actual_errors_num:
:param stage:
:param print_inconsistencies: whether to print the inconsistencies metric or not
:param prior:
"""
original_pred_fine_data, original_pred_coarse_data = None, None
test = split == 'test'
# if stage != 'original':
# original_pred_fine_data, original_pred_coarse_data = self.get_predictions(test=test, stage='original')
pred_fine_data, pred_coarse_data = self.get_predictions(test=test, stage=stage)
true_fine_data, true_coarse_data = self.preprocessor.get_ground_truths(test=test,
K=self.K_test if test else self.K_train)
neural_metrics.get_and_print_metrics(preprocessor=self.preprocessor,
pred_fine_data=pred_fine_data,
pred_coarse_data=pred_coarse_data,
loss=self.loss,
true_fine_data=true_fine_data,
true_coarse_data=true_coarse_data,
split=split,
prior=prior,
combined=self.combined,
model_name=self.main_model_name,
lr=self.lr,
print_inconsistencies=print_inconsistencies,
current_num_test_inconsistencies=
self.get_constraints_true_positives_and_total_positives()[0],
original_test_inconsistencies=self.original_test_inconsistencies,
original_pred_fine_data=original_pred_fine_data,
original_pred_coarse_data=original_pred_coarse_data)
# Calculate boolean masks for each condition
# correct_coarse_incorrect_fine = np.logical_and(pred_coarse_data == true_coarse_data,
# pred_fine_data != true_fine_data)
# incorrect_coarse_correct_fine = np.logical_and(pred_coarse_data != true_coarse_data,
# pred_fine_data == true_fine_data)
# incorrect_both = np.logical_and(pred_coarse_data != true_coarse_data, pred_fine_data != true_fine_data)
# correct_both = np.logical_and(pred_coarse_data == true_coarse_data,
# pred_fine_data == true_fine_data) # for completeness
#
# # Calculate total number of examples
# total_examples = len(pred_coarse_data) # Assuming shapes are compatible
# fractions = {
# 'correct_coarse_incorrect_fine': np.sum(correct_coarse_incorrect_fine) / total_examples,
# 'incorrect_coarse_correct_fine': np.sum(incorrect_coarse_correct_fine) / total_examples,
# 'incorrect_both': np.sum(incorrect_both) / total_examples,
# 'correct_both': np.sum(correct_both) / total_examples
# }
#
# print(f"fraction of error associate with each type: \n",
# f"correct_coarse_incorrect_fine: {round(fractions['correct_coarse_incorrect_fine'], 2)} \n",
# f"incorrect_coarse_correct_fine: {round(fractions['incorrect_coarse_correct_fine'], 2)} \n",
# f"incorrect_both: {round(fractions['incorrect_both'], 2)} \n",
# f"correct_both: {round(fractions['correct_both'], 2)} \n")
# if print_actual_errors_num:
# print(utils.red_text(f'\nNumber of actual errors on test: {len(self.actual_examples_with_errors)} / '
# f'{self.T_test}\n'))
def get_where_predicted_correct(self,
test: bool,
g: granularity.Granularity,
stage: str = 'original') -> np.array:
"""Calculates true positive mask for given granularity and label.
:param stage:
:param test: whether to get data from train or test set
:param g: The granularity level.
:return: A mask with 1s for true positive instances, 0s otherwise.
"""
ground_truth = self.preprocessor.get_ground_truths(test=test, K=self.K_test if test else self.K_train, g=g)
g_predictions = self.get_predictions(test=test, g=g, stage=stage)
where_predicted_correct = np.where(g_predictions == ground_truth, 1, 0)
return where_predicted_correct
def get_where_predicted_correct_in_data(self,
g: granularity.Granularity,
test_pred_fine_data: np.array,
test_pred_coarse_data: np.array) -> np.array:
"""Calculates true positive mask for given granularity and label.
:param test_pred_fine_data:
:param test_pred_coarse_data:
:param g: The granularity level.
:return: A mask with 1s for true positive instances, 0s otherwise.
"""
ground_truth = self.preprocessor.get_ground_truths(test=True, K=self.K_test, g=g)
prediction = test_pred_fine_data if g == data_preprocessing.FineCoarseDataPreprocessor.granularities['fine'] \
else test_pred_coarse_data
return np.where(prediction == ground_truth, 1, 0)
def get_where_predicted_incorrect(self,
test: bool,
g: granularity.Granularity,
stage: str = 'original') -> np.array:
"""Calculates false positive mask for given granularity and label.
:param stage:
:param test: whether to get data from train or test set
:param g: The granularity level
:return: A mask with 1s for false positive instances, 0s otherwise.
"""
return 1 - self.get_where_predicted_correct(test=test, g=g, stage=stage)
def get_where_predicted_inconsistently(self,
test: bool,
stage: str = 'original'
):
predicted_derived_coarse = np.array([self.preprocessor.fine_to_course_idx[i]
for i in self.get_predictions(test=test,
g=self.preprocessor.granularities['fine'],
stage=stage)])
predicted_coarse = self.get_predictions(test=test,
g=self.preprocessor.granularities['coarse'],
stage=stage)
return np.where(predicted_derived_coarse != predicted_coarse, 1, 0)
def get_where_predicted_incorrect_in_data(self,
g: granularity.Granularity,
test_pred_fine_data: np.array,
test_pred_coarse_data: np.array) -> np.array:
"""Calculates false positive mask for given granularity and label.
:param test_pred_coarse_data:
:param test_pred_fine_data:
:param g: The granularity level
:return: A mask with 1s for false positive instances, 0s otherwise.
"""
return 1 - self.get_where_predicted_correct_in_data(g=g,
test_pred_fine_data=test_pred_fine_data,
test_pred_coarse_data=test_pred_coarse_data)
def get_where_tp_l(self,
test: bool,
l: label.Label,
stage: str = 'original', ) -> np.array:
""" Retrieves indices of training instances where the true label is l and the model correctly predicted l.
:param stage:
:param test: whether to get data from train or test set
:param l: The label to query.
:return: A boolean array indicating which training instances satisfy the criteria.
"""
return (self.get_where_label_is_l(pred=True, test=test, l=l, stage=stage) *
self.get_where_predicted_correct(test=test, g=l.g, stage=stage))
def get_where_tp_l_in_data(self,
l: label.Label,
test_pred_fine_data: np.array,
test_pred_coarse_data: np.array) -> np.array:
""" Retrieves indices of training instances where the true label is l and the model correctly predicted l.
:param test_pred_coarse_data:
:param test_pred_fine_data:
:param l: The label to query.
:return: A boolean array indicating which training instances satisfy the criteria.
"""
return (self.get_where_label_is_l_in_data(l=l,
test_pred_fine_data=test_pred_fine_data,
test_pred_coarse_data=test_pred_coarse_data) *
self.get_where_predicted_correct_in_data(g=l.g,
test_pred_fine_data=test_pred_fine_data,
test_pred_coarse_data=test_pred_coarse_data))
def get_where_fp_l(self,
test: bool,
l: label.Label,
stage: str = 'original') -> np.array:
""" Retrieves indices of instances where the predicted label is l and the ground truth is not l.
:param stage:
:param test: whether to get data from train or test set
:param l: The label to query.
:return: A boolean array indicating which instances satisfy the criteria.
"""
return (self.get_where_label_is_l(pred=True, test=test, l=l, stage=stage) *
self.get_where_predicted_incorrect(test=test, g=l.g, stage=stage))
def get_where_fp_l_in_data(self,
l: label.Label,
test_pred_fine_data: np.array,
test_pred_coarse_data: np.array) -> np.array:
""" Retrieves indices of instances where the predicted label is l and the ground truth is not l.
:param test_pred_coarse_data:
:param test_pred_fine_data:
:param l: The label to query.
:return: A boolean array indicating which instances satisfy the criteria.
"""
return (self.get_where_label_is_l_in_data(l=l,
test_pred_fine_data=test_pred_fine_data,
test_pred_coarse_data=test_pred_coarse_data) *
self.get_where_predicted_incorrect_in_data(g=l.g,
test_pred_fine_data=test_pred_fine_data,
test_pred_coarse_data=test_pred_coarse_data))
def get_l_precision_and_recall(self,
test: bool,
l: label.Label,
stage: str = 'original'):
t_p_l = np.sum(self.get_where_tp_l(test=test, l=l, stage=stage))
f_p_l = np.sum(self.get_where_fp_l(test=test, l=l, stage=stage))
N_l_gt = np.sum(self.get_where_label_is_l(test=test, pred=False, l=l, stage=stage))
p_l = t_p_l / (t_p_l + f_p_l) if not (t_p_l == 0 and f_p_l == 0) else 0
r_l = t_p_l / N_l_gt if not N_l_gt == 0 else 0
return p_l, r_l
def get_g_precision_and_recall(self,
test: bool,
g: granularity.Granularity,
stage: str = 'original',
test_pred_fine_data: np.array = None,
test_pred_coarse_data: np.array = None) -> (
typing.Dict[label.Label, float],
typing.Dict[label.Label, float]):
p_g = {}
r_g = {}
if test_pred_fine_data is None and test_pred_coarse_data is None:
for l in self.preprocessor.get_labels(g).values():
p_g[l], r_g[l] = self.get_l_precision_and_recall(test=test, l=l, stage=stage)
else:
for l in self.preprocessor.get_labels(g).values():
t_p_l = np.sum(self.get_where_tp_l_in_data(l=l,
test_pred_fine_data=test_pred_fine_data,
test_pred_coarse_data=test_pred_coarse_data))
f_p_l = np.sum(self.get_where_fp_l_in_data(l=l,
test_pred_fine_data=test_pred_fine_data,
test_pred_coarse_data=test_pred_coarse_data))
N_l_gt = np.sum(self.get_where_label_is_l_in_data(l=l,
test_pred_fine_data=test_pred_fine_data,
test_pred_coarse_data=test_pred_coarse_data))
p_g[l] = t_p_l / (t_p_l + f_p_l)
r_g[l] = t_p_l / N_l_gt
return p_g, r_g
def get_NEG_l_C(self,
l: label.Label,
C: set[condition.Condition],
stage: str = 'original') -> int:
"""Calculate the number of train samples that satisfy any of the conditions and are true positive.
:param stage:
:param C: A set of `Condition` objects.
:param l: The label of interest.
:return: The number of instances that is true negative and satisfying all condition.
"""
train_pred_fine_data, train_pred_coarse_data = self.get_predictions(test=False, stage=stage)
secondary_train_pred_fine_data, secondary_train_pred_coarse_data = (
self.get_predictions(test=False, secondary=True)) if self.secondary_model_name is not None else \
(None, None)
lower_train_pred_fine_data, lower_train_pred_coarse_data = (
self.get_predictions(test=False, lower_predictions=True)) \
if len(self.lower_predictions_indices) else (None, None)
binary_data = self.get_predictions(test=False, binary=True) if len(self.binary_l_strs) else None
where_any_conditions_satisfied_on_train = (
rule.Rule.get_where_any_conditions_satisfied(C=C,
fine_data=train_pred_fine_data,
coarse_data=train_pred_coarse_data,
secondary_fine_data=secondary_train_pred_fine_data,
secondary_coarse_data=secondary_train_pred_coarse_data,
lower_predictions_fine_data=lower_train_pred_fine_data,
lower_predictions_coarse_data=lower_train_pred_coarse_data,
binary_data=binary_data))
where_train_tp_l = self.get_where_tp_l(test=False, l=l, stage=stage)
NEG_l = np.sum(where_train_tp_l * where_any_conditions_satisfied_on_train)
return NEG_l
def get_BOD_l_C(self,
l: label.Label,
C: set[condition.Condition]) -> int:
"""Calculate the number of train samples that satisfy any conditions for some set of conditions and
are positives
:param l:
:param C: A set of `Condition` objects.
:return: The number of instances that are false negative and satisfying some condition.
"""
where_predicted_l = self.get_where_label_is_l(pred=True, test=False, l=l)
train_pred_fine_data, train_pred_coarse_data = self.get_predictions(test=False)
secondary_train_pred_fine_data, secondary_train_pred_coarse_data = (
self.get_predictions(test=False, secondary=True)) if self.secondary_model_name is not None else (None, None)
lower_train_pred_fine_data, lower_train_pred_coarse_data = (
self.get_predictions(test=False, lower_predictions=True)) \
if len(self.lower_predictions_indices) else (None, None)
binary_data = self.get_predictions(test=False, binary=True) if len(self.binary_l_strs) else None
where_any_conditions_satisfied_on_train = (
rule.Rule.get_where_any_conditions_satisfied(C=C,
fine_data=train_pred_fine_data,
coarse_data=train_pred_coarse_data,
secondary_fine_data=secondary_train_pred_fine_data,
secondary_coarse_data=secondary_train_pred_coarse_data,
lower_predictions_fine_data=lower_train_pred_fine_data,
lower_predictions_coarse_data=lower_train_pred_coarse_data,
binary_data=binary_data
))
BOD_l = np.sum(where_any_conditions_satisfied_on_train * where_predicted_l)
return BOD_l
def get_POS_l_C(self,
l: label.Label,
C: set[condition.Condition],
stage: str = 'original') -> int:
"""Calculate the number of train samples that satisfy any conditions for some set of conditions
and are false positive.
:param stage:
:param C: A set of `Condition` objects.
:param l: The label of interest.
:return: The number of instances that are false negative and satisfying some condition.
"""
where_fp_l = self.get_where_fp_l(test=False, l=l, stage=stage)
train_pred_fine_data, train_pred_coarse_data = self.get_predictions(test=False, stage=stage)
secondary_train_pred_fine_data, secondary_train_pred_coarse_data = (
self.get_predictions(test=False, secondary=True)) if self.secondary_model_name is not None else (None, None)
lower_train_pred_fine_data, lower_train_pred_coarse_data = (
self.get_predictions(test=False, lower_predictions=True)) \
if len(self.lower_predictions_indices) else (None, None)
binary_data = self.get_predictions(test=False, binary=True) if len(self.binary_l_strs) else None
where_any_conditions_satisfied_on_train = (
rule.Rule.get_where_any_conditions_satisfied(C=C,
fine_data=train_pred_fine_data,
coarse_data=train_pred_coarse_data,
secondary_fine_data=secondary_train_pred_fine_data,
secondary_coarse_data=secondary_train_pred_coarse_data,
lower_predictions_fine_data=lower_train_pred_fine_data,
lower_predictions_coarse_data=lower_train_pred_coarse_data,
binary_data=binary_data))
POS_l = np.sum(where_fp_l * where_any_conditions_satisfied_on_train)
return POS_l
def DetRuleLearn(self,
l: label.Label) -> set[condition.Condition]:
"""Learns error detection rules for a specific label and granularity. These rules capture conditions
that, when satisfied, indicate a higher likelihood of prediction errors for a given label.
:param l: The label of interest.
:return: A set of `Condition` representing the learned error detection rule.
"""
DC_l = set()
stage = 'original' if self.correction_model is None else 'post_detection'
N_l = np.sum(self.get_where_label_is_l(pred=True, test=False, l=l, stage=stage))
if N_l:
P_l, R_l = self.get_l_precision_and_recall(test=False, l=l, stage=stage)
q_l = self.epsilon * N_l * P_l / R_l
DC_star = [cond for cond in self.all_conditions if self.get_NEG_l_C(l=l,
C={cond},
stage=stage) <= q_l
and not (isinstance(cond, condition.PredCondition) and cond.l == l
and cond.secondary_model_name is None)]
while DC_star:
best_cond = sorted(DC_star,
key=lambda cond: self.get_POS_l_C(l=l, C=DC_l.union({cond}), stage=stage))[-1]
DC_l = DC_l.union({best_cond})
DC_star = sorted([cond for cond in
set(self.all_conditions).difference(DC_l)
if self.get_NEG_l_C(l=l, C=DC_l.union({cond}), stage=stage) <= q_l
and not (isinstance(cond, condition.PredCondition) and cond.l == l
and cond.secondary_model_name is None)
],
key=lambda cond: str(cond))
return DC_l
def get_minimization_denominator(self,
l: label.Label,
C: set[condition.Condition],
stage: str = 'original'):
POS = 2 * self.get_POS_l_C(l=l, C=C, stage=stage)
return POS
@staticmethod
def get_f_margin(f: typing.Callable,
l: label.Label,
DC_l_i: set[condition.Condition],
cond: condition.Condition):
return f(l=l, C=DC_l_i.union({cond})) - f(l=l, C=DC_l_i)
def get_minimization_numerator(self,
l: label.Label,
C: set[condition.Condition]):
return self.get_BOD_l_C(l=l, C=C) + np.sum(self.get_where_fp_l(l=l, test=False))
def get_ratio_of_margins(self,
l: label.Label,
DC_l_i: set[condition.Condition],
cond: condition.Condition,
init_value: float) -> float:
minimization_numerator_margin = self.get_f_margin(f=self.get_minimization_numerator,
l=l,
DC_l_i=DC_l_i,
cond=cond)
minimization_denominator_margin = self.get_f_margin(f=self.get_minimization_denominator,
l=l,
DC_l_i=DC_l_i,
cond=cond)
return (minimization_numerator_margin / minimization_denominator_margin) \
if (minimization_denominator_margin > 0) else init_value
def get_minimization_ratio(self,
l: label.Label,
DC_l_i: set[condition.Condition],
init_value: float) -> float:
minimization_numerator = self.get_minimization_numerator(l=l, C=DC_l_i)
minimization_denominator = self.get_minimization_denominator(l=l, C=DC_l_i)
return (minimization_numerator / minimization_denominator) if (minimization_denominator > 0) else init_value
def RatioDetRuleLearn(self,
l: label.Label) -> set[condition.Condition]:
"""Learns error detection rules for a specific label and granularity. These rules capture conditions
that, when satisfied, indicate a higher likelihood of prediction errors for a given label.
:param l: The label of interest.
:return: A set of `Condition` representing the learned error detection rule.
"""
stage = 'original' if self.correction_model is None else 'post_detection'
N_l = np.sum(self.get_where_label_is_l(pred=True, test=False, l=l, stage=stage))
init_value = float('inf')
DC_ls = {0: set()}
DC_l_scores = {0: init_value}
if N_l:
# print(f'Curvature for {l} is: {self.get_numerator_curvature(l=l)}')
i = 0
# 1. sorting the conditions by their 1/f1 value from least to greatest
DC_star = (
sorted(
[cond for cond in self.all_conditions
if not ((isinstance(cond, condition.PredCondition) and (cond.l == l)
and (cond.secondary_model_name is None)))]
, key=lambda cond: self.get_minimization_ratio(l=l,
DC_l_i={cond},
init_value=init_value)
)
)
while DC_star:
DC_l_i = DC_ls[i]
# print({str(cond): ((self.get_BOD_l_C(l=l, C=DC_l_i.union({cond})) - self.get_BOD_l_C(l=l, C=DC_l_i)) /
# (self.get_POS_l_C(l=l, C=DC_l_i.union({cond}), stage=stage) -
# self.get_POS_l_C(l=l, C=DC_l_i, stage=stage)))
# if ((self.get_POS_l_C(l=l, C=DC_l_i.union({cond}), stage=stage) -
# self.get_POS_l_C(l=l, C=DC_l_i, stage=stage)) > 0)
# else init_value for cond in DC_star})
# 2. minimizing the margin of 1/f1 based on the algorithm
best_cond = sorted(DC_star,
key=lambda cond: self.get_ratio_of_margins(l=l,
DC_l_i=DC_l_i,
cond=cond,
init_value=init_value,
))[0]
DC_l_i_1 = DC_l_i.union({best_cond})
DC_ls[i + 1] = DC_l_i_1
# 3. updating the new set 1/f1 score
DC_l_scores[i + 1] = self.get_minimization_ratio(l=l,
DC_l_i=DC_l_i_1,
init_value=init_value)
# 4. updating the set of conditions based on the algorithm and also again sorting like in step 1
# from least to greatest