File size: 12,310 Bytes
fc0f7bd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Using fairlearn GridSearch with census data\n",
    "\n",
    "This notebook shows how to use `fairlearn` and the Fairness dashboard to generate predictors for the Census dataset. This dataset is a classification problem - given a range of data about 32,000 individuals, predict whether their annual income is above or below fifty thousand dollars per year.\n",
    "\n",
    "For the purposes of this notebook, we shall treat this as a loan decision problem. We will pretend that the label indicates whether or not each individual repaid a loan in the past. We will use the data to train a predictor to predict whether previously unseen individuals will repay a loan or not. The assumption is that the model predictions are used to decide whether an individual should be offered a loan.\n",
    "\n",
    "We will first train a fairness-unaware predictor and show that it leads to unfair decisions under a specific notion of fairness called *demographic parity*. We then mitigate unfairness by applying the `GridSearch` algorithm from `fairlearn` package."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Load and preprocess the data set\n",
    "\n",
    "For simplicity, we import the data set from the `shap` package, which contains the data in a cleaned format. We start by importing the various modules we're going to use:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from fairlearn.reductions import GridSearch\n",
    "from fairlearn.reductions import DemographicParity, ErrorRate\n",
    "\n",
    "from sklearn import svm, neighbors, tree\n",
    "from sklearn.preprocessing import LabelEncoder,StandardScaler\n",
    "from sklearn.linear_model import LogisticRegression\n",
    "import pandas as pd\n",
    "import shap\n",
    "\n",
    "import numpy as np\n",
    "\n",
    "shap.initjs()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We can now load and inspect the data from the `shap` package:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "X_raw, Y = shap.datasets.adult()\n",
    "X_raw"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We are going to treat the sex of each individual as a protected attribute (where 0 indicates female and 1 indicates male), and in this particular case we are going separate this attribute out and drop it from the main data. We then perform some standard data preprocessing steps to convert the data into a format suitable for the ML algorithms"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "A = X_raw[\"Sex\"]\n",
    "X = X_raw.drop(labels=['Sex'],axis = 1)\n",
    "X = pd.get_dummies(X)\n",
    "\n",
    "sc = StandardScaler()\n",
    "X_scaled = sc.fit_transform(X)\n",
    "X_scaled = pd.DataFrame(X_scaled, columns=X.columns)\n",
    "\n",
    "le = LabelEncoder()\n",
    "Y = le.fit_transform(Y)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Finally, we split the data into training and test sets:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.model_selection import train_test_split\n",
    "X_train, X_test, Y_train, Y_test, A_train, A_test = train_test_split(X_scaled, \n",
    "                                                    Y, \n",
    "                                                    A,\n",
    "                                                    test_size = 0.2,\n",
    "                                                    random_state=0,\n",
    "                                                    stratify=Y)\n",
    "\n",
    "# Work around indexing bug\n",
    "X_train = X_train.reset_index(drop=True)\n",
    "A_train = A_train.reset_index(drop=True)\n",
    "X_test = X_test.reset_index(drop=True)\n",
    "A_test = A_test.reset_index(drop=True)\n",
    "\n",
    "# Improve labels\n",
    "A_test = A_test.map({ 0:\"female\", 1:\"male\"})"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Training a fairness-unaware predictor\n",
    "\n",
    "To show the effect of `fairlearn` we will first train a standard ML predictor that does not incorporate fairness For speed of demonstration, we use a simple logistic regression estimator from `sklearn`:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "scrolled": true
   },
   "outputs": [],
   "source": [
    "unmitigated_predictor = LogisticRegression(solver='liblinear', fit_intercept=True)\n",
    "\n",
    "unmitigated_predictor.fit(X_train, Y_train)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We can load this predictor into the Fairness dashboard, and examine how it is unfair (there is a warning about AzureML since we are not yet integrated with that product):"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from fairlearn.widget import FairlearnDashboard\n",
    "FairlearnDashboard(sensitive_features=A_test, sensitive_feature_names=['sex'],\n",
    "                   y_true=Y_test,\n",
    "                   y_pred={\"unmitigated\": unmitigated_predictor.predict(X_test)})"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Looking at the disparity in accuracy, we see that males have an error rate about three times greater than the females. More interesting is the disparity in opportunitiy - males are offered loans at three times the rate of females.\n",
    "\n",
    "Despite the fact that we removed the feature from the training data, our predictor still discriminates based on sex. This demonstrates that simply ignoring a protected attribute when fitting a predictor rarely eliminates unfairness. There will generally be enough other features correlated with the removed attribute to lead to disparate impact."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Mitigation with GridSearch\n",
    "\n",
    "The `GridSearch` class in `fairlearn` implements a simplified version of the exponentiated gradient reduction of [Agarwal et al. 2018](https://arxiv.org/abs/1803.02453). The user supplies a standard ML estimator, which is treated as a blackbox. `GridSearch` works by generating a sequence of relabellings and reweightings, and trains a predictor for each.\n",
    "\n",
    "For this example, we specify demographic parity (on the protected attribute of sex) as the fairness metric. Demographic parity requires that individuals are offered the opportunity (are approved for a loan in this example) independent of membership in the protected class (i.e., females and males should be offered loans at the same rate). We are using this metric for the sake of simplicity; in general, the appropriate fairness metric will not be obvious."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "sweep = GridSearch(LogisticRegression(solver='liblinear', fit_intercept=True),\n",
    "                   constraints=DemographicParity(),\n",
    "                   grid_size=71)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Our algorithms provide `fit()` and `predict()` methods, so they behave in a similar manner to other ML packages in Python. We do however have to specify two extra arguments to `fit()` - the column of protected attribute labels, and also the number of predictors to generate in our sweep.\n",
    "\n",
    "After `fit()` completes, we extract the full set of predictors from the `GridSearch` object."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "sweep.fit(X_train, Y_train,\n",
    "          sensitive_features=A_train)\n",
    "\n",
    "predictors = [ z.predictor for z in sweep.all_results]"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We could load these predictors into the Fairness dashboard now. However, the plot would be somewhat confusing due to their number. In this case, we are going to remove the predictors which are dominated in the error-disparity space by others from the sweep (note that the disparity will only be calculated for the protected attribute; other potentially protected attributes will not be mitigated). In general, one might not want to do this, since there may be other considerations beyond the strict optimisation of error and disparity (of the given protected attribute)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "errors, disparities = [], []\n",
    "for m in predictors:\n",
    "    classifier = lambda X: m.predict(X)\n",
    "    \n",
    "    error = ErrorRate()\n",
    "    error.load_data(X_train, pd.Series(Y_train), sensitive_features=A_train)\n",
    "    disparity = DemographicParity()\n",
    "    disparity.load_data(X_train, pd.Series(Y_train), sensitive_features=A_train)\n",
    "    \n",
    "    errors.append(error.gamma(classifier)[0])\n",
    "    disparities.append(disparity.gamma(classifier).max())\n",
    "    \n",
    "all_results = pd.DataFrame( {\"predictor\": predictors, \"error\": errors, \"disparity\": disparities})\n",
    "\n",
    "non_dominated = []\n",
    "for row in all_results.itertuples():\n",
    "    errors_for_lower_or_eq_disparity = all_results[\"error\"][all_results[\"disparity\"]<=row.disparity]\n",
    "    if row.error <= errors_for_lower_or_eq_disparity.min():\n",
    "        non_dominated.append(row.predictor)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Finally, we can put the dominant models into the Fairness dashboard, along with the unmitigated model."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "dashboard_predicted = {\"unmitigated\": unmitigated_predictor.predict(X_test)}\n",
    "for i in range(len(non_dominated)):\n",
    "    key = \"dominant_model_{0}\".format(i)\n",
    "    value = non_dominated[i].predict(X_test)\n",
    "    dashboard_predicted[key] = value\n",
    "\n",
    "\n",
    "FairlearnDashboard(sensitive_features=A_test, sensitive_feature_names=['sex'],\n",
    "                   y_true=Y_test,\n",
    "                   y_pred=dashboard_predicted)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We see a Pareto front forming - the set of predictors which represent optimal tradeoffs between accuracy and disparity i predictions. In the ideal case, we would have a predictor at (1,0) - perfectly accurate and without any unfairness under demographic parity (with respect to the protected attribute \"sex\"). The Pareto front represents the closest we can come to this ideal based on our data and choice of estimator. Note the range of the axes - the disparity axis covers more values than the accuracy, so we can reduce disparity substantially for a small loss in accuracy.\n",
    "\n",
    "By clicking on individual models on the plot, we can inspect their metrics for disparity and accuracy in greater detail. In a real example, we would then pick the model which represented the best trade-off between accuracy and disparity given the relevant business constraints."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.9"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}