mljar-supervised 1.2.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (94) hide show
  1. mljar_supervised-1.2.1.dist-info/METADATA +657 -0
  2. mljar_supervised-1.2.1.dist-info/RECORD +94 -0
  3. mljar_supervised-1.2.1.dist-info/WHEEL +5 -0
  4. mljar_supervised-1.2.1.dist-info/licenses/LICENSE +21 -0
  5. mljar_supervised-1.2.1.dist-info/top_level.txt +1 -0
  6. supervised/__init__.py +14 -0
  7. supervised/algorithms/__init__.py +0 -0
  8. supervised/algorithms/algorithm.py +151 -0
  9. supervised/algorithms/baseline.py +90 -0
  10. supervised/algorithms/catboost.py +436 -0
  11. supervised/algorithms/decision_tree.py +305 -0
  12. supervised/algorithms/extra_trees.py +176 -0
  13. supervised/algorithms/factory.py +28 -0
  14. supervised/algorithms/knn.py +137 -0
  15. supervised/algorithms/lightgbm.py +406 -0
  16. supervised/algorithms/linear.py +211 -0
  17. supervised/algorithms/nn.py +180 -0
  18. supervised/algorithms/random_forest.py +181 -0
  19. supervised/algorithms/registry.py +76 -0
  20. supervised/algorithms/sklearn.py +197 -0
  21. supervised/algorithms/xgboost.py +413 -0
  22. supervised/automl.py +568 -0
  23. supervised/base_automl.py +2542 -0
  24. supervised/callbacks/__init__.py +0 -0
  25. supervised/callbacks/callback.py +25 -0
  26. supervised/callbacks/callback_list.py +33 -0
  27. supervised/callbacks/early_stopping.py +213 -0
  28. supervised/callbacks/learner_time_constraint.py +47 -0
  29. supervised/callbacks/max_iters_constraint.py +16 -0
  30. supervised/callbacks/metric_logger.py +48 -0
  31. supervised/callbacks/terminate_on_nan.py +28 -0
  32. supervised/callbacks/total_time_constraint.py +79 -0
  33. supervised/ensemble.py +583 -0
  34. supervised/exceptions.py +21 -0
  35. supervised/fairness/__init__.py +0 -0
  36. supervised/fairness/metrics.py +654 -0
  37. supervised/fairness/optimization.py +414 -0
  38. supervised/fairness/plots.py +131 -0
  39. supervised/fairness/report.py +116 -0
  40. supervised/fairness/utils.py +40 -0
  41. supervised/model_framework.py +734 -0
  42. supervised/preprocessing/__init__.py +0 -0
  43. supervised/preprocessing/datetime_transformer.py +106 -0
  44. supervised/preprocessing/encoding_selector.py +30 -0
  45. supervised/preprocessing/exclude_missing_target.py +46 -0
  46. supervised/preprocessing/goldenfeatures_transformer.py +310 -0
  47. supervised/preprocessing/kmeans_transformer.py +115 -0
  48. supervised/preprocessing/label_binarizer.py +81 -0
  49. supervised/preprocessing/label_encoder.py +54 -0
  50. supervised/preprocessing/preprocessing.py +652 -0
  51. supervised/preprocessing/preprocessing_categorical.py +117 -0
  52. supervised/preprocessing/preprocessing_missing.py +97 -0
  53. supervised/preprocessing/preprocessing_utils.py +136 -0
  54. supervised/preprocessing/scale.py +92 -0
  55. supervised/preprocessing/text_transformer.py +73 -0
  56. supervised/tuner/__init__.py +0 -0
  57. supervised/tuner/data_info.py +64 -0
  58. supervised/tuner/hill_climbing.py +80 -0
  59. supervised/tuner/mljar_tuner.py +1501 -0
  60. supervised/tuner/optuna/__init__.py +0 -0
  61. supervised/tuner/optuna/catboost.py +148 -0
  62. supervised/tuner/optuna/extra_trees.py +80 -0
  63. supervised/tuner/optuna/knn.py +64 -0
  64. supervised/tuner/optuna/lightgbm.py +165 -0
  65. supervised/tuner/optuna/nn.py +66 -0
  66. supervised/tuner/optuna/random_forest.py +77 -0
  67. supervised/tuner/optuna/tuner.py +335 -0
  68. supervised/tuner/optuna/xgboost.py +130 -0
  69. supervised/tuner/preprocessing_tuner.py +137 -0
  70. supervised/tuner/random_parameters.py +22 -0
  71. supervised/tuner/time_controller.py +273 -0
  72. supervised/utils/__init__.py +11 -0
  73. supervised/utils/additional_metrics.py +955 -0
  74. supervised/utils/additional_plots.py +228 -0
  75. supervised/utils/automl_plots.py +368 -0
  76. supervised/utils/common.py +39 -0
  77. supervised/utils/config.py +25 -0
  78. supervised/utils/constants.py +4 -0
  79. supervised/utils/data_validation.py +48 -0
  80. supervised/utils/importance.py +93 -0
  81. supervised/utils/jsonencoder.py +33 -0
  82. supervised/utils/leaderboard_plots.py +137 -0
  83. supervised/utils/learning_curves.py +145 -0
  84. supervised/utils/metric.py +450 -0
  85. supervised/utils/report_structured.py +525 -0
  86. supervised/utils/shap.py +373 -0
  87. supervised/utils/subsample.py +17 -0
  88. supervised/utils/utils.py +29 -0
  89. supervised/validation/__init__.py +0 -0
  90. supervised/validation/validation_step.py +37 -0
  91. supervised/validation/validator_base.py +17 -0
  92. supervised/validation/validator_custom.py +112 -0
  93. supervised/validation/validator_kfold.py +153 -0
  94. supervised/validation/validator_split.py +143 -0
@@ -0,0 +1,414 @@
1
+ import numpy as np
2
+
3
+
4
+ class FairnessOptimization:
5
+ @staticmethod
6
+ def binary_classification(
7
+ target,
8
+ predicted_labels,
9
+ sensitive_features,
10
+ fairness_metric,
11
+ fairness_threshold,
12
+ privileged_groups=[],
13
+ underprivileged_groups=[],
14
+ previous_fairness_optimization=None,
15
+ min_selection_rate=None,
16
+ max_selection_rate=None,
17
+ ):
18
+ target = np.array(target).ravel()
19
+ preds = np.array(predicted_labels)
20
+
21
+ # fairness optimization stats
22
+ sensitive_values = {}
23
+ for col in sensitive_features.columns:
24
+ col_name = col[10:] # skip 'senstive_'
25
+ values = list(sensitive_features[col].unique())
26
+ sensitive_values[col] = values
27
+
28
+ for v in values:
29
+ ii = sensitive_features[col] == v
30
+
31
+ new_sensitive_values = {}
32
+ for k, prev_values in sensitive_values.items():
33
+ if k == col:
34
+ continue
35
+ new_sensitive_values[f"{k}@{col}"] = []
36
+ for v in values:
37
+ for pv in prev_values:
38
+ if isinstance(pv, tuple):
39
+ new_sensitive_values[f"{k}@{col}"] += [(*pv, v)]
40
+ else:
41
+ new_sensitive_values[f"{k}@{col}"] += [(pv, v)]
42
+
43
+ sensitive_values = {**sensitive_values, **new_sensitive_values}
44
+
45
+ # print(sensitive_values)
46
+
47
+ sensitive_indices = {}
48
+ for k, values_list in sensitive_values.items():
49
+ if k.count("@") == sensitive_features.shape[1] - 1:
50
+ # print(k)
51
+ # print("values_list",values_list)
52
+ cols = k.split("@")
53
+ for values in values_list:
54
+ if not isinstance(values, tuple):
55
+ values = (values,)
56
+ # print("values", values)
57
+
58
+ ii = None
59
+ for i, c in enumerate(cols):
60
+ if ii is None:
61
+ ii = sensitive_features[c] == values[i]
62
+ else:
63
+ ii &= sensitive_features[c] == values[i]
64
+
65
+ key = "@".join([str(s) for s in values])
66
+ # print(key, np.sum(ii))
67
+ sensitive_indices[key] = ii
68
+
69
+ total_dp_ratio = min_selection_rate / max_selection_rate
70
+ # print("total dp ratio", total_dp_ratio)
71
+
72
+ c0 = np.sum(target == 0)
73
+ c1 = np.sum(target == 1)
74
+
75
+ selection_rates = {}
76
+ weights = {}
77
+
78
+ for key, indices in sensitive_indices.items():
79
+ selection_rates[key] = np.sum((preds == 1) & indices) / np.sum(indices)
80
+ # print(key, np.sum(indices), selection_rates[key])
81
+
82
+ t = np.sum(indices)
83
+ t0 = np.sum(indices & (target == 0))
84
+ t1 = np.sum(indices & (target == 1))
85
+
86
+ w0 = t / target.shape[0] * c0 / t0
87
+ w1 = t / target.shape[0] * c1 / t1
88
+
89
+ # print("----", key, w0, w1, t, t0, t1)
90
+ weights[key] = [w0, w1]
91
+
92
+ max_selection_rate = np.max(list(selection_rates.values()))
93
+ min_selection_rate = np.min(list(selection_rates.values()))
94
+
95
+ for k, v in selection_rates.items():
96
+ selection_rates[k] = v / max_selection_rate
97
+
98
+ # print("previous fairness optimization")
99
+ # print(previous_fairness_optimization)
100
+ # print("********")
101
+
102
+ previous_weights = {}
103
+ if previous_fairness_optimization is not None:
104
+ weights = previous_fairness_optimization.get("weights")
105
+ for key, indices in sensitive_indices.items():
106
+ # print("Previous")
107
+ # print(previous_fairness_optimization["selection_rates"][key], selection_rates[key])
108
+
109
+ direction = 0.0
110
+ if (
111
+ previous_fairness_optimization["selection_rates"][key]
112
+ < selection_rates[key]
113
+ ):
114
+ # print("Improvement")
115
+ direction = 1.0
116
+ elif selection_rates[key] > 0.8:
117
+ # print("GOOD")
118
+ direction = 0.0
119
+ else:
120
+ # print("Decrease")
121
+ direction = -0.5
122
+
123
+ # need to add previous weights instead 1.0
124
+ prev_weights = previous_fairness_optimization.get(
125
+ "previous_weights", {}
126
+ ).get(key, [1, 1])
127
+ # print("prev_weights", prev_weights)
128
+ delta0 = weights[key][0] - prev_weights[0]
129
+ delta1 = weights[key][1] - prev_weights[1]
130
+
131
+ previous_weights[key] = [weights[key][0], weights[key][1]]
132
+
133
+ # print("BEFORE")
134
+ # print(weights[key])
135
+ weights[key][0] += direction * delta0
136
+ weights[key][1] += direction * delta1
137
+ # print("AFTER")
138
+ # print(weights[key])
139
+ # print(previous_fairness_optimization["weights"][key])
140
+
141
+ step = None
142
+ if previous_fairness_optimization is not None:
143
+ step = previous_fairness_optimization.get("step")
144
+
145
+ if step is None:
146
+ step = 0
147
+ else:
148
+ step += 1
149
+
150
+ return {
151
+ "selection_rates": selection_rates,
152
+ "previous_weights": previous_weights,
153
+ "weights": weights,
154
+ "total_dp_ratio": total_dp_ratio,
155
+ "step": step,
156
+ "fairness_threshold": fairness_threshold,
157
+ }
158
+
159
+ @staticmethod
160
+ def regression(
161
+ target,
162
+ predictions,
163
+ sensitive_features,
164
+ fairness_metric,
165
+ fairness_threshold,
166
+ privileged_groups=[],
167
+ underprivileged_groups=[],
168
+ previous_fairness_optimization=None,
169
+ performance_metric=None,
170
+ performance_metric_name=None,
171
+ ):
172
+ target = np.array(target).ravel()
173
+ preds = np.array(predictions)
174
+
175
+ # fairness optimization stats
176
+ sensitive_values = {}
177
+ for col in sensitive_features.columns:
178
+ col_name = col[10:] # skip 'senstive_'
179
+ values = list(sensitive_features[col].unique())
180
+ sensitive_values[col] = values
181
+
182
+ for v in values:
183
+ ii = sensitive_features[col] == v
184
+
185
+ new_sensitive_values = {}
186
+ for k, prev_values in sensitive_values.items():
187
+ if k == col:
188
+ continue
189
+ new_sensitive_values[f"{k}@{col}"] = []
190
+ for v in values:
191
+ for pv in prev_values:
192
+ if isinstance(pv, tuple):
193
+ new_sensitive_values[f"{k}@{col}"] += [(*pv, v)]
194
+ else:
195
+ new_sensitive_values[f"{k}@{col}"] += [(pv, v)]
196
+
197
+ sensitive_values = {**sensitive_values, **new_sensitive_values}
198
+
199
+ sensitive_indices = {}
200
+ least_frequent_key = None
201
+ least_frequency = sensitive_features.shape[0]
202
+ for k, values_list in sensitive_values.items():
203
+ if k.count("@") == sensitive_features.shape[1] - 1:
204
+ # print(k)
205
+ # print("values_list",values_list)
206
+ cols = k.split("@")
207
+ for values in values_list:
208
+ if not isinstance(values, tuple):
209
+ values = (values,)
210
+ # print("values", values)
211
+
212
+ ii = None
213
+ for i, c in enumerate(cols):
214
+ if ii is None:
215
+ ii = sensitive_features[c] == values[i]
216
+ else:
217
+ ii &= sensitive_features[c] == values[i]
218
+
219
+ key = "@".join([str(s) for s in values])
220
+ if np.sum(ii) > 0:
221
+ sensitive_indices[key] = ii
222
+ if np.sum(ii) < least_frequency:
223
+ least_frequency = np.sum(ii)
224
+ least_frequent_key = key
225
+
226
+ weights = {}
227
+ performance = {}
228
+
229
+ for key, indices in sensitive_indices.items():
230
+ w = target.shape[0] / len(sensitive_indices) / np.sum(indices)
231
+ weights[key] = w
232
+ performance[key] = performance_metric(target[indices], predictions[indices])
233
+
234
+ # try to upscale more the largest weight
235
+ weights[least_frequent_key] *= 1.5
236
+
237
+ denominator = np.max(list(performance.values()))
238
+ new_performance = {}
239
+ for k, v in performance.items():
240
+ new_performance[k] = np.round(v / denominator, 4)
241
+ performance = new_performance
242
+
243
+ previous_weights = {}
244
+ if previous_fairness_optimization is not None:
245
+ weights = previous_fairness_optimization.get("weights")
246
+ for key, indices in sensitive_indices.items():
247
+ direction = 0.0
248
+ if (
249
+ previous_fairness_optimization["performance"][key]
250
+ < performance[key]
251
+ ):
252
+ direction = 1.0
253
+ elif performance[key] > fairness_threshold:
254
+ direction = 0.0
255
+ else:
256
+ direction = -0.5
257
+
258
+ # need to add previous weights instead 1.0
259
+ prev_weights = previous_fairness_optimization.get(
260
+ "previous_weights", {}
261
+ ).get(key, 1)
262
+ delta0 = weights[key] - prev_weights
263
+ previous_weights[key] = weights[key]
264
+ weights[key] = max(weights[key] + direction * delta0, 0.01)
265
+
266
+ no_weights_change = False
267
+ if str(previous_weights) == str(weights):
268
+ no_weights_change = True
269
+
270
+ step = None
271
+ if previous_fairness_optimization is not None:
272
+ step = previous_fairness_optimization.get("step")
273
+
274
+ if step is None:
275
+ step = 0
276
+ else:
277
+ if not no_weights_change:
278
+ step += 1
279
+
280
+ return {
281
+ "performance": performance,
282
+ "previous_weights": previous_weights,
283
+ "weights": weights,
284
+ "step": step,
285
+ "fairness_threshold": fairness_threshold,
286
+ }
287
+
288
+ @staticmethod
289
+ def multiclass_classification(
290
+ target,
291
+ predicted_labels,
292
+ sensitive_features,
293
+ fairness_metric,
294
+ fairness_threshold,
295
+ privileged_groups=[],
296
+ underprivileged_groups=[],
297
+ previous_fairness_optimization=None,
298
+ ):
299
+ target = np.array(target).ravel()
300
+ preds = np.array(predicted_labels)
301
+ target_values = list(np.unique(target))
302
+
303
+ # fairness optimization stats
304
+ sensitive_values = {}
305
+ for col in sensitive_features.columns:
306
+ col_name = col[10:] # skip 'senstive_'
307
+ values = list(sensitive_features[col].unique())
308
+ sensitive_values[col] = values
309
+ for v in values:
310
+ ii = sensitive_features[col] == v
311
+ new_sensitive_values = {}
312
+ for k, prev_values in sensitive_values.items():
313
+ if k == col:
314
+ continue
315
+ new_sensitive_values[f"{k}@{col}"] = []
316
+ for v in values:
317
+ for pv in prev_values:
318
+ if isinstance(pv, tuple):
319
+ new_sensitive_values[f"{k}@{col}"] += [(*pv, v)]
320
+ else:
321
+ new_sensitive_values[f"{k}@{col}"] += [(pv, v)]
322
+
323
+ sensitive_values = {**sensitive_values, **new_sensitive_values}
324
+
325
+ sensitive_indices = {}
326
+ for k, values_list in sensitive_values.items():
327
+ if k.count("@") == sensitive_features.shape[1] - 1:
328
+ cols = k.split("@")
329
+ for values in values_list:
330
+ if not isinstance(values, tuple):
331
+ values = (values,)
332
+
333
+ ii = None
334
+ for i, c in enumerate(cols):
335
+ if ii is None:
336
+ ii = sensitive_features[c] == values[i]
337
+ else:
338
+ ii &= sensitive_features[c] == values[i]
339
+
340
+ key = "@".join([str(s) for s in values])
341
+ sensitive_indices[key] = ii
342
+
343
+ cs = {}
344
+ for t in target_values:
345
+ cs[t] = np.sum(target == t)
346
+ selection_rates = {}
347
+ weights = {}
348
+
349
+ for key, indices in sensitive_indices.items():
350
+ weights[key] = []
351
+ sv = np.sum(indices)
352
+ selection_rates[key] = {}
353
+ for t in target_values:
354
+ selection_rates[key][t] = np.sum((preds == t) & indices) / np.sum(
355
+ indices
356
+ )
357
+
358
+ t_k = np.sum(indices & (target == t))
359
+ w_k = sv / target.shape[0] * cs[t] / t_k
360
+ weights[key] += [w_k]
361
+
362
+ for t in target_values:
363
+ values = []
364
+ for k, v in selection_rates.items():
365
+ values += [v[t]]
366
+ max_selection_rate = np.max(values)
367
+ for k, v in selection_rates.items():
368
+ v[t] /= max_selection_rate
369
+
370
+ previous_weights = {}
371
+ if previous_fairness_optimization is not None:
372
+ weights = previous_fairness_optimization.get("weights")
373
+ for key, indices in sensitive_indices.items():
374
+ previous_weights[key] = [1] * len(target_values)
375
+ for i, t in enumerate(target_values):
376
+ direction = 0.0
377
+ if (
378
+ previous_fairness_optimization["selection_rates"][key][t]
379
+ < selection_rates[key][t]
380
+ ):
381
+ direction = 1.0
382
+ elif selection_rates[key][t] > 0.8:
383
+ direction = 0.0
384
+ else:
385
+ direction = -0.5
386
+
387
+ # need to add previous weights instead 1.0
388
+ prev_weights = previous_fairness_optimization.get(
389
+ "previous_weights", {}
390
+ ).get(key, [1] * len(target_values))
391
+
392
+ delta_i = weights[key][i] - prev_weights[i]
393
+
394
+ previous_weights[key][i] = weights[key][i]
395
+
396
+ weights[key][i] += direction * delta_i
397
+
398
+ step = None
399
+ if previous_fairness_optimization is not None:
400
+ step = previous_fairness_optimization.get("step")
401
+
402
+ if step is None:
403
+ step = 0
404
+ else:
405
+ step += 1
406
+
407
+ return {
408
+ "selection_rates": selection_rates,
409
+ "previous_weights": previous_weights,
410
+ "weights": weights,
411
+ "step": step,
412
+ "fairness_threshold": fairness_threshold,
413
+ "target_values": target_values,
414
+ }
@@ -0,0 +1,131 @@
1
+ import numpy as np
2
+ from matplotlib import pyplot as plt
3
+
4
+
5
+ class FairnessPlots:
6
+ @staticmethod
7
+ def binary_classification(
8
+ fairness_metric,
9
+ col_name,
10
+ metrics,
11
+ selection_rates,
12
+ max_selection_rate,
13
+ fairness_threshold,
14
+ ):
15
+ figures = []
16
+ # selection rate figure
17
+ fair_selection_rate = max_selection_rate * fairness_threshold
18
+
19
+ fig = plt.figure(figsize=(10, 7))
20
+ ax1 = fig.add_subplot(1, 1, 1)
21
+ bars = ax1.bar(metrics.index[1:], metrics["Selection Rate"][1:])
22
+
23
+ ax1.spines[["right", "top", "left"]].set_visible(False)
24
+ ax1.yaxis.set_visible(False)
25
+ _ = ax1.bar_label(bars, padding=5)
26
+
27
+ if fairness_metric == "demographic_parity_ratio":
28
+ ax1.axhline(y=fair_selection_rate, zorder=0, color="grey", ls="--", lw=1.5)
29
+ _ = ax1.text(
30
+ y=fair_selection_rate,
31
+ x=-0.6,
32
+ s="Fairness threshold",
33
+ ha="center",
34
+ fontsize=12,
35
+ bbox=dict(facecolor="white", edgecolor="grey", ls="--"),
36
+ )
37
+ _ = ax1.text(
38
+ y=1.2 * fair_selection_rate,
39
+ x=-0.6,
40
+ s="Fair",
41
+ ha="center",
42
+ fontsize=12,
43
+ )
44
+ _ = ax1.text(
45
+ y=0.8 * fair_selection_rate,
46
+ x=-0.6,
47
+ s="Unfair",
48
+ ha="center",
49
+ fontsize=12,
50
+ )
51
+
52
+ ax1.axhspan(
53
+ fairness_threshold * max_selection_rate,
54
+ 1.25 * np.max(selection_rates[1:]),
55
+ color="green",
56
+ alpha=0.05,
57
+ )
58
+ ax1.axhspan(
59
+ 0, fairness_threshold * max_selection_rate, color="red", alpha=0.05
60
+ )
61
+
62
+ figures += [
63
+ {
64
+ "title": f"Selection Rate for {col_name}",
65
+ "fname": f"selection_rate_{col_name}.png",
66
+ "figure": fig,
67
+ }
68
+ ]
69
+
70
+ fig, axes = plt.subplots(figsize=(10, 5), ncols=2, sharey=True)
71
+ fig.tight_layout()
72
+ bars = axes[0].barh(
73
+ metrics.index[1:],
74
+ metrics["False Negative Rate"][1:],
75
+ zorder=10,
76
+ color="tab:orange",
77
+ )
78
+ xmax = 1.2 * max(
79
+ metrics["False Negative Rate"][1:].max(),
80
+ metrics["False Positive Rate"][1:].max(),
81
+ )
82
+ axes[0].set_xlim(0, xmax)
83
+ axes[0].invert_xaxis()
84
+ axes[0].set_title("False Negative Rate")
85
+ _ = axes[0].bar_label(bars, padding=5)
86
+
87
+ bars = axes[1].barh(
88
+ metrics.index[1:],
89
+ metrics["False Positive Rate"][1:],
90
+ zorder=10,
91
+ color="tab:blue",
92
+ )
93
+ axes[1].tick_params(axis="y", colors="tab:orange") # tick color
94
+ axes[1].set_xlim(0, xmax)
95
+ axes[1].set_title("False Positive Rate")
96
+ _ = axes[1].bar_label(bars, padding=5)
97
+ _ = plt.subplots_adjust(wspace=0, top=0.85, bottom=0.1, left=0.18, right=0.95)
98
+
99
+ figures += [
100
+ {
101
+ "title": f"False Rates for {col_name}",
102
+ "fname": f"false_rates_{col_name}.png",
103
+ "figure": fig,
104
+ }
105
+ ]
106
+
107
+ return figures
108
+
109
+ @staticmethod
110
+ def regression(fairness_metric, col_name, metrics, fairness_metric_name):
111
+ figures = []
112
+ metric_name = fairness_metric.split("@")[1].upper()
113
+
114
+ fig = plt.figure(figsize=(10, 7))
115
+ ax1 = fig.add_subplot(1, 1, 1)
116
+ bars = ax1.bar(metrics.index[1:], metrics[metric_name][1:])
117
+
118
+ ax1.spines[["right", "top"]].set_visible(False)
119
+ # ax1.yaxis.set_visible(False)
120
+ ax1.set_ylabel(metric_name)
121
+ _ = ax1.bar_label(bars, padding=5)
122
+
123
+ figures += [
124
+ {
125
+ "title": f"{metric_name} for {col_name}",
126
+ "fname": f"{metric_name}_{col_name}.png",
127
+ "figure": fig,
128
+ }
129
+ ]
130
+
131
+ return figures
@@ -0,0 +1,116 @@
1
+ import os
2
+
3
+
4
+ class FairnessReport:
5
+ """Saves information about fairness in the report."""
6
+
7
+ @staticmethod
8
+ def save_classification(fairness_metrics, fout, model_path, is_multi=False):
9
+ for k, v in fairness_metrics.items():
10
+ if k == "fairness_optimization":
11
+ continue
12
+
13
+ if is_multi:
14
+ a = k.split("__", maxsplit=1)
15
+ feature, class_name = a
16
+
17
+ if is_multi:
18
+ fout.write(
19
+ f"\n\n## Fairness metrics for {feature} feature and {class_name} class\n\n"
20
+ )
21
+ else:
22
+ fout.write(f"\n\n## Fairness metrics for {k} feature\n\n")
23
+
24
+ fout.write(v["metrics"].to_markdown())
25
+ fout.write("\n\n")
26
+ fout.write(v["stats"].to_markdown())
27
+ fout.write("\n\n")
28
+
29
+ if is_multi:
30
+ fout.write(
31
+ f"\n\n## Is model fair for {feature} feature and {class_name} class?\n"
32
+ )
33
+ else:
34
+ fout.write(f"\n\n## Is model fair for {k} feature?\n")
35
+ fair_str = "fair" if v["is_fair"] else "unfair"
36
+ fairness_threshold = fairness_metrics.get("fairness_optimization", {}).get(
37
+ "fairness_threshold"
38
+ )
39
+ fairness_threshold_str = ""
40
+ if fairness_threshold is not None:
41
+ if "ratio" in v["fairness_metric_name"].lower():
42
+ fairness_threshold_str = (
43
+ f"It should be higher than {fairness_threshold}."
44
+ )
45
+ else:
46
+ fairness_threshold_str = (
47
+ f"It should be lower than {fairness_threshold}."
48
+ )
49
+
50
+ if is_multi:
51
+ fout.write(
52
+ f"Model is {fair_str} for {feature} feature and {class_name} class.\n"
53
+ )
54
+ else:
55
+ fout.write(f"Model is {fair_str} for {k} feature.\n")
56
+ fout.write(
57
+ f'The {v["fairness_metric_name"]} is {v["fairness_metric_value"]}. {fairness_threshold_str}\n'
58
+ )
59
+ if not v["is_fair"]:
60
+ # display information about privileged and underprivileged groups
61
+ # for unfair models
62
+ if v.get("underprivileged_value") is not None:
63
+ fout.write(
64
+ f'Underprivileged value is {v["underprivileged_value"]}.\n'
65
+ )
66
+ if v.get("privileged_value") is not None:
67
+ fout.write(f'Privileged value is {v["privileged_value"]}.\n')
68
+
69
+ for figure in v["figures"]:
70
+ fout.write(f"\n\n### {figure['title']}\n\n")
71
+ figure["figure"].savefig(os.path.join(model_path, figure["fname"]))
72
+ fout.write(f"\n![]({figure['fname']})\n\n")
73
+
74
+ @staticmethod
75
+ def regression(fairness_metrics, fout, model_path):
76
+ for k, v in fairness_metrics.items():
77
+ if k == "fairness_optimization":
78
+ continue
79
+ fout.write(f"\n\n## Fairness metrics for {k} feature\n\n")
80
+
81
+ fout.write(v["metrics"].to_markdown())
82
+ fout.write("\n\n")
83
+
84
+ fout.write(f'Privileged value: {v["privileged_value"]}\n\n')
85
+ fout.write(f'Underprivileged value: {v["underprivileged_value"]}\n\n\n')
86
+ fout.write(f'Fairness metric: {v["fairness_metric_name"]}\n\n')
87
+ fout.write(f'{v["metric_name"]} Difference: {v["diff"]}\n\n')
88
+ fout.write(f'{v["metric_name"]} Ratio: {v["ratio"]}\n\n')
89
+
90
+ # add sentence about model fairness
91
+ if v["is_fair"]:
92
+ fout.write(f"Model is fair for {k} feature.\n")
93
+ if "ratio" in v["fairness_metric_name"].lower():
94
+ fout.write(
95
+ f"The {v['fairness_metric_name']} value is above threshold {v['fairness_threshold']}.\n\n"
96
+ )
97
+ else:
98
+ fout.write(
99
+ f"The {v['fairness_metric_name']} value is below threshold {v['fairness_threshold']}.\n\n"
100
+ )
101
+ else:
102
+ # model is not fair
103
+ fout.write(f"Model is unfair for {k} feature.\n")
104
+ if "ratio" in v["fairness_metric_name"].lower():
105
+ fout.write(
106
+ f"The {v['fairness_metric_name']} value is below threshold {v['fairness_threshold']}.\n\n"
107
+ )
108
+ else:
109
+ fout.write(
110
+ f"The {v['fairness_metric_name']} value is above threshold {v['fairness_threshold']}.\n\n"
111
+ )
112
+
113
+ for figure in v["figures"]:
114
+ fout.write(f"\n\n### {figure['title']}\n\n")
115
+ figure["figure"].savefig(os.path.join(model_path, figure["fname"]))
116
+ fout.write(f"\n![]({figure['fname']})\n\n")
@@ -0,0 +1,40 @@
1
+ import numpy as np
2
+
3
+
4
+ def accuracy(t, y):
5
+ return np.round(np.sum(t == y) / t.shape[0], 4)
6
+
7
+
8
+ def selection_rate(y):
9
+ return np.round(
10
+ np.sum((y == 1)) / y.shape[0],
11
+ 4,
12
+ )
13
+
14
+
15
+ def true_positive_rate(t, y):
16
+ return np.round(
17
+ np.sum((y == 1) & (t == 1)) / np.sum((t == 1)),
18
+ 4,
19
+ )
20
+
21
+
22
+ def false_positive_rate(t, y):
23
+ return np.round(
24
+ np.sum((y == 1) & (t == 0)) / np.sum((t == 0)),
25
+ 4,
26
+ )
27
+
28
+
29
+ def true_negative_rate(t, y):
30
+ return np.round(
31
+ np.sum((y == 0) & (t == 0)) / np.sum((t == 0)),
32
+ 4,
33
+ )
34
+
35
+
36
+ def false_negative_rate(t, y):
37
+ return np.round(
38
+ np.sum((y == 0) & (t == 1)) / np.sum((t == 1)),
39
+ 4,
40
+ )