-
Notifications
You must be signed in to change notification settings - Fork 31
Expand file tree
/
Copy path_classification.py
More file actions
1138 lines (919 loc) · 33.9 KB
/
Copy path_classification.py
File metadata and controls
1138 lines (919 loc) · 33.9 KB
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
# Base Imports
import warnings
import numpy as np
import pandas as pd
# Efficacy metrics
from sklearn.metrics import accuracy_score, confusion_matrix, roc_auc_score
from sklearn.neighbors import NearestNeighbors
# utils
from holisticai.utils._validation import (
_array_like_to_numpy,
_check_binary,
_classification_checks,
_matrix_like_to_numpy,
_regression_checks,
)
def _group_success_rate(g, y):
"""Group success rate.
This function computes the success rate for a given subgroup.
Parameters
----------
g : array-like
subgroup vector (binary)
y : array-like
predictions vector (binary)
Returns
-------
float
group success rate
"""
return y[g == 1].sum() / g.sum() # success rate group_a
def statistical_parity(group_a, group_b, y_pred):
"""Statistical parity.
This function computes the statistical parity (difference of success rates)\
between group_a and group_b.
Interpretation
--------------
A value of 0 is desired. Negative values are unfair towards group_a.\
Positive values are unfair towards group_b. The range (-0.1,0.1)\
is considered acceptable.
Parameters
----------
group_a : array-like
Group membership vector (binary)
group_b : array-like
Group membership vector (binary)
y_pred : array-like
Predictions vector (binary)
Returns
-------
float
Statistical Parity
Notes
-----
:math:`sr_a - sr_b`
Examples
--------
>>> import numpy as np
>>> from holisticai.bias.metrics import statistical_parity
>>> group_a = np.array([1, 1, 1, 1, 0, 0, 0, 0, 0, 0])
>>> group_b = np.array([0, 0, 0, 0, 1, 1, 1, 1, 1, 1])
>>> y_pred = np.array([1, 1, 1, 0, 1, 1, 0, 0, 0, 0])
>>> statistical_parity(group_a, group_b, y_pred)
0.4166666666666667
"""
# check and coerce
group_a, group_b, y_pred, _ = _classification_checks(group_a, group_b, y_pred, y_true=None)
# calculate sr_a and sr_b
sr_a = _group_success_rate(group_a, y_pred) # success rate group_a
sr_b = _group_success_rate(group_b, y_pred) # success rate group_b
return sr_a - sr_b
def success_rate(group_a, group_b, y_pred):
"""Success Rate
Calculates the raw success rates for each group.
Parameters
----------
group_a : array-like
Group membership vector (binary)
group_b : array-like
Group membership vector (binary)
y_pred : array-like
Predictions vector (binary)
Returns
-------
dict
Dictionary with two keys, sr_a and sr_b (success rate for group a and b)
"""
sr_a = _group_success_rate(group_a, y_pred) # success rate group_a
sr_b = _group_success_rate(group_b, y_pred) # success rate group_b
return {"sr_a": sr_a, "sr_b": sr_b}
def disparate_impact(group_a, group_b, y_pred):
"""Disparate Impact.
This function computes the disparate impact (ratio of success rates)\
between group_a and group_b class.
Interpretation
--------------
A value of 1 is desired. Values below 1 are unfair towards group_a.\
Values above 1 are unfair towards group_b. The range (0.8,1.2)\
is considered acceptable.
Parameters
----------
group_a : array-like
Group membership vector (binary)
group_b : array-like
Group membership vector (binary)
y_pred : array-like
Predictions vector (binary)
Returns
-------
float
Disparate Impact
Notes
-----
:math:`sr_a/sr_b`
References
----------
.. [1] `M B Zafar, I Valera, M G Rodriguez, K P. Gummadi (2017).
Fairness Constraints: Mechanisms for Fair Classification, MPI-SWS
<https://arxiv.org/pdf/1507.05259.pdf>`
Examples
-------
>>> import numpy as np
>>> from holisticai.bias.metrics import disparate_impact
>>> group_a = np.array([1, 1, 1, 1, 0, 0, 0, 0, 0, 0])
>>> group_b = np.array([0, 0, 0, 0, 1, 1, 1, 1, 1, 1])
>>> y_pred = np.array([1, 1, 1, 0, 1, 1, 0, 0, 0, 0])
>>> disparate_impact(group_a, group_b, y_pred)
2.25
"""
# check and coerce
group_a, group_b, y_pred, _ = _classification_checks(group_a, group_b, y_pred, y_true=None)
# calculate sr_a and sr_b
sr_a = _group_success_rate(group_a, y_pred) # success rate group_a
sr_b = _group_success_rate(group_b, y_pred) # success rate group_b
return sr_a / sr_b
def four_fifths(group_a, group_b, y_pred):
"""Four Fifths
This function computes the four fifths rule (ratio of success rates)\
between group_a and group_b. We return the minimum of the ratio taken both ways.
Interpretation
--------------
A value of 1 is desired. Values below 1 are unfair. The range (0.8,1) is considered acceptable.
Parameters
----------
group_a : array-like
Group membership vector (binary)
group_b : array-like
Group membership vector (binary)
y_pred : array-like
Predictions vector (binary)
Returns
-------
float
Four Fifths
Examples
--------
>>> import numpy as np
>>> from holisticai.bias.metrics import four_fifths
>>> group_a = np.array([1, 1, 1, 1, 0, 0, 0, 0, 0, 0])
>>> group_b = np.array([0, 0, 0, 0, 1, 1, 1, 1, 1, 1])
>>> y_pred = np.array([1, 1, 1, 0, 1, 1, 0, 0, 0, 0])
>>> four_fifths(group_a, group_b, y_pred)
0.4444444444444444
"""
# check and coerce
group_a, group_b, y_pred, _ = _classification_checks(group_a, group_b, y_pred, y_true=None)
# calculate sr_a and sr_b
sr_a = _group_success_rate(group_a, y_pred) # success rate group_a
sr_b = _group_success_rate(group_b, y_pred) # success rate group_b
return min(sr_a / sr_b, sr_b / sr_a)
def cohen_d(group_a, group_b, y_pred):
"""Cohen D
This function computes the Cohen D statistic (normalised statistical parity)\
between group_a and group_b.
Interpretation
--------------
A value of 0 is desired. Negative values are unfair towards group_a.
Positive values are unfair towards group_b. Reference values: 0.2 is\
considered a small effect size, 0.5 is considered medium, 0.8 is considered large.
Parameters
----------
group_a : array-like
Group membership vector (binary)
group_b : array-like
Group membership vector (binary)
y_pred : array-like
Predictions vector (binary)
Returns
-------
float
Cohen D :
Notes
-----
:math:`\frac{sr_a-sr_b}{\texttt{std_pool}}`
Examples
--------
>>> import numpy as np
>>> from holisticai.bias.metrics import cohen_d
>>> group_a = np.array([1, 1, 1, 1, 0, 0, 0, 0, 0, 0])
>>> group_b = np.array([0, 0, 0, 0, 1, 1, 1, 1, 1, 1])
>>> y_pred = np.array([1, 1, 0, 0, 1, 1, 0, 1, 1, 1])
>>> cohen_d(group_a, group_b, y_pred)
-0.7844645405527363
"""
# check and coerce
group_a, group_b, y_pred, _ = _classification_checks(group_a, group_b, y_pred, y_true=None)
# calculate sr_a and sr_b
sr_a = _group_success_rate(group_a, y_pred) # success rate group_a
sr_b = _group_success_rate(group_b, y_pred) # success rate group_b
# calculate STD_a and STD_b
std_b = np.sqrt(sr_b * (1 - sr_b))
std_a = np.sqrt(sr_a * (1 - sr_a))
# calculate n_a and n_b
n_a = group_a.sum()
n_b = group_b.sum()
# calculate poolSTD
std_pool = np.sqrt(((n_b - 1) * std_b**2 + (n_a - 1) * std_a**2) / (n_a + n_b - 2))
return (sr_a - sr_b) / std_pool
def z_test_diff(group_a, group_b, y_pred):
"""Z Test (Difference)
This function computes the Z-test statistic for the difference\
in success rates. Also known as 2-SD Statistic.
Interpretation
--------------
A value of 0 is desired. This test considers the data unfair if\
the computed value is greater than 2 or smaller than -2, indicating\
a statistically significant difference in success rates.
Parameters
----------
group_a : array-like
Group membership vector (binary)
group_b : array-like
Group membership vector (binary)
y_pred : array-like
Predictions vector (binary)
Returns
-------
float
Z test (difference version)
Examples
--------
>>> import numpy as np
>>> from holisticai.bias.metrics import z_test_diff
>>> group_a = np.array([1, 1, 1, 1, 0, 0, 0, 0, 0, 0])
>>> group_b = np.array([0, 0, 0, 0, 1, 1, 1, 1, 1, 1])
>>> y_pred = np.array([1, 1, 1, 0, 1, 1, 0, 0, 0, 0])
>>> z_test_diff(group_a, group_b, y_pred)
1.290994449
References
----------
.. [1] `Morris (2001).
Sample size requirements for adverse impact analysis
<https://www.semanticscholar.org/paper/Sample-Size-Required-for-Adverse-Impact-Analysis-Morris/877f7acd7c646a21f4947166a07f41664dcabe95>`
"""
# check and coerce
group_a, group_b, y_pred, _ = _classification_checks(group_a, group_b, y_pred, y_true=None)
# calculate sr_a and sr_b
sr_a = _group_success_rate(group_a, y_pred) # success rate group_a
sr_b = _group_success_rate(group_b, y_pred) # success rate group_b
n_a = group_a.sum()
n_b = group_b.sum()
sr_tot = (sr_a * n_a + sr_b * n_b) / (n_a + n_b)
n_tot = n_a + n_b
# calculate p_a
p_a = n_a / n_tot
return (sr_a - sr_b) / np.sqrt((sr_tot * (1 - sr_tot)) / (n_tot * p_a * (1 - p_a)))
def z_test_ratio(group_a, group_b, y_pred):
"""Z Test (Ratio)
This function computes the Z-test statistic for the ratio\
in success rates. Also known as 2-SD Statistic.
Interpretation
--------------
A value of 0 is desired. This test considers the data unfair if\
the computed value is greater than 2 or smaller than -2, indicating\
a statistically significant ratio in success rates.
Parameters
----------
group_a : array-like
Group membership vector (binary)
group_b : array-like
Group membership vector (binary)
y_pred : array-like
Predictions vector (binary)
Returns
-------
float
Z-test (ratio version)
Examples
--------
>>> import numpy as np
>>> from holisticai.bias.metrics import z_test_ratio
>>> group_a = np.array([1, 1, 1, 1, 0, 0, 0, 0, 0, 0])
>>> group_b = np.array([0, 0, 0, 0, 1, 1, 1, 1, 1, 1])
>>> y_pred = np.array([1, 1, 1, 0, 1, 1, 0, 0, 0, 0])
>>> z_test_ratio(group_a, group_b, y_pred)
1.256287689
References
----------
.. [1] `Morris (2001).
Sample size requirements for adverse impact analysis
<https://www.semanticscholar.org/paper/Sample-Size-Required-for-Adverse-Impact-Analysis-Morris/877f7acd7c646a21f4947166a07f41664dcabe95>`
"""
# check and coerce
group_a, group_b, y_pred, _ = _classification_checks(group_a, group_b, y_pred, y_true=None)
# calculate sr_a and sr_b
sr_a = _group_success_rate(group_a, y_pred) # success rate group_a
sr_b = _group_success_rate(group_b, y_pred) # success rate group_b
n_a = group_a.sum()
n_b = group_b.sum()
sr_tot = (sr_a * n_a + sr_b * n_b) / (n_a + n_b)
n_tot = n_a + n_b
# calculate p_a
p_a = n_a / n_tot
return (np.log(sr_a / sr_b)) / np.sqrt((1 - sr_tot) / (sr_tot * n_tot * p_a * (1 - p_a)))
def _correlation_diff(group_a, group_b, y_pred, y_true):
"""Correlation difference
This function computes the difference in correlation between predicted\
and true labels for group_a and group_b.
Interpretation
--------------
A value of 0 is desired. This metric ranges between -2 and 2, with\
negative values indicating bias against group_a, and positive values indicating bias against group_b.
Parameters
----------
group_a : array-like
Group membership vector (binary)
group_b : array-like
Group membership vector (binary)
y_pred : array-like
Predictions vector (binary)
y_true : array-like
Target vector (binary)
Returns
-------
float
Correlation Difference
Notes
-----
:math:`CV_a - CV_b`
Examples
--------
>>> import numpy as np
>>> from holisticai.bias.metrics import correlation_diff
>>> group_a = np.array([1, 1, 1, 1, 0, 0, 0, 0, 0, 0])
>>> group_b = np.array([0, 0, 0, 0, 1, 1, 1, 1, 1, 1])
>>> y_pred = np.array([1, 1, 0, 0, 1, 1, 0, 1, 1, 1])
>>> y_true = np.array([1, 1, 0, 0, 1, 0, 1, 0, 0, 1])
>>> correlation_diff(group_a, group_b, y_pred, y_true)
1.4472135954999579
"""
# check and coerce
group_a, group_b, y_pred, y_true = _classification_checks(group_a, group_b, y_pred, y_true)
# Calculate Pearson correlations
cv_a = np.corrcoef(y_pred[group_a == 1], y_true[group_a == 1])[1, 0]
cv_b = np.corrcoef(y_pred[group_b == 1], y_true[group_b == 1])[1, 0]
return cv_a - cv_b
def equal_opportunity_diff(group_a, group_b, y_pred, y_true):
"""Equality of opportunity difference
This function computes the difference in true positive\
rates for group_a and group_b.
Interpretation
--------------
A value of 0 is desired. This metric ranges between -1 and 1,\
with negative values indicating bias against group_a, and\
positive values indicating bias against group_b.
Parameters
----------
group_a : array-like
Group membership vector (binary)
group_b : array-like
Group membership vector (binary)
y_pred : array-like
Predictions vector (binary)
y_true : array-like
Target vector (binary)
Returns
-------
float
Equal opportunity difference
Notes
-----
:math:`tpr_a - tpr_b`
Examples
--------
>>> import numpy as np
>>> from holisticai.bias.metrics import equal_opportunity_diff
>>> group_a = np.array([1, 1, 1, 1, 0, 0, 0, 0, 0, 0])
>>> group_b = np.array([0, 0, 0, 0, 1, 1, 1, 1, 1, 1])
>>> y_pred = np.array([1, 1, 0, 0, 1, 1, 0, 1, 1, 1])
>>> y_true = np.array([1, 1, 0, 0, 1, 0, 1, 0, 0, 1])
>>> equal_opportunity_diff(group_a, group_b, y_pred, y_true)
0.33333333333333337
"""
# check and coerce
group_a, group_b, y_pred, y_true = _classification_checks(group_a, group_b, y_pred, y_true)
# Calculate true positive rates
tpr_a = confusion_matrix(y_true[group_a == 1], y_pred[group_a == 1], normalize="true")[1, 1]
tpr_b = confusion_matrix(y_true[group_b == 1], y_pred[group_b == 1], normalize="true")[1, 1]
return tpr_a - tpr_b
def false_positive_rate_diff(group_a, group_b, y_pred, y_true):
"""False positive rate difference
This function computes the difference in false positive\
rates between group_a and group_b.
Interpretation
--------------
A value of 0 is desired. This metric ranges between -1 and 1,\
with negative values indicating bias against group_a, and\
positive values indicating bias against group_b.
Parameters
----------
group_a : array-like
Group membership vector (binary)
group_b : array-like
Group membership vector (binary)
y_pred : array-like
Predictions vector (binary)
y_true : array-like
Target vector (binary)
Returns
-------
float
FPR_diff
Notes
-----
:math:`fpr_a - fpr_b`
Examples
--------
>>> import numpy as np
>>> from holisticai.bias.metrics import false_positive_diff
>>> group_a = np.array([1, 1, 1, 1, 0, 0, 0, 0, 0, 0])
>>> group_b = np.array([0, 0, 0, 0, 1, 1, 1, 1, 1, 1])
>>> y_pred = np.array([1, 1, 0, 0, 1, 1, 0, 1, 1, 1])
>>> y_true = np.array([1, 1, 0, 0, 1, 0, 1, 0, 0, 1])
>>> false_positive_diff(group_a, group_b, y_pred, y_true)
-1.0
"""
# check and coerce
group_a, group_b, y_pred, y_true = _classification_checks(group_a, group_b, y_pred, y_true)
# Calculate false positive rates
fpr_a = confusion_matrix(y_true[group_a == 1], y_pred[group_a == 1], normalize="true")[0, 1]
fpr_b = confusion_matrix(y_true[group_b == 1], y_pred[group_b == 1], normalize="true")[0, 1]
return fpr_a - fpr_b
def false_negative_rate_diff(group_a, group_b, y_pred, y_true):
"""False negative Rate difference
This function computes the difference in false negative\
rates for group_a and group_b.
Interpretation
----------
A value of 0 is desired. This metric ranges between -1 and 1,\
with negative values indicating bias against group_b, and\
positive values indicating bias against group_a.
Parameters
----------
group_a : array-like
Group membership vector (binary)
group_b : array-like
Group membership vector (binary)
y_pred : array-like
Predictions vector (binary)
y_true : array-like
Target vector (binary)
Returns
-------
float
False Negative Rate difference
Notes
-----
:math:`fnr_a - fnr_b`
Examples
-------
>>> import numpy as np
>>> from holisticai.bias.metrics import fnr_diff
>>> group_a = np.array([1, 1, 1, 1, 0, 0, 0, 0, 0, 0])
>>> group_b = np.array([0, 0, 0, 0, 1, 1, 1, 1, 1, 1])
>>> y_pred = np.array([1, 1, 0, 0, 1, 1, 0, 1, 1, 1])
>>> y_true = np.array([1, 1, 0, 0, 1, 0, 1, 0, 0, 1])
>>> fnr_diff(group_a, group_b, y_pred, y_true)
-0.3333333333333333
"""
# check and coerce
group_a, group_b, y_pred, y_true = _classification_checks(group_a, group_b, y_pred, y_true)
# Calculate false negative rates
fnr_a = confusion_matrix(y_true[group_a == 1], y_pred[group_a == 1], normalize="true")[1, 0]
fnr_b = confusion_matrix(y_true[group_b == 1], y_pred[group_b == 1], normalize="true")[1, 0]
return fnr_a - fnr_b
def true_negative_rate_diff(group_a, group_b, y_pred, y_true):
"""True negative Rate difference
This function computes the difference in true negative\
rates for group_a and group_b.
Interpretation
----------
A value of 0 is desired. This metric ranges between -1 and 1,\
with negative values indicating bias against group_a, and\
positive values indicating bias against group_b.
Parameters
----------
group_a : array-like
Group membership vector (binary)
group_b : array-like
Group membership vector (binary)
y_pred : array-like
Predictions vector (binary)
y_true : array-like
Target vector (binary)
Returns
-------
float
True Negative Rate difference
Notes
-----
:math:`tnr_a - tnr_b`
Examples
-------
>>> import numpy as np
>>> from holisticai.bias.metrics import tnr_diff
>>> group_a = np.array([1, 1, 1, 1, 0, 0, 0, 0, 0, 0])
>>> group_b = np.array([0, 0, 0, 0, 1, 1, 1, 1, 1, 1])
>>> y_pred = np.array([1, 1, 0, 0, 1, 1, 0, 1, 1, 1])
>>> y_true = np.array([1, 1, 0, 0, 1, 0, 1, 0, 0, 1])
>>> tnr_diff(group_a, group_b, y_pred, y_true)
1
"""
# check and coerce
group_a, group_b, y_pred, y_true = _classification_checks(group_a, group_b, y_pred, y_true)
# Calculate false negative rates
tnr_a = confusion_matrix(y_true[group_a == 1], y_pred[group_a == 1], normalize="true")[0, 0]
tnr_b = confusion_matrix(y_true[group_b == 1], y_pred[group_b == 1], normalize="true")[0, 0]
return tnr_a - tnr_b
def average_odds_diff(group_a, group_b, y_pred, y_true):
"""Average Odds Difference
This function computes the difference in average odds\
between group_a and group_b.
Interpretation
--------------
A value of 0 is desired. This metric ranges between -1 and 1,\
with negative values indicating bias against group_a,\
and positive values indicating bias against group_b.\
The range (-0.1,0.1) is considered acceptable.
Parameters
----------
group_a : array-like
Group membership vector (binary)
group_b : array-like
Group membership vector (binary)
y_pred : array-like
Predictions vector (binary)
y_true : array-like
Target vector (binary)
Returns
-------
float
AOD score
Notes
-----
:math:`0.5 * (fpr_a-fpr_b + tpr_a-tpr_b)`
Examples
-------
>>> import numpy as np
>>> from holisticai.bias.metrics import average_odds_diff
>>> group_a = np.array([1, 1, 1, 1, 0, 0, 0, 0, 0, 0])
>>> group_b = np.array([0, 0, 0, 0, 1, 1, 1, 1, 1, 1])
>>> y_pred = np.array([1, 1, 0, 0, 1, 1, 0, 1, 1, 1])
>>> y_true = np.array([1, 1, 0, 0, 1, 0, 1, 0, 0, 1])
>>> average_odds_diff(group_a, group_b, y_pred, y_true)
-0.3333333333333333
"""
# check and coerce
group_a, group_b, y_pred, y_true = _classification_checks(group_a, group_b, y_pred, y_true)
# Compute AOD
return 0.5 * (
equal_opportunity_diff(group_a, group_b, y_pred, y_true)
+ false_positive_rate_diff(group_a, group_b, y_pred, y_true)
)
def accuracy_diff(group_a, group_b, y_score, y_true):
"""Accuracy Difference
This function computes the difference in accuracy\
of predictions for group_a and group_b
Interpretation
--------------
A value of 0 is desired. This metric ranges between -1 and 1,\
with negative values indicating bias against group_a,\
and positive values indicating bias against group_b.
Parameters
----------
group_a : array-like
Group membership vector (binary)
group_b : array-like
Group membership vector (binary)
y_score : numpy array
Probability estimates (regression)
y_true : array-like
Target vector (binary)
Returns
-------
float
acc_diff : acc_a - acc_b
Examples
-------
>>> import numpy as np
>>> from holisticai.bias.metrics import accuracy_diff
>>> group_a = np.array([1, 1, 1, 1, 0, 0, 0, 0, 0, 0])
>>> group_b = np.array([0, 0, 0, 0, 1, 1, 1, 1, 1, 1])
>>> y_pred = np.array([1, 1, 0, 0, 1, 1, 0, 1, 1, 1])
>>> y_true = np.array([1, 1, 0, 0, 1, 0, 1, 0, 0, 1])
>>> accuracy_diff(group_a, group_b, y_pred, y_true)
0.6666666666666667
"""
# check and coerce
group_a, group_b, y_score, y_true, _ = _regression_checks(group_a, group_b, y_score, y_true, None)
_check_binary(y_true, "y_true")
# split data by groups
y_true_a = y_true[group_a == 1]
y_score_a = y_score[group_a == 1]
y_true_b = y_true[group_b == 1]
y_score_b = y_score[group_b == 1]
# compute abroca
return accuracy_score(y_true_a, y_score_a) - accuracy_score(y_true_b, y_score_b)
def abroca(group_a, group_b, y_score, y_true):
"""ABROCA (area between roc curves)
This function computes the area between the roc curve\
of group_a and the roc curve of group_b
Interpretation
--------------
A value of 0 is desired. This metric ranges between -1 and 1,\
with negative values indicating bias against group_a,\
and positive values indicating bias against group_b.
Parameters
----------
group_a : array-like
Group membership vector (binary)
group_b : array-like
Group membership vector (binary)
y_score : array-like
Probability estimates (regression)
y_true : array-like
Target vector (binary)
Returns
-------
float
ABROCA : roc_auc_a - roc_auc_b
Examples
--------
>>> import numpy as np
>>> from holisticai.bias.metrics import abroca
>>> group_a = np.array([1] * 50 + [0] * 50)
>>> group_b = np.array([0] * 50 + [1] * 50)
>>> y_score = np.concatenate((np.linspace(0, 1, 50), np.linspace(0, 1, 50) ** 2))
>>> y_true = y_score + np.random.random(y_score.shape) > 0.5
>>> abroca(group_a, group_b, y_score, y_true)
0.11806478405315601
"""
# check and coerce
group_a, group_b, y_score, y_true, _ = _regression_checks(group_a, group_b, y_score, y_true, None)
_check_binary(y_true, "y_true")
# split data by groups
y_true_a = y_true[group_a == 1]
y_score_a = y_score[group_a == 1]
y_true_b = y_true[group_b == 1]
y_score_b = y_score[group_b == 1]
# compute abroca
return roc_auc_score(y_true_a, y_score_a) - roc_auc_score(y_true_b, y_score_b)
def classification_bias_metrics(
group_a=None, group_b=None, y_pred=None, y_true=None, y_score=None, X=None, metric_type="group", **kargs
):
"""Classification bias metrics batch computation
This function computes all the relevant classification bias metrics,\
and displays them as a pandas dataframe. It also includes a fair reference\
value for comparison.
Parameters
----------
group_a : array-like
Group membership vector (binary)
group_b : array-like
Group membership vector (binary)
y_pred : array-like
Predictions vector (binary)
y_true : array-like, optional
Target vector (binary)
y_score : array-like, optional
Probability estimates (regression)
X : array-like, optional
Feature matrix
metric_type : str, optional
Specifies which metrics we compute 'group', 'individual', 'equal_outcome' , 'equal_opportunity'
**kargs : dict
Additional keyword arguments for individual metrics
Returns
-------
pandas DataFrame
Metrics | Values | Reference
"""
individual_metrics_format_1 = {
"Theil Index": theil_index,
"Generalized Entropy Index": generalized_entropy_index,
"Coefficient of Variation": coefficient_of_variation,
}
individual_metrics_format_2 = {
"Consistency Score": consistency_score,
}
equal_outcome_metrics = {
"Statistical Parity": statistical_parity,
"Disparate Impact": disparate_impact,
"Four Fifths Rule": four_fifths,
"Cohen D": cohen_d,
"2SD Rule": z_test_diff,
}
equal_opportunity_metrics = {
"Equality of Opportunity Difference": equal_opportunity_diff,
"False Positive Rate Difference": false_positive_rate_diff,
"Average Odds Difference": average_odds_diff,
"Accuracy Difference": accuracy_diff,
}
soft_metrics = {
"ABROCA": abroca,
}
ref_vals = {
"Statistical Parity": 0,
"Disparate Impact": 1,
"Four Fifths Rule": 1,
"Cohen D": 0,
"Equality of Opportunity Difference": 0,
"False Positive Rate Difference": 0,
"Average Odds Difference": 0,
"Accuracy Difference": 0,
"ABROCA": 0,
"2SD Rule": 0,
"Theil Index": 0,
"Generalized Entropy Index": 0,
"Consistency Score": 1,
"Coefficient of Variation": 0,
}
has_group_parameters = all((p is not None) for p in [group_a, group_b, y_pred])
if has_group_parameters:
out_metrics = [[pf, fn(group_a, group_b, y_pred), ref_vals[pf]] for pf, fn in equal_outcome_metrics.items()]
opp_metrics = []
if y_true is not None:
opp_metrics += [
[pf, fn(group_a, group_b, y_pred, y_true), ref_vals[pf]] for pf, fn in equal_opportunity_metrics.items()
]
if y_score is not None:
opp_metrics += [
[pf, fn(group_a, group_b, y_score, y_true), ref_vals[pf]] for pf, fn in soft_metrics.items()
]
if metric_type == "individual":
from collections import defaultdict
metric_kargs = defaultdict(dict)
for k, value in kargs.items():
metric, arg = k.split("__")
metric_kargs[metric][arg] = value
indv_metrics = []
if y_pred is not None:
if y_true is not None:
indv_metrics += [
[pf, fn(y_pred, y_true, **metric_kargs[fn.__name__]), ref_vals[pf]]
for pf, fn in individual_metrics_format_1.items()
]
if X is not None:
indv_metrics += [
[pf, fn(X, y_pred, **metric_kargs[fn.__name__]), ref_vals[pf]]
for pf, fn in individual_metrics_format_2.items()
]
if metric_type in ["group", "both"]:
if metric_type == "both":
# TODO: remove both for next version
warnings.warn( # noqa: B028
"`both` option will be depreciated in the next versions, use group",
DeprecationWarning,
)
metrics = out_metrics + opp_metrics
return pd.DataFrame(metrics, columns=["Metric", "Value", "Reference"]).set_index("Metric")
if metric_type == "equal_outcome":
return pd.DataFrame(out_metrics, columns=["Metric", "Value", "Reference"]).set_index("Metric")
if metric_type == "equal_opportunity":
return pd.DataFrame(opp_metrics, columns=["Metric", "Value", "Reference"]).set_index("Metric")
if metric_type == "individual":
return pd.DataFrame(indv_metrics, columns=["Metric", "Value", "Reference"]).set_index("Metric")
msg = "metric_type is not one of : group, individual, equal_outcome, equal_opportunity"
raise ValueError(msg)
### Individual Metrics
def benefit_function(y_pred, y_true):
"""Benefit function
This function computes the benefit function\
used in the generalized entropy index.
Parameters
----------
y_true : array-like
True target values
y_pred : array-like
Predicted target values
Returns
-------
np.ndarray
Benefit function
"""
return y_pred - y_true + 1
def theil_index(y_pred: np.ndarray, y_true: np.ndarray) -> float:
"""The Theil index
The Theil index is a measure of inequality that is commonly used in economics.\
It is used to measure the inequality of a distribution, such as the distribution\
of income or wealth. The Theil index is a special case of general entropy indices\
that allows to observe inequalities at group level and individual level.
Interpretation
--------------
A high value implies high inequality while a value of 0 indicates perfect equality.
Parameters
----------
y_true : array-like of shape (n_samples,)
The true target values.
y_pred : array-like of shape (n_samples,)