-
Notifications
You must be signed in to change notification settings - Fork 20
/
Copy patheq_odds.py
248 lines (198 loc) · 8.74 KB
/
eq_odds.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
import cvxpy as cvx
import numpy as np
from collections import namedtuple
class Model(namedtuple('Model', 'pred label')):
def logits(self):
raw_logits = np.clip(np.log(self.pred / (1 - self.pred)), -100, 100)
return raw_logits
def num_samples(self):
return len(self.pred)
def base_rate(self):
"""
Percentage of samples belonging to the positive class
"""
return np.mean(self.label)
def accuracy(self):
return self.accuracies().mean()
def precision(self):
return (self.label[self.pred.round() == 1]).mean()
def recall(self):
return (self.label[self.label == 1].round()).mean()
def tpr(self):
"""
True positive rate
"""
return np.mean(np.logical_and(self.pred.round() == 1, self.label == 1))
def fpr(self):
"""
False positive rate
"""
return np.mean(np.logical_and(self.pred.round() == 1, self.label == 0))
def tnr(self):
"""
True negative rate
"""
return np.mean(np.logical_and(self.pred.round() == 0, self.label == 0))
def fnr(self):
"""
False negative rate
"""
return np.mean(np.logical_and(self.pred.round() == 0, self.label == 1))
def fn_cost(self):
"""
Generalized false negative cost
"""
return 1 - self.pred[self.label == 1].mean()
def fp_cost(self):
"""
Generalized false positive cost
"""
return self.pred[self.label == 0].mean()
def accuracies(self):
return self.pred.round() == self.label
def eq_odds(self, othr, mix_rates=None):
has_mix_rates = not (mix_rates is None)
if not has_mix_rates:
mix_rates = self.eq_odds_optimal_mix_rates(othr)
sp2p, sn2p, op2p, on2p = tuple(mix_rates)
self_fair_pred = self.pred.copy()
self_pp_indices, = np.nonzero(self.pred.round())
self_pn_indices, = np.nonzero(1 - self.pred.round())
np.random.shuffle(self_pp_indices)
np.random.shuffle(self_pn_indices)
n2p_indices = self_pn_indices[:int(len(self_pn_indices) * sn2p)]
self_fair_pred[n2p_indices] = 1 - self_fair_pred[n2p_indices]
p2n_indices = self_pp_indices[:int(len(self_pp_indices) * (1 - sp2p))]
self_fair_pred[p2n_indices] = 1 - self_fair_pred[p2n_indices]
othr_fair_pred = othr.pred.copy()
othr_pp_indices, = np.nonzero(othr.pred.round())
othr_pn_indices, = np.nonzero(1 - othr.pred.round())
np.random.shuffle(othr_pp_indices)
np.random.shuffle(othr_pn_indices)
n2p_indices = othr_pn_indices[:int(len(othr_pn_indices) * on2p)]
othr_fair_pred[n2p_indices] = 1 - othr_fair_pred[n2p_indices]
p2n_indices = othr_pp_indices[:int(len(othr_pp_indices) * (1 - op2p))]
othr_fair_pred[p2n_indices] = 1 - othr_fair_pred[p2n_indices]
fair_self = Model(self_fair_pred, self.label)
fair_othr = Model(othr_fair_pred, othr.label)
if not has_mix_rates:
return fair_self, fair_othr, mix_rates
else:
return fair_self, fair_othr
def eq_odds_optimal_mix_rates(self, othr):
sbr = float(self.base_rate())
obr = float(othr.base_rate())
sp2p = cvx.Variable(1)
sp2n = cvx.Variable(1)
sn2p = cvx.Variable(1)
sn2n = cvx.Variable(1)
op2p = cvx.Variable(1)
op2n = cvx.Variable(1)
on2p = cvx.Variable(1)
on2n = cvx.Variable(1)
sfpr = self.fpr() * sp2p + self.tnr() * sn2p
sfnr = self.fnr() * sn2n + self.tpr() * sp2n
ofpr = othr.fpr() * op2p + othr.tnr() * on2p
ofnr = othr.fnr() * on2n + othr.tpr() * op2n
error = sfpr + sfnr + ofpr + ofnr
sflip = 1 - self.pred
sconst = self.pred
oflip = 1 - othr.pred
oconst = othr.pred
sm_tn = np.logical_and(self.pred.round() == 0, self.label == 0)
sm_fn = np.logical_and(self.pred.round() == 0, self.label == 1)
sm_tp = np.logical_and(self.pred.round() == 1, self.label == 1)
sm_fp = np.logical_and(self.pred.round() == 1, self.label == 0)
om_tn = np.logical_and(othr.pred.round() == 0, othr.label == 0)
om_fn = np.logical_and(othr.pred.round() == 0, othr.label == 1)
om_tp = np.logical_and(othr.pred.round() == 1, othr.label == 1)
om_fp = np.logical_and(othr.pred.round() == 1, othr.label == 0)
spn_given_p = (sn2p * (sflip * sm_fn).mean() + sn2n * (sconst * sm_fn).mean()) / sbr + \
(sp2p * (sconst * sm_tp).mean() + sp2n * (sflip * sm_tp).mean()) / sbr
spp_given_n = (sp2n * (sflip * sm_fp).mean() + sp2p * (sconst * sm_fp).mean()) / (1 - sbr) + \
(sn2p * (sflip * sm_tn).mean() + sn2n * (sconst * sm_tn).mean()) / (1 - sbr)
opn_given_p = (on2p * (oflip * om_fn).mean() + on2n * (oconst * om_fn).mean()) / obr + \
(op2p * (oconst * om_tp).mean() + op2n * (oflip * om_tp).mean()) / obr
opp_given_n = (op2n * (oflip * om_fp).mean() + op2p * (oconst * om_fp).mean()) / (1 - obr) + \
(on2p * (oflip * om_tn).mean() + on2n * (oconst * om_tn).mean()) / (1 - obr)
constraints = [
sp2p == 1 - sp2n,
sn2p == 1 - sn2n,
op2p == 1 - op2n,
on2p == 1 - on2n,
sp2p <= 1,
sp2p >= 0,
sn2p <= 1,
sn2p >= 0,
op2p <= 1,
op2p >= 0,
on2p <= 1,
on2p >= 0,
spp_given_n == opp_given_n,
spn_given_p == opn_given_p,
]
prob = cvx.Problem(cvx.Minimize(error), constraints)
prob.solve()
res = np.array([sp2p.value, sn2p.value, op2p.value, on2p.value])
return res
def __repr__(self):
return '\n'.join([
'Accuracy:\t%.3f' % self.accuracy(),
'F.P. cost:\t%.3f' % self.fp_cost(),
'F.N. cost:\t%.3f' % self.fn_cost(),
'Base rate:\t%.3f' % self.base_rate(),
'Avg. score:\t%.3f' % self.pred.mean(),
])
"""
Demo
"""
if __name__ == '__main__':
"""
To run the demo:
```
python eq_odds.py <path_to_model_predictions.csv>
```
`<path_to_model_predictions.csv>` should contain the following columns for the VALIDATION set:
- `prediction` (a score between 0 and 1)
- `label` (ground truth - either 0 or 1)
- `group` (group assignment - either 0 or 1)
Try the following experiments, which were performed in the paper:
```
python eq_odds.py data/income.csv
python eq_odds.py data/health.csv
python eq_odds.py data/criminal_recidivism.csv
```
"""
import pandas as pd
import sys
if not len(sys.argv) == 2:
raise RuntimeError('Invalid number of arguments')
# Load the validation set scores from csvs
data_filename = sys.argv[1]
test_and_val_data = pd.read_csv(sys.argv[1])
# Randomly split the data into two sets - one for computing the fairness constants
order = np.random.permutation(len(test_and_val_data))
val_indices = order[0::2]
test_indices = order[1::2]
val_data = test_and_val_data.iloc[val_indices]
test_data = test_and_val_data.iloc[test_indices]
# Create model objects - one for each group, validation and test
group_0_val_data = val_data[val_data['group'] == 0]
group_1_val_data = val_data[val_data['group'] == 1]
group_0_test_data = test_data[test_data['group'] == 0]
group_1_test_data = test_data[test_data['group'] == 1]
group_0_val_model = Model(group_0_val_data['prediction'].as_matrix(), group_0_val_data['label'].as_matrix())
group_1_val_model = Model(group_1_val_data['prediction'].as_matrix(), group_1_val_data['label'].as_matrix())
group_0_test_model = Model(group_0_test_data['prediction'].as_matrix(), group_0_test_data['label'].as_matrix())
group_1_test_model = Model(group_1_test_data['prediction'].as_matrix(), group_1_test_data['label'].as_matrix())
# Find mixing rates for equalized odds models
_, _, mix_rates = Model.eq_odds(group_0_val_model, group_1_val_model)
# Apply the mixing rates to the test models
eq_odds_group_0_test_model, eq_odds_group_1_test_model = Model.eq_odds(group_0_test_model,
group_1_test_model,
mix_rates)
# Print results on test model
print('Original group 0 model:\n%s\n' % repr(group_0_test_model))
print('Original group 1 model:\n%s\n' % repr(group_1_test_model))
print('Equalized odds group 0 model:\n%s\n' % repr(eq_odds_group_0_test_model))
print('Equalized odds group 1 model:\n%s\n' % repr(eq_odds_group_1_test_model))