-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain_plots.py
317 lines (254 loc) · 11.3 KB
/
main_plots.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
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.4'
# jupytext_version: 1.1.7
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# +
# %matplotlib inline
# %load_ext autoreload
# %autoreload 2
import pickle
from mutabledataset import GermanSimDataset
from sklearn.preprocessing import MaxAbsScaler
from agent import RationalAgent, RationalAgentOrig
from simulation import Simulation, SimulationResultSet
from learner import LogisticLearner
import plot
import numpy as np
import pandas as pd
from learner import StatisticalParityLogisticLearner, StatisticalParityFlipperLogisticLearner
from learner import FairLearnLearner
from learner import GaussianNBLearner
from learner import RejectOptionsLogisticLearner, MetaFairLearner, CalibratedLogisticLearner
from learner import ReweighingLogisticLearner
from IPython.display import display, Markdown, Latex
import matplotlib.pyplot as plt
import seaborn as sns
from numpy.random import normal
from IPython.display import display, Markdown, Latex
from scipy.special import huber
from utils import _df_selection, count_df
#sns.set(rc={'figure.figsize':(20.7,8.27)})
# -
# ## Parameters for simulation
# +
immutable = ['age']
mutable_monotone_neg = ['month', 'credit_amount', 'status', 'investment_as_income_percentage', 'number_of_credits', 'people_liable_for']
mutable_dontknow = ['residence_since']
mutable_monotone_pos = ['savings']
categorical = [#'credit_history=A30',
#'credit_history=A31',
#'credit_history=A32',
#'credit_history=A33',
#'credit_history=A34',
#'employment=A71',
#'employment=A72',
#'employment=A73',
#'employment=A74',
#'employment=A75',
#'has_checking_account',
#'housing=A151',
#'housing=A152',
#'housing=A153',
#'installment_plans=A141',
#'installment_plans=A142',
#'installment_plans=A143',
#'other_debtors=A101',
#'other_debtors=A102',
#'other_debtors=A103',
#'property=A121',
#'property=A122',
#'property=A123',
#'property=A124',
'purpose=A40',
'purpose=A41',
'purpose=A410',
'purpose=A42',
'purpose=A43',
'purpose=A44',
'purpose=A45',
'purpose=A46',
'purpose=A48',
'purpose=A49']
#'skill_level=A171',
#'skill_level=A172',
#'skill_level=A173',
#'skill_level=A174',
#'telephone=A191',
#'telephone=A192']
mutable_attr = 'savings'
group_attr = 'age'
priv_classes = [lambda x: x >= 25]
privileged_group = {group_attr: 1}
unprivileged_group = {group_attr: 0}
DefaultAgent = RationalAgent #RationalAgent, RationalAgentOrig (approx b(x) = h(x))
# CURRENT PROBLEM: subsidy doesnt help with stat parity...
# IDEA: if we subsidize heavily, the motivation to move across the boundary is too low
# especially because of the stopping criteria (direction should stay the same as subsidy is constant)
cost_fixed = lambda size: np.array([0] * size) #lambda size: np.abs(np.random.normal(loc=1,scale=0.5,size=size))# np.array([0.] * size) #np.abs(np.random.normal(loc=0,scale=0,size=size)) #np.abs(np.random.normal(loc=1,scale=0.5,size=size))
# TODO: plot cost function for dataset
C = 0.25
# https://en.wikipedia.org/wiki/Smooth_maximum
# differentiable function approximating max
def softmax(x1, x2):
return np.maximum(x1,x2)
alpha = 1
e_x1 = np.exp(alpha*x1)
e_x2 = np.exp(alpha*x2)
return (x1*e_x1 + x2*e_x2)/(e_x1+e_x2)
# /len(all_mutable)
all_mutable = mutable_monotone_pos + mutable_monotone_neg + mutable_dontknow + categorical
all_mutable_dedummy = list(set(list(map(lambda s: s.split('=')[0], all_mutable))))
COST_CONST = 12. #len(all_mutable)
c_pos = lambda x_new, x, rank: softmax((rank(x_new)-rank(x)), 0.)/COST_CONST
c_neg = lambda x_new, x, rank: softmax((rank(x)-rank(x_new)), 0.)/COST_CONST
c_cat = lambda x_new, x, rank: softmax(x-x_new, x_new-x) * C/COST_CONST
c_immutable = lambda x_new, x, rank: np.abs(x_new-x)*np.nan_to_num(float('inf'))
# -
# ## Common simulation code
# +
def dataset():
return GermanSimDataset(mutable_features=all_mutable,
domains={k: 'auto' for k in all_mutable},
discrete=all_mutable,
protected_attribute_names=[group_attr],
cost_fns={ **{a: c_pos for a in mutable_monotone_pos},
**{a: c_neg for a in mutable_monotone_neg},
**{a: c_cat for a in categorical},
**{a: c_immutable for a in immutable}},
privileged_classes=priv_classes,
features_to_drop=['personal_status', 'sex', 'foreign_worker'])
def do_sim(learner, cost_fixed=cost_fixed, cost_fixed_dep=None, collect_incentive_data=False, max_it=60):
data = dataset()
sim = Simulation(data,
DefaultAgent,
learner,
cost_fixed if cost_fixed_dep is None else None,
collect_incentive_data=collect_incentive_data,
max_it=max_it,
cost_distribution_dep=cost_fixed_dep,
split=[0.9])
result_set = sim.start_simulation(runs=1)
return result_set
def save(obj, filename):
dumpfile = open(filename, 'wb')
pickle.dump(obj, dumpfile)
dumpfile.close()
def load(filename):
rs = {}
dumpfile = open(filename, 'rb')
rs = pickle.load(dumpfile)
dumpfile.close()
return rs
# -
C_EXECUTE = True
data = False()
# # Notions of Fairness
# +
# Compare different notions of fairness
data = dataset()
COST_CONST = 8
data = dataset()
learners = [("no constraint", LogisticLearner(exclude_protected=False)),
("calibration", CalibratedLogisticLearner([privileged_group], [unprivileged_group])),
("statistical parity", RejectOptionsLogisticLearner([privileged_group], [unprivileged_group], exclude_protected=False)),
("average odds", RejectOptionsLogisticLearner([privileged_group], [unprivileged_group], metric_name='Average odds difference', exclude_protected=False))]
if C_EXECUTE:
# execute
rss = list(map(lambda x: (x[0],do_sim(x[1], max_it=50)), learners))
# save
save(rss, "notions_of_fairness_lr_1_bf_" + str(COST_CONST))
# -
plot.boxplot(rss, unprivileged_group, privileged_group, name='sdffsdfdsfd')
#display(rss[0][1].feature_table([unprivileged_group, privileged_group]))
# +
filename = "notions_of_fairness_bf_8"
rss = load(filename)
plot.boxplot(rss, unprivileged_group, privileged_group, name=filename)
plot.plot_all_mutable_features_combined(rss, unprivileged_group, privileged_group, dataset, 'purpose', filename=filename, kind='cdf', select_group='1', barplot_delta=True)
plot.plot_all_mutable_features_combined(rss, unprivileged_group, privileged_group, dataset, 'purpose', filename=filename, kind='cdf', select_group='0', barplot_delta=True)
plot.plot_all_mutable_features_combined(rss, unprivileged_group, privileged_group, dataset, 'savings', filename=filename, kind='cdf', select_group='1')
plot.plot_all_mutable_features_combined(rss, unprivileged_group, privileged_group, dataset, 'savings', filename=filename, kind='cdf', select_group='0')
#for ft in all_mutable_dedummy:
# if ft == 'savings':
# for name, rs in rss:
# display(Markdown("#### " + ft + ", " + name))
# plot.plot_all_mutable_features(rs, unprivileged_group, privileged_group, dataset, [ft], name=filename+'_'+name, kind='cdf')
#
#
# -
# # Statistical Parity Comparison
data = dataset()
COST_CONST = 8
learners = [("no constraint", LogisticLearner(exclude_protected=False)),
("pre", ReweighingLogisticLearner([privileged_group], [unprivileged_group])),
("in",FairLearnLearner([privileged_group], [unprivileged_group])),
("post",RejectOptionsLogisticLearner([privileged_group], [unprivileged_group]))]
if C_EXECUTE:
# execute
rss = list(map(lambda x: (x[0],do_sim(x[1], max_it=130)), learners))
# save
save(rss, "statpar_comp_cost_bf" + str(COST_CONST))
# +
filename = "statpar_comp_cost_bf8"
rss = load(filename)
rss[0] = ('no constraint', rss[0][1])
save(rss, filename)
plot.boxplot(rss, unprivileged_group, privileged_group, name=filename)
plot.plot_all_mutable_features_combined(rss, unprivileged_group, privileged_group, dataset, 'purpose', filename=filename, kind='cdf', select_group='1', barplot_delta=True)
plot.plot_all_mutable_features_combined(rss, unprivileged_group, privileged_group, dataset, 'purpose', filename=filename, kind='cdf', select_group='0', barplot_delta=True)
plot.plot_all_mutable_features_combined(rss, unprivileged_group, privileged_group, dataset, 'savings', filename=filename, kind='cdf', select_group='1')
plot.plot_all_mutable_features_combined(rss, unprivileged_group, privileged_group, dataset, 'savings', filename=filename, kind='cdf', select_group='0')
#plot.plot_all_mutable_features_combined(rss, unprivileged_group, privileged_group, dataset, 'savings', filename=filename, kind='cdf', select_group='0')
#for ft in all_mutable_dedummy:
# for name, rs in rss:
# if ft == 'purpose':
# display(Markdown("#### " + ft + ", " + name))
# plot.plot_all_mutable_features(rs, unprivileged_group, privileged_group, dataset, [ft], name=filename+'_'+name, kind='cdf')
#plot.boxplot(rss, unprivileged_group, privileged_group, name=filename)
# -
# # Colorblind vs Colorsighted
# +
data = dataset()
COST_CONST = 8
learners = [("logreg cb", LogisticLearner(exclude_protected=True)),
("logreg cs", LogisticLearner(exclude_protected=False)),
("nb cb",GaussianNBLearner(exclude_protected=True)),
("nb cs",GaussianNBLearner(exclude_protected=False))]
if C_EXECUTE:
# execute
rss = list(map(lambda x: (x[0],do_sim(x[1], no_neighbors=60)), learners))
# save
save(rss, "colorsigted_blind_" + str(COST_CONST))
# +
rss = load("colorsigted_blind_8")
for ft in all_mutable_dedummy:
for name, rs in rss:
display(Markdown("#### " + ft + ", " + name))
plot.plot_all_mutable_features(rs, unprivileged_group, privileged_group, dataset, [ft], name=name, kind='cdf')
plot.boxplot(rss, unprivileged_group, privileged_group)
# -
# # Debug gradient ascend (plot)
# +
index = 1
features = ['purpose=A40', 'purpose=A41']
rss = load("calib_expl_8")
plot.plot_distribution(dataset(), 'month')
plot.plot_ga(rss[0][1], index, features=features)
plot.plot_ga(rss[1][1], index, features=features)
plot.boxplot(rss, unprivileged_group, privileged_group, name="calib_expl_8")
display(rss[0][1].feature_table([unprivileged_group, privileged_group]))
display(rss[1][1].feature_table([unprivileged_group, privileged_group]))
for ft in all_mutable_dedummy:
for name, rs in rss:
display(Markdown("#### " + ft + ", " + name))
plot.plot_all_mutable_features(rs, unprivileged_group, privileged_group, dataset, [ft], name=name, kind='cdf')
plot.boxplot(rss, unprivileged_group, privileged_group)