|
3 | 3 | # SPDX-License-Identifier: Apache-2.0 |
4 | 4 |
|
5 | 5 | import inspect |
6 | | -from typing import List, Union |
| 6 | +from typing import List, Union, Optional |
7 | 7 | from typing import NamedTuple |
8 | 8 |
|
9 | 9 | import numpy as np |
10 | 10 | import pandas as pd |
11 | 11 |
|
12 | 12 | from jurity.fairness.base import _BaseBinaryFairness |
13 | 13 | from jurity.fairness.base import _BaseMultiClassMetric |
14 | | -from jurity.utils import check_inputs_validity |
| 14 | +from jurity.utils import is_one_dimensional |
| 15 | +from jurity.utils_proba import get_argmax_memberships |
| 16 | +from jurity.utils_proba import get_bootstrap_results |
15 | 17 | from .average_odds import AverageOdds |
16 | 18 | from .disparate_impact import BinaryDisparateImpact, MultiDisparateImpact |
17 | 19 | from .equal_opportunity import EqualOpportunity |
@@ -41,57 +43,121 @@ class BinaryFairnessMetrics(NamedTuple): |
41 | 43 | @staticmethod |
42 | 44 | def get_all_scores(labels: Union[List, np.ndarray, pd.Series], |
43 | 45 | predictions: Union[List, np.ndarray, pd.Series], |
44 | | - is_member: Union[List, np.ndarray, pd.Series], |
45 | | - membership_label: Union[str, float, int] = 1) -> pd.DataFrame: |
| 46 | + memberships: Union[List, np.ndarray, pd.Series], |
| 47 | + surrogates: Union[List, np.ndarray, pd.Series] = None, |
| 48 | + membership_labels: Union[str, float, int, List, np.array] = 1, |
| 49 | + bootstrap_results: Optional[pd.DataFrame] = None) -> pd.DataFrame: |
46 | 50 | """ |
47 | | - Calculates and tabulates all of the fairness metric scores. |
48 | | -
|
| 51 | + Calculates and tabulates all fairness metric scores. |
49 | 52 | Parameters |
50 | 53 | ---------- |
51 | 54 | labels: Union[List, np.ndarray, pd.Series] |
52 | | - Binary ground truth labels for the provided dataset (0/1). |
| 55 | + Binary ground truth labels for each sample. |
53 | 56 | predictions: Union[List, np.ndarray, pd.Series] |
54 | | - Binary predictions from some black-box classifier (0/1). |
55 | | - is_member: Union[List, np.ndarray, pd.Series] |
56 | | - Binary membership labels (0/1). |
57 | | - membership_label: Union[str, float, int] |
58 | | - Value indicating group membership. |
59 | | - Default value is 1. |
60 | | -
|
| 57 | + Binary prediction for each sample from a black-box classifier binary (0/1). |
| 58 | + memberships: Union[List, np.ndarray, pd.Series, List[List], pd.DataFrame] |
| 59 | + Membership attribute for each sample. |
| 60 | + If deterministic, it is the binary label for each sample [0, 1, 0, ..., 1] |
| 61 | + If probabilistic, it is the likelihoods array of membership labels |
| 62 | + for each sample, i.e., a two-dim array [[0.6, 0.2, 0.2], ..., [..]] |
| 63 | + surrogates: Union[List, np.ndarray, pd.Series] |
| 64 | + Surrogate class attribute for each sample. |
| 65 | + If the membership is deterministic, surrogates are not needed. |
| 66 | + If the membership is probabilistic, |
| 67 | + - if surrogates are given, inferred metrics are used |
| 68 | + to calculate the fairness metric as proposed in [1]_. |
| 69 | + - when surrogates are not given, the arg max likelihood is used as the membership for each sample. |
| 70 | + Default is None. |
| 71 | + membership_labels: Union[int, float, str, List[int],np.array[int]] |
| 72 | + Labels indicating group membership. |
| 73 | + If the membership is deterministic, a single str/int is expected, e.g., 1. |
| 74 | + If the membership is probabilistic, a list or np.array of int is expected, |
| 75 | + with the index of the protected groups in the memberships array, |
| 76 | + e.g, [1, 2, 3], if 1-2-3 indexes are protected. |
| 77 | + Default value is 1 for deterministic case or [1] for probabilistic case. |
| 78 | + bootstrap_results: Optional[pd.DataFrame] |
| 79 | + A Pandas dataframe with inferred scores based surrogate class memberships. |
| 80 | + Default value is None. |
| 81 | + When given, other parameters will be discarded and bootstrap results will be used. |
61 | 82 | Returns |
62 | 83 | ---------- |
63 | 84 | Pandas data frame with all implemented binary fairness metrics. |
64 | 85 | """ |
65 | | - # Logic to check input types |
66 | | - check_inputs_validity(labels=labels, predictions=predictions, is_member=is_member, optional_labels=False) |
67 | | - |
68 | | - fairness_funcs = inspect.getmembers(BinaryFairnessMetrics, predicate=inspect.isclass)[:-1] |
69 | 86 |
|
| 87 | + # if memberships is given as likelihoods WITHOUT any surrogates, then revise it to deterministic case |
| 88 | + is_memberships_1d = is_one_dimensional(memberships) |
| 89 | + if not is_memberships_1d and surrogates is None and bootstrap_results is None: |
| 90 | + # Subtle point: membership_labels need to be an array when membership is 2d |
| 91 | + # if the user didn't specify, which defaults to 1, convert 1 -> [1] automatically |
| 92 | + # BUT do not overwrite membership_labels, we are still in "deterministic" mode via argmax |
| 93 | + # In deterministic mode, we need a single primitive label like 1 |
| 94 | + memberships = get_argmax_memberships(memberships, [1] if membership_labels == 1 else membership_labels) |
| 95 | + # We now converted 2d likelihoods memberships into deterministic 1d membership, set flag to true |
| 96 | + is_memberships_1d = True |
| 97 | + |
| 98 | + # Probabilistic version |
| 99 | + if not is_memberships_1d or bootstrap_results is not None: |
| 100 | + if membership_labels == 1: |
| 101 | + membership_labels = [1] |
| 102 | + |
| 103 | + if bootstrap_results is None: |
| 104 | + bootstrap_results = get_bootstrap_results(predictions, memberships, surrogates, |
| 105 | + membership_labels, labels) |
| 106 | + |
| 107 | + # Output df |
70 | 108 | df = pd.DataFrame(columns=["Metric", "Value", "Ideal Value", "Lower Bound", "Upper Bound"]) |
| 109 | + |
| 110 | + fairness_funcs = inspect.getmembers(BinaryFairnessMetrics, predicate=inspect.isclass)[:-1] |
71 | 111 | for fairness_func in fairness_funcs: |
72 | 112 |
|
| 113 | + # Get metric |
73 | 114 | name = fairness_func[0] |
74 | 115 | class_ = getattr(BinaryFairnessMetrics, name) # grab a class which is a property of BinaryFairnessMetrics |
75 | | - instance = class_() # dynamically instantiate such class |
| 116 | + metric = class_() # dynamically instantiate such class |
76 | 117 |
|
77 | | - if name in ["DisparateImpact", "StatisticalParity"]: |
78 | | - score = instance.get_score(predictions, is_member, membership_label) |
79 | | - elif name in ["GeneralizedEntropyIndex", "TheilIndex"]: |
80 | | - score = instance.get_score(labels, predictions) |
81 | | - else: |
82 | | - score = instance.get_score(labels, predictions, is_member, membership_label) |
| 118 | + # Get score |
| 119 | + score = BinaryFairnessMetrics._get_score_logic(metric, name, |
| 120 | + labels, predictions, memberships, surrogates, |
| 121 | + membership_labels, bootstrap_results) |
83 | 122 |
|
84 | | - if score is None: |
85 | | - score = np.nan |
86 | | - score = np.round(score, 3) |
87 | | - df = pd.concat([df, pd.DataFrame( |
88 | | - [[instance.name, score, instance.ideal_value, instance.lower_bound, instance.upper_bound]], |
89 | | - columns=df.columns)], axis=0, ignore_index=True) |
| 123 | + # Add score |
| 124 | + df = pd.concat([df, |
| 125 | + pd.DataFrame([[metric.name, score, metric.ideal_value, |
| 126 | + metric.lower_bound, metric.upper_bound]], columns=df.columns)], |
| 127 | + axis=0, ignore_index=True) |
90 | 128 |
|
91 | 129 | df = df.set_index("Metric") |
92 | 130 |
|
93 | 131 | return df |
94 | 132 |
|
| 133 | + @staticmethod |
| 134 | + def _get_score_logic(metric, name, |
| 135 | + labels, predictions, |
| 136 | + memberships, surrogates, |
| 137 | + membership_labels, bootstrap_results): |
| 138 | + |
| 139 | + # Standard deterministic calculation |
| 140 | + if bootstrap_results is None: |
| 141 | + if name in ["DisparateImpact", "StatisticalParity"]: |
| 142 | + score = metric.get_score(predictions, memberships, membership_labels) |
| 143 | + elif name in ["GeneralizedEntropyIndex", "TheilIndex"]: |
| 144 | + score = metric.get_score(labels, predictions) |
| 145 | + else: |
| 146 | + score = metric.get_score(labels, predictions, memberships, membership_labels) |
| 147 | + else: |
| 148 | + if name == "StatisticalParity": |
| 149 | + score = metric.get_score(predictions, memberships, surrogates, membership_labels, bootstrap_results) |
| 150 | + elif name in ["AverageOdds", "EqualOpportunity", "FNRDifference", "PredictiveEquality"]: |
| 151 | + score = metric.get_score(labels, predictions, memberships, surrogates, |
| 152 | + membership_labels, bootstrap_results) |
| 153 | + else: |
| 154 | + score = None |
| 155 | + |
| 156 | + # pretty score |
| 157 | + score = np.nan if score is None else np.round(score, 3) |
| 158 | + |
| 159 | + return score |
| 160 | + |
95 | 161 |
|
96 | 162 | class MultiClassFairnessMetrics(NamedTuple): |
97 | 163 | """ |
|
0 commit comments