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.
- mljar_supervised-1.2.1.dist-info/METADATA +657 -0
- mljar_supervised-1.2.1.dist-info/RECORD +94 -0
- mljar_supervised-1.2.1.dist-info/WHEEL +5 -0
- mljar_supervised-1.2.1.dist-info/licenses/LICENSE +21 -0
- mljar_supervised-1.2.1.dist-info/top_level.txt +1 -0
- supervised/__init__.py +14 -0
- supervised/algorithms/__init__.py +0 -0
- supervised/algorithms/algorithm.py +151 -0
- supervised/algorithms/baseline.py +90 -0
- supervised/algorithms/catboost.py +436 -0
- supervised/algorithms/decision_tree.py +305 -0
- supervised/algorithms/extra_trees.py +176 -0
- supervised/algorithms/factory.py +28 -0
- supervised/algorithms/knn.py +137 -0
- supervised/algorithms/lightgbm.py +406 -0
- supervised/algorithms/linear.py +211 -0
- supervised/algorithms/nn.py +180 -0
- supervised/algorithms/random_forest.py +181 -0
- supervised/algorithms/registry.py +76 -0
- supervised/algorithms/sklearn.py +197 -0
- supervised/algorithms/xgboost.py +413 -0
- supervised/automl.py +568 -0
- supervised/base_automl.py +2542 -0
- supervised/callbacks/__init__.py +0 -0
- supervised/callbacks/callback.py +25 -0
- supervised/callbacks/callback_list.py +33 -0
- supervised/callbacks/early_stopping.py +213 -0
- supervised/callbacks/learner_time_constraint.py +47 -0
- supervised/callbacks/max_iters_constraint.py +16 -0
- supervised/callbacks/metric_logger.py +48 -0
- supervised/callbacks/terminate_on_nan.py +28 -0
- supervised/callbacks/total_time_constraint.py +79 -0
- supervised/ensemble.py +583 -0
- supervised/exceptions.py +21 -0
- supervised/fairness/__init__.py +0 -0
- supervised/fairness/metrics.py +654 -0
- supervised/fairness/optimization.py +414 -0
- supervised/fairness/plots.py +131 -0
- supervised/fairness/report.py +116 -0
- supervised/fairness/utils.py +40 -0
- supervised/model_framework.py +734 -0
- supervised/preprocessing/__init__.py +0 -0
- supervised/preprocessing/datetime_transformer.py +106 -0
- supervised/preprocessing/encoding_selector.py +30 -0
- supervised/preprocessing/exclude_missing_target.py +46 -0
- supervised/preprocessing/goldenfeatures_transformer.py +310 -0
- supervised/preprocessing/kmeans_transformer.py +115 -0
- supervised/preprocessing/label_binarizer.py +81 -0
- supervised/preprocessing/label_encoder.py +54 -0
- supervised/preprocessing/preprocessing.py +652 -0
- supervised/preprocessing/preprocessing_categorical.py +117 -0
- supervised/preprocessing/preprocessing_missing.py +97 -0
- supervised/preprocessing/preprocessing_utils.py +136 -0
- supervised/preprocessing/scale.py +92 -0
- supervised/preprocessing/text_transformer.py +73 -0
- supervised/tuner/__init__.py +0 -0
- supervised/tuner/data_info.py +64 -0
- supervised/tuner/hill_climbing.py +80 -0
- supervised/tuner/mljar_tuner.py +1501 -0
- supervised/tuner/optuna/__init__.py +0 -0
- supervised/tuner/optuna/catboost.py +148 -0
- supervised/tuner/optuna/extra_trees.py +80 -0
- supervised/tuner/optuna/knn.py +64 -0
- supervised/tuner/optuna/lightgbm.py +165 -0
- supervised/tuner/optuna/nn.py +66 -0
- supervised/tuner/optuna/random_forest.py +77 -0
- supervised/tuner/optuna/tuner.py +335 -0
- supervised/tuner/optuna/xgboost.py +130 -0
- supervised/tuner/preprocessing_tuner.py +137 -0
- supervised/tuner/random_parameters.py +22 -0
- supervised/tuner/time_controller.py +273 -0
- supervised/utils/__init__.py +11 -0
- supervised/utils/additional_metrics.py +955 -0
- supervised/utils/additional_plots.py +228 -0
- supervised/utils/automl_plots.py +368 -0
- supervised/utils/common.py +39 -0
- supervised/utils/config.py +25 -0
- supervised/utils/constants.py +4 -0
- supervised/utils/data_validation.py +48 -0
- supervised/utils/importance.py +93 -0
- supervised/utils/jsonencoder.py +33 -0
- supervised/utils/leaderboard_plots.py +137 -0
- supervised/utils/learning_curves.py +145 -0
- supervised/utils/metric.py +450 -0
- supervised/utils/report_structured.py +525 -0
- supervised/utils/shap.py +373 -0
- supervised/utils/subsample.py +17 -0
- supervised/utils/utils.py +29 -0
- supervised/validation/__init__.py +0 -0
- supervised/validation/validation_step.py +37 -0
- supervised/validation/validator_base.py +17 -0
- supervised/validation/validator_custom.py +112 -0
- supervised/validation/validator_kfold.py +153 -0
- supervised/validation/validator_split.py +143 -0
|
@@ -0,0 +1,955 @@
|
|
|
1
|
+
import json
|
|
2
|
+
import logging
|
|
3
|
+
import os
|
|
4
|
+
import warnings
|
|
5
|
+
|
|
6
|
+
import numpy as np
|
|
7
|
+
import pandas as pd
|
|
8
|
+
from sklearn.metrics import (
|
|
9
|
+
accuracy_score,
|
|
10
|
+
classification_report,
|
|
11
|
+
confusion_matrix,
|
|
12
|
+
f1_score,
|
|
13
|
+
matthews_corrcoef,
|
|
14
|
+
mean_absolute_error,
|
|
15
|
+
mean_absolute_percentage_error,
|
|
16
|
+
mean_squared_error,
|
|
17
|
+
precision_score,
|
|
18
|
+
r2_score,
|
|
19
|
+
recall_score,
|
|
20
|
+
roc_auc_score,
|
|
21
|
+
)
|
|
22
|
+
|
|
23
|
+
from supervised.algorithms.registry import (
|
|
24
|
+
BINARY_CLASSIFICATION,
|
|
25
|
+
MULTICLASS_CLASSIFICATION,
|
|
26
|
+
REGRESSION,
|
|
27
|
+
)
|
|
28
|
+
from supervised.utils.metric import logloss
|
|
29
|
+
|
|
30
|
+
logger = logging.getLogger(__name__)
|
|
31
|
+
from supervised.utils.config import LOG_LEVEL
|
|
32
|
+
|
|
33
|
+
logger.setLevel(LOG_LEVEL)
|
|
34
|
+
from tabulate import tabulate
|
|
35
|
+
|
|
36
|
+
from supervised.fairness.metrics import FairnessMetrics
|
|
37
|
+
from supervised.fairness.report import FairnessReport
|
|
38
|
+
from supervised.utils.additional_plots import AdditionalPlots
|
|
39
|
+
from supervised.utils.common import construct_learner_name, get_fold_repeat_cnt
|
|
40
|
+
from supervised.utils.learning_curves import LearningCurves
|
|
41
|
+
from supervised.utils.jsonencoder import MLJSONEncoder
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
class AdditionalMetrics:
|
|
45
|
+
@staticmethod
|
|
46
|
+
def binary_classification(
|
|
47
|
+
target,
|
|
48
|
+
predictions,
|
|
49
|
+
sample_weight=None,
|
|
50
|
+
sensitive_features=None,
|
|
51
|
+
fairness_metric=None,
|
|
52
|
+
fairness_threshold=None,
|
|
53
|
+
privileged_groups=[],
|
|
54
|
+
underprivileged_groups=[],
|
|
55
|
+
previous_fairness_optimization=None,
|
|
56
|
+
):
|
|
57
|
+
negative_label, positive_label = "0", "1"
|
|
58
|
+
mapping = None
|
|
59
|
+
try:
|
|
60
|
+
pred_col = predictions.columns[0]
|
|
61
|
+
if "_0_for_" in pred_col and "_1_for_" in pred_col:
|
|
62
|
+
t = pred_col.split("_0_for_")[1]
|
|
63
|
+
t = t.split("_1_for_")
|
|
64
|
+
negative_label, positive_label = t[0], t[1]
|
|
65
|
+
mapping = {0: negative_label, 1: positive_label}
|
|
66
|
+
except Exception as e:
|
|
67
|
+
pass
|
|
68
|
+
|
|
69
|
+
predictions = np.array(predictions).flatten()
|
|
70
|
+
sorted_predictions = np.sort(predictions)
|
|
71
|
+
|
|
72
|
+
STEPS = 100 # can go lower for speed increase ???
|
|
73
|
+
details = {
|
|
74
|
+
"threshold": [],
|
|
75
|
+
"f1": [],
|
|
76
|
+
"accuracy": [],
|
|
77
|
+
"precision": [],
|
|
78
|
+
"recall": [],
|
|
79
|
+
"mcc": [],
|
|
80
|
+
}
|
|
81
|
+
samples_per_step = max(1, np.floor(predictions.shape[0] / STEPS))
|
|
82
|
+
|
|
83
|
+
for i in range(STEPS):
|
|
84
|
+
idx = int(i * samples_per_step)
|
|
85
|
+
if idx + 1 >= predictions.shape[0]:
|
|
86
|
+
break
|
|
87
|
+
if i == 0:
|
|
88
|
+
th = 0.9 * np.min(sorted_predictions)
|
|
89
|
+
else:
|
|
90
|
+
th = float(
|
|
91
|
+
0.5 * (sorted_predictions[idx] + sorted_predictions[idx + 1])
|
|
92
|
+
)
|
|
93
|
+
|
|
94
|
+
if np.sum(predictions > th) < 1:
|
|
95
|
+
break
|
|
96
|
+
response = (predictions > th).astype(int)
|
|
97
|
+
|
|
98
|
+
details["threshold"] += [th]
|
|
99
|
+
details["f1"] += [f1_score(target, response, sample_weight=sample_weight)]
|
|
100
|
+
details["accuracy"] += [
|
|
101
|
+
accuracy_score(target, response, sample_weight=sample_weight)
|
|
102
|
+
]
|
|
103
|
+
details["precision"] += [
|
|
104
|
+
precision_score(target, response, sample_weight=sample_weight)
|
|
105
|
+
]
|
|
106
|
+
details["recall"] += [
|
|
107
|
+
recall_score(target, response, sample_weight=sample_weight)
|
|
108
|
+
]
|
|
109
|
+
if i == 0:
|
|
110
|
+
details["mcc"] += [0.0]
|
|
111
|
+
else:
|
|
112
|
+
details["mcc"] += [
|
|
113
|
+
matthews_corrcoef(target, response, sample_weight=sample_weight)
|
|
114
|
+
]
|
|
115
|
+
|
|
116
|
+
# max metrics
|
|
117
|
+
max_metrics = {
|
|
118
|
+
"logloss": {
|
|
119
|
+
"score": logloss(target, predictions, sample_weight=sample_weight),
|
|
120
|
+
"threshold": None,
|
|
121
|
+
}, # there is no threshold for LogLoss
|
|
122
|
+
"auc": {
|
|
123
|
+
"score": roc_auc_score(
|
|
124
|
+
target, predictions, sample_weight=sample_weight
|
|
125
|
+
),
|
|
126
|
+
"threshold": None,
|
|
127
|
+
}, # there is no threshold for AUC
|
|
128
|
+
"f1": {
|
|
129
|
+
"score": np.max(details["f1"]),
|
|
130
|
+
"threshold": details["threshold"][np.argmax(details["f1"])],
|
|
131
|
+
},
|
|
132
|
+
"accuracy": {
|
|
133
|
+
"score": np.max(details["accuracy"]),
|
|
134
|
+
"threshold": details["threshold"][np.argmax(details["accuracy"])],
|
|
135
|
+
},
|
|
136
|
+
"precision": {
|
|
137
|
+
"score": np.max(details["precision"]),
|
|
138
|
+
"threshold": details["threshold"][np.argmax(details["precision"])],
|
|
139
|
+
},
|
|
140
|
+
"recall": {
|
|
141
|
+
"score": np.max(details["recall"]),
|
|
142
|
+
"threshold": details["threshold"][np.argmax(details["recall"])],
|
|
143
|
+
},
|
|
144
|
+
"mcc": {
|
|
145
|
+
"score": np.max(details["mcc"]),
|
|
146
|
+
"threshold": details["threshold"][np.argmax(details["mcc"])],
|
|
147
|
+
},
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
threshold = float(max_metrics["accuracy"]["threshold"])
|
|
151
|
+
|
|
152
|
+
# updating resopnse variable for accuracy metric
|
|
153
|
+
response = (predictions > threshold).astype(int)
|
|
154
|
+
|
|
155
|
+
# accuracy threshold metrics
|
|
156
|
+
accuracy_threshold_metrics = {
|
|
157
|
+
"logloss": {
|
|
158
|
+
"score": logloss(target, predictions, sample_weight=sample_weight),
|
|
159
|
+
"threshold": None,
|
|
160
|
+
}, # there is no threshold for LogLoss
|
|
161
|
+
"auc": {
|
|
162
|
+
"score": roc_auc_score(
|
|
163
|
+
target, predictions, sample_weight=sample_weight
|
|
164
|
+
),
|
|
165
|
+
"threshold": None,
|
|
166
|
+
}, # there is no threshold for AUC
|
|
167
|
+
"f1": {
|
|
168
|
+
"score": f1_score(target, response, sample_weight=sample_weight),
|
|
169
|
+
"threshold": threshold,
|
|
170
|
+
},
|
|
171
|
+
"accuracy": {
|
|
172
|
+
"score": accuracy_score(target, response, sample_weight=sample_weight),
|
|
173
|
+
"threshold": threshold,
|
|
174
|
+
},
|
|
175
|
+
"precision": {
|
|
176
|
+
"score": precision_score(target, response, sample_weight=sample_weight),
|
|
177
|
+
"threshold": threshold,
|
|
178
|
+
},
|
|
179
|
+
"recall": {
|
|
180
|
+
"score": recall_score(target, response, sample_weight=sample_weight),
|
|
181
|
+
"threshold": threshold,
|
|
182
|
+
},
|
|
183
|
+
"mcc": {
|
|
184
|
+
"score": matthews_corrcoef(
|
|
185
|
+
target, response, sample_weight=sample_weight
|
|
186
|
+
),
|
|
187
|
+
"threshold": threshold,
|
|
188
|
+
},
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
# if sample_weight is not None:
|
|
192
|
+
# new_max_metrics = {}
|
|
193
|
+
# for k, v in max_metrics.items():
|
|
194
|
+
# new_max_metrics["weighted_" + k] = v
|
|
195
|
+
# max_metrics = new_max_metrics
|
|
196
|
+
|
|
197
|
+
# confusion matrix
|
|
198
|
+
|
|
199
|
+
conf_matrix = confusion_matrix(
|
|
200
|
+
target, predictions > threshold, sample_weight=sample_weight
|
|
201
|
+
)
|
|
202
|
+
|
|
203
|
+
conf_matrix = pd.DataFrame(
|
|
204
|
+
conf_matrix,
|
|
205
|
+
columns=[
|
|
206
|
+
f"Predicted as {negative_label}",
|
|
207
|
+
f"Predicted as {positive_label}",
|
|
208
|
+
],
|
|
209
|
+
index=[f"Labeled as {negative_label}", f"Labeled as {positive_label}"],
|
|
210
|
+
)
|
|
211
|
+
|
|
212
|
+
predicted_labels = pd.Series((predictions.ravel() > threshold).astype(int))
|
|
213
|
+
predicted_labels_01 = predicted_labels.copy()
|
|
214
|
+
predicted_probas = pd.DataFrame(
|
|
215
|
+
{"proba_0": 1 - predictions.ravel(), "proba_1": predictions.ravel()}
|
|
216
|
+
)
|
|
217
|
+
|
|
218
|
+
if mapping is not None:
|
|
219
|
+
labeled_target = target["target"].map(mapping)
|
|
220
|
+
predicted_labels = predicted_labels.map(mapping)
|
|
221
|
+
else:
|
|
222
|
+
labeled_target = target
|
|
223
|
+
|
|
224
|
+
metrics = {
|
|
225
|
+
"metric_details": pd.DataFrame(details),
|
|
226
|
+
"max_metrics": pd.DataFrame(max_metrics),
|
|
227
|
+
"accuracy_threshold_metrics": pd.DataFrame(accuracy_threshold_metrics),
|
|
228
|
+
"confusion_matrix": conf_matrix,
|
|
229
|
+
"threshold": threshold,
|
|
230
|
+
"additional_plots": AdditionalPlots.plots_binary(
|
|
231
|
+
labeled_target, predicted_labels, predicted_probas
|
|
232
|
+
),
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
if sensitive_features is not None:
|
|
236
|
+
metrics["fairness_metrics"] = FairnessMetrics.binary_classification(
|
|
237
|
+
target,
|
|
238
|
+
predicted_labels_01,
|
|
239
|
+
sensitive_features,
|
|
240
|
+
fairness_metric,
|
|
241
|
+
fairness_threshold,
|
|
242
|
+
privileged_groups,
|
|
243
|
+
underprivileged_groups,
|
|
244
|
+
previous_fairness_optimization,
|
|
245
|
+
)
|
|
246
|
+
|
|
247
|
+
return metrics
|
|
248
|
+
|
|
249
|
+
@staticmethod
|
|
250
|
+
def multiclass_classification(
|
|
251
|
+
target,
|
|
252
|
+
predictions,
|
|
253
|
+
sample_weight=None,
|
|
254
|
+
sensitive_features=None,
|
|
255
|
+
fairness_metric=None,
|
|
256
|
+
fairness_threshold=None,
|
|
257
|
+
privileged_groups=[],
|
|
258
|
+
underprivileged_groups=[],
|
|
259
|
+
previous_fairness_optimization=None,
|
|
260
|
+
):
|
|
261
|
+
all_labels = [i[11:] for i in predictions.columns.tolist()[:-1]]
|
|
262
|
+
|
|
263
|
+
predicted_probas = predictions[predictions.columns[:-1]]
|
|
264
|
+
ll = logloss(
|
|
265
|
+
target, predictions[predictions.columns[:-1]], sample_weight=sample_weight
|
|
266
|
+
)
|
|
267
|
+
|
|
268
|
+
if "target" in target.columns.tolist():
|
|
269
|
+
# multiclass coding with integer
|
|
270
|
+
labels = {i: l for i, l in enumerate(all_labels)}
|
|
271
|
+
target = target["target"].map(labels)
|
|
272
|
+
else:
|
|
273
|
+
# multiclass coding with one-hot encoding
|
|
274
|
+
old_columns = target.columns
|
|
275
|
+
t = target[old_columns[0]]
|
|
276
|
+
for l in all_labels:
|
|
277
|
+
t[target[f"target_{l}"] == 1] = l
|
|
278
|
+
|
|
279
|
+
target = pd.DataFrame({"target": t})
|
|
280
|
+
|
|
281
|
+
# Print the confusion matrix
|
|
282
|
+
predicted_labels = predictions["label"]
|
|
283
|
+
predictions = predictions["label"]
|
|
284
|
+
if not pd.api.types.is_string_dtype(predictions):
|
|
285
|
+
predictions = predictions.astype(str)
|
|
286
|
+
|
|
287
|
+
if not pd.api.types.is_string_dtype(target):
|
|
288
|
+
target = target.astype(str)
|
|
289
|
+
|
|
290
|
+
conf_matrix = confusion_matrix(
|
|
291
|
+
target, predictions, labels=all_labels, sample_weight=sample_weight
|
|
292
|
+
)
|
|
293
|
+
|
|
294
|
+
rows = [f"Predicted as {a}" for a in all_labels]
|
|
295
|
+
cols = [f"Labeled as {a}" for a in all_labels]
|
|
296
|
+
|
|
297
|
+
conf_matrix = pd.DataFrame(conf_matrix, columns=rows, index=cols)
|
|
298
|
+
|
|
299
|
+
max_metrics = classification_report(
|
|
300
|
+
target,
|
|
301
|
+
predictions,
|
|
302
|
+
digits=6,
|
|
303
|
+
labels=all_labels,
|
|
304
|
+
output_dict=True,
|
|
305
|
+
sample_weight=sample_weight,
|
|
306
|
+
)
|
|
307
|
+
max_metrics["logloss"] = ll
|
|
308
|
+
|
|
309
|
+
metrics = {
|
|
310
|
+
"max_metrics": pd.DataFrame(max_metrics).transpose(),
|
|
311
|
+
"confusion_matrix": conf_matrix,
|
|
312
|
+
"additional_plots": AdditionalPlots.plots_multiclass(
|
|
313
|
+
target, predicted_labels, predicted_probas
|
|
314
|
+
),
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
if sensitive_features is not None:
|
|
318
|
+
metrics["fairness_metrics"] = FairnessMetrics.multiclass_classification(
|
|
319
|
+
target,
|
|
320
|
+
predicted_labels,
|
|
321
|
+
sensitive_features,
|
|
322
|
+
fairness_metric,
|
|
323
|
+
fairness_threshold,
|
|
324
|
+
privileged_groups,
|
|
325
|
+
underprivileged_groups,
|
|
326
|
+
previous_fairness_optimization,
|
|
327
|
+
)
|
|
328
|
+
return metrics
|
|
329
|
+
|
|
330
|
+
@staticmethod
|
|
331
|
+
def regression(
|
|
332
|
+
target,
|
|
333
|
+
predictions,
|
|
334
|
+
sample_weight=None,
|
|
335
|
+
sensitive_features=None,
|
|
336
|
+
fairness_metric=None,
|
|
337
|
+
fairness_threshold=None,
|
|
338
|
+
privileged_groups=[],
|
|
339
|
+
underprivileged_groups=[],
|
|
340
|
+
previous_fairness_optimization=None,
|
|
341
|
+
):
|
|
342
|
+
regression_metrics = {
|
|
343
|
+
"MAE": mean_absolute_error,
|
|
344
|
+
"MSE": mean_squared_error,
|
|
345
|
+
"RMSE": lambda t, p, sample_weight: np.sqrt(
|
|
346
|
+
mean_squared_error(t, p, sample_weight=sample_weight)
|
|
347
|
+
),
|
|
348
|
+
"R2": r2_score,
|
|
349
|
+
"MAPE": mean_absolute_percentage_error,
|
|
350
|
+
}
|
|
351
|
+
max_metrics = {}
|
|
352
|
+
for k, v in regression_metrics.items():
|
|
353
|
+
max_metrics[k] = v(target, predictions, sample_weight=sample_weight)
|
|
354
|
+
|
|
355
|
+
metrics = {
|
|
356
|
+
"max_metrics": pd.DataFrame(
|
|
357
|
+
{
|
|
358
|
+
"Metric": list(max_metrics.keys()),
|
|
359
|
+
"Score": list(max_metrics.values()),
|
|
360
|
+
}
|
|
361
|
+
),
|
|
362
|
+
"additional_plots": AdditionalPlots.plots_regression(target, predictions),
|
|
363
|
+
}
|
|
364
|
+
|
|
365
|
+
if sensitive_features is not None:
|
|
366
|
+
metrics["fairness_metrics"] = FairnessMetrics.regression(
|
|
367
|
+
target,
|
|
368
|
+
predictions,
|
|
369
|
+
sensitive_features,
|
|
370
|
+
fairness_metric,
|
|
371
|
+
fairness_threshold,
|
|
372
|
+
privileged_groups,
|
|
373
|
+
underprivileged_groups,
|
|
374
|
+
previous_fairness_optimization,
|
|
375
|
+
)
|
|
376
|
+
|
|
377
|
+
return metrics
|
|
378
|
+
|
|
379
|
+
@staticmethod
|
|
380
|
+
def compute(
|
|
381
|
+
target,
|
|
382
|
+
predictions,
|
|
383
|
+
sample_weight,
|
|
384
|
+
ml_task,
|
|
385
|
+
sensitive_features=None,
|
|
386
|
+
fairness_metric=None,
|
|
387
|
+
fairness_threshold=None,
|
|
388
|
+
privileged_groups=[],
|
|
389
|
+
underprivileged_groups=[],
|
|
390
|
+
previous_fairness_optimization=None,
|
|
391
|
+
):
|
|
392
|
+
with warnings.catch_warnings():
|
|
393
|
+
warnings.simplefilter("ignore")
|
|
394
|
+
if ml_task == BINARY_CLASSIFICATION:
|
|
395
|
+
return AdditionalMetrics.binary_classification(
|
|
396
|
+
target,
|
|
397
|
+
predictions,
|
|
398
|
+
sample_weight,
|
|
399
|
+
sensitive_features,
|
|
400
|
+
fairness_metric,
|
|
401
|
+
fairness_threshold,
|
|
402
|
+
privileged_groups,
|
|
403
|
+
underprivileged_groups,
|
|
404
|
+
previous_fairness_optimization,
|
|
405
|
+
)
|
|
406
|
+
elif ml_task == MULTICLASS_CLASSIFICATION:
|
|
407
|
+
return AdditionalMetrics.multiclass_classification(
|
|
408
|
+
target,
|
|
409
|
+
predictions,
|
|
410
|
+
sample_weight,
|
|
411
|
+
sensitive_features,
|
|
412
|
+
fairness_metric,
|
|
413
|
+
fairness_threshold,
|
|
414
|
+
privileged_groups,
|
|
415
|
+
underprivileged_groups,
|
|
416
|
+
previous_fairness_optimization,
|
|
417
|
+
)
|
|
418
|
+
elif ml_task == REGRESSION:
|
|
419
|
+
return AdditionalMetrics.regression(
|
|
420
|
+
target,
|
|
421
|
+
predictions,
|
|
422
|
+
sample_weight,
|
|
423
|
+
sensitive_features,
|
|
424
|
+
fairness_metric,
|
|
425
|
+
fairness_threshold,
|
|
426
|
+
privileged_groups,
|
|
427
|
+
underprivileged_groups,
|
|
428
|
+
previous_fairness_optimization,
|
|
429
|
+
)
|
|
430
|
+
|
|
431
|
+
@staticmethod
|
|
432
|
+
def save(additional_metrics, ml_task, model_desc, model_path):
|
|
433
|
+
try:
|
|
434
|
+
fold_cnt, repeat_cnt = get_fold_repeat_cnt(model_path)
|
|
435
|
+
if ml_task == BINARY_CLASSIFICATION:
|
|
436
|
+
AdditionalMetrics.save_binary_classification(
|
|
437
|
+
additional_metrics, model_desc, model_path, fold_cnt, repeat_cnt
|
|
438
|
+
)
|
|
439
|
+
elif ml_task == MULTICLASS_CLASSIFICATION:
|
|
440
|
+
AdditionalMetrics.save_multiclass_classification(
|
|
441
|
+
additional_metrics, model_desc, model_path, fold_cnt, repeat_cnt
|
|
442
|
+
)
|
|
443
|
+
elif ml_task == REGRESSION:
|
|
444
|
+
AdditionalMetrics.save_regression(
|
|
445
|
+
additional_metrics, model_desc, model_path, fold_cnt, repeat_cnt
|
|
446
|
+
)
|
|
447
|
+
except Exception as e:
|
|
448
|
+
logger.exception(
|
|
449
|
+
f"Exception while saving additional metrics. {str(e)}\nContinuing ..."
|
|
450
|
+
)
|
|
451
|
+
|
|
452
|
+
@staticmethod
|
|
453
|
+
def add_learning_curves(fout):
|
|
454
|
+
fout.write("\n\n## Learning curves\n")
|
|
455
|
+
fout.write(f"")
|
|
456
|
+
|
|
457
|
+
@staticmethod
|
|
458
|
+
def save_binary_classification(
|
|
459
|
+
additional_metrics, model_desc, model_path, fold_cnt, repeat_cnt
|
|
460
|
+
):
|
|
461
|
+
max_metrics = additional_metrics["max_metrics"].transpose()
|
|
462
|
+
accuracy_threshold_metrics = additional_metrics[
|
|
463
|
+
"accuracy_threshold_metrics"
|
|
464
|
+
].transpose()
|
|
465
|
+
confusion_matrix = additional_metrics["confusion_matrix"]
|
|
466
|
+
threshold = additional_metrics["threshold"]
|
|
467
|
+
|
|
468
|
+
fairness_metrics = additional_metrics.get("fairness_metrics")
|
|
469
|
+
|
|
470
|
+
with open(os.path.join(model_path, "README.md"), "w", encoding="utf-8") as fout:
|
|
471
|
+
fout.write(model_desc)
|
|
472
|
+
fout.write("\n## Metric details\n{}\n\n".format(max_metrics.to_markdown()))
|
|
473
|
+
fout.write(
|
|
474
|
+
"\n## Metric details with threshold from accuracy metric\n{}\n\n".format(
|
|
475
|
+
accuracy_threshold_metrics.to_markdown()
|
|
476
|
+
)
|
|
477
|
+
)
|
|
478
|
+
fout.write(
|
|
479
|
+
"\n## Confusion matrix (at threshold={})\n{}".format(
|
|
480
|
+
np.round(threshold, 6), confusion_matrix.to_markdown()
|
|
481
|
+
)
|
|
482
|
+
)
|
|
483
|
+
|
|
484
|
+
if fairness_metrics is not None:
|
|
485
|
+
FairnessReport.save_classification(
|
|
486
|
+
fairness_metrics, fout, model_path, is_multi=False
|
|
487
|
+
)
|
|
488
|
+
|
|
489
|
+
AdditionalMetrics.add_learning_curves(fout)
|
|
490
|
+
AdditionalMetrics.add_tree_viz(fout, model_path, fold_cnt, repeat_cnt)
|
|
491
|
+
AdditionalMetrics.add_linear_coefs(fout, model_path, fold_cnt, repeat_cnt)
|
|
492
|
+
AdditionalMetrics.add_permutation_importance(
|
|
493
|
+
fout, model_path, fold_cnt, repeat_cnt
|
|
494
|
+
)
|
|
495
|
+
|
|
496
|
+
plots = additional_metrics.get("additional_plots")
|
|
497
|
+
if plots is not None:
|
|
498
|
+
AdditionalPlots.append(fout, model_path, plots)
|
|
499
|
+
|
|
500
|
+
AdditionalMetrics.add_shap_importance(
|
|
501
|
+
fout, model_path, fold_cnt, repeat_cnt
|
|
502
|
+
)
|
|
503
|
+
AdditionalMetrics.add_shap_binary(fout, model_path, fold_cnt, repeat_cnt)
|
|
504
|
+
|
|
505
|
+
fout.write("\n\n[<< Go back](../README.md)\n")
|
|
506
|
+
|
|
507
|
+
@staticmethod
|
|
508
|
+
def save_multiclass_classification(
|
|
509
|
+
additional_metrics, model_desc, model_path, fold_cnt, repeat_cnt
|
|
510
|
+
):
|
|
511
|
+
max_metrics = additional_metrics["max_metrics"].transpose()
|
|
512
|
+
confusion_matrix = additional_metrics["confusion_matrix"]
|
|
513
|
+
|
|
514
|
+
fairness_metrics = additional_metrics.get("fairness_metrics")
|
|
515
|
+
|
|
516
|
+
with open(os.path.join(model_path, "README.md"), "w", encoding="utf-8") as fout:
|
|
517
|
+
fout.write(model_desc)
|
|
518
|
+
fout.write("\n### Metric details\n{}\n\n".format(max_metrics.to_markdown()))
|
|
519
|
+
fout.write(
|
|
520
|
+
"\n## Confusion matrix\n{}".format(confusion_matrix.to_markdown())
|
|
521
|
+
)
|
|
522
|
+
|
|
523
|
+
if fairness_metrics is not None:
|
|
524
|
+
# we treat multiclass problem as several binary problems
|
|
525
|
+
FairnessReport.save_classification(
|
|
526
|
+
fairness_metrics, fout, model_path, is_multi=True
|
|
527
|
+
)
|
|
528
|
+
|
|
529
|
+
AdditionalMetrics.add_learning_curves(fout)
|
|
530
|
+
AdditionalMetrics.add_tree_viz(fout, model_path, fold_cnt, repeat_cnt)
|
|
531
|
+
AdditionalMetrics.add_linear_coefs(fout, model_path, fold_cnt, repeat_cnt)
|
|
532
|
+
AdditionalMetrics.add_permutation_importance(
|
|
533
|
+
fout, model_path, fold_cnt, repeat_cnt
|
|
534
|
+
)
|
|
535
|
+
|
|
536
|
+
plots = additional_metrics.get("additional_plots")
|
|
537
|
+
if plots is not None:
|
|
538
|
+
AdditionalPlots.append(fout, model_path, plots)
|
|
539
|
+
|
|
540
|
+
AdditionalMetrics.add_shap_importance(
|
|
541
|
+
fout, model_path, fold_cnt, repeat_cnt
|
|
542
|
+
)
|
|
543
|
+
AdditionalMetrics.add_shap_multiclass(
|
|
544
|
+
fout, model_path, fold_cnt, repeat_cnt
|
|
545
|
+
)
|
|
546
|
+
|
|
547
|
+
fout.write("\n\n[<< Go back](../README.md)\n")
|
|
548
|
+
|
|
549
|
+
@staticmethod
|
|
550
|
+
def save_regression(
|
|
551
|
+
additional_metrics, model_desc, model_path, fold_cnt, repeat_cnt
|
|
552
|
+
):
|
|
553
|
+
max_metrics = additional_metrics["max_metrics"]
|
|
554
|
+
fairness_metrics = additional_metrics.get("fairness_metrics")
|
|
555
|
+
|
|
556
|
+
with open(os.path.join(model_path, "README.md"), "w", encoding="utf-8") as fout:
|
|
557
|
+
fout.write(model_desc)
|
|
558
|
+
fout.write(
|
|
559
|
+
"\n### Metric details:\n{}\n\n".format(
|
|
560
|
+
tabulate(max_metrics.values, max_metrics.columns, tablefmt="pipe")
|
|
561
|
+
)
|
|
562
|
+
)
|
|
563
|
+
|
|
564
|
+
if fairness_metrics is not None:
|
|
565
|
+
FairnessReport.regression(fairness_metrics, fout, model_path)
|
|
566
|
+
|
|
567
|
+
AdditionalMetrics.add_learning_curves(fout)
|
|
568
|
+
AdditionalMetrics.add_tree_viz(fout, model_path, fold_cnt, repeat_cnt)
|
|
569
|
+
AdditionalMetrics.add_linear_coefs(fout, model_path, fold_cnt, repeat_cnt)
|
|
570
|
+
AdditionalMetrics.add_permutation_importance(
|
|
571
|
+
fout, model_path, fold_cnt, repeat_cnt
|
|
572
|
+
)
|
|
573
|
+
|
|
574
|
+
plots = additional_metrics.get("additional_plots")
|
|
575
|
+
if plots is not None:
|
|
576
|
+
AdditionalPlots.append(fout, model_path, plots)
|
|
577
|
+
|
|
578
|
+
AdditionalMetrics.add_shap_importance(
|
|
579
|
+
fout, model_path, fold_cnt, repeat_cnt
|
|
580
|
+
)
|
|
581
|
+
AdditionalMetrics.add_shap_regression(
|
|
582
|
+
fout, model_path, fold_cnt, repeat_cnt
|
|
583
|
+
)
|
|
584
|
+
|
|
585
|
+
fout.write("\n\n[<< Go back](../README.md)\n")
|
|
586
|
+
|
|
587
|
+
@staticmethod
|
|
588
|
+
def add_linear_coefs(fout, model_path, fold_cnt, repeat_cnt):
|
|
589
|
+
coef_files = [f for f in os.listdir(model_path) if "_coefs.csv" in f]
|
|
590
|
+
if not len(coef_files):
|
|
591
|
+
return
|
|
592
|
+
|
|
593
|
+
# check if multiclass
|
|
594
|
+
df = pd.read_csv(os.path.join(model_path, coef_files[0]), index_col=0)
|
|
595
|
+
if df.shape[0] > 100:
|
|
596
|
+
return
|
|
597
|
+
multiclass = df.shape[1] > 1
|
|
598
|
+
|
|
599
|
+
if multiclass:
|
|
600
|
+
fout.write("\n\n## Coefficients\n")
|
|
601
|
+
|
|
602
|
+
for repeat in range(repeat_cnt):
|
|
603
|
+
repeat_str = f", repeat #{repeat+1}" if repeat_cnt > 1 else ""
|
|
604
|
+
for fold in range(fold_cnt):
|
|
605
|
+
learner_name = construct_learner_name(fold, repeat, repeat_cnt)
|
|
606
|
+
fname = learner_name + "_coefs.csv"
|
|
607
|
+
if fname in coef_files:
|
|
608
|
+
fout.write(
|
|
609
|
+
f"\n### Coefficients learner #{fold+1}{repeat_str}\n"
|
|
610
|
+
)
|
|
611
|
+
df = pd.read_csv(os.path.join(model_path, fname), index_col=0)
|
|
612
|
+
fout.write(df.to_markdown() + "\n")
|
|
613
|
+
|
|
614
|
+
else:
|
|
615
|
+
df_all = []
|
|
616
|
+
for repeat in range(repeat_cnt):
|
|
617
|
+
repeat_str = f"_Repeat_{repeat+1}" if repeat_cnt > 1 else ""
|
|
618
|
+
for fold in range(fold_cnt):
|
|
619
|
+
learner_name = construct_learner_name(fold, repeat, repeat_cnt)
|
|
620
|
+
fname = learner_name + "_coefs.csv"
|
|
621
|
+
if fname in coef_files:
|
|
622
|
+
df = pd.read_csv(os.path.join(model_path, fname), index_col=0)
|
|
623
|
+
df.columns = [f"Learner_{fold+1}{repeat_str}"]
|
|
624
|
+
df_all += [df]
|
|
625
|
+
|
|
626
|
+
df = pd.concat(df_all, axis=1)
|
|
627
|
+
df["m"] = df.mean(axis=1)
|
|
628
|
+
|
|
629
|
+
df = df.sort_values("m", axis=0, ascending=False)
|
|
630
|
+
df = df.drop("m", axis=1)
|
|
631
|
+
|
|
632
|
+
fout.write("\n\n## Coefficients\n")
|
|
633
|
+
fout.write(df.to_markdown() + "\n")
|
|
634
|
+
|
|
635
|
+
@staticmethod
|
|
636
|
+
def add_tree_viz(fout, model_path, fold_cnt, repeat_cnt):
|
|
637
|
+
tree_viz = [f for f in os.listdir(model_path) if "_tree.svg" in f]
|
|
638
|
+
if len(tree_viz):
|
|
639
|
+
fout.write("\n\n## Decision Tree \n")
|
|
640
|
+
for repeat in range(repeat_cnt):
|
|
641
|
+
repeat_str = f", Repeat #{repeat+1}" if repeat_cnt > 1 else ""
|
|
642
|
+
for fold in range(fold_cnt):
|
|
643
|
+
learner_name = construct_learner_name(fold, repeat, repeat_cnt)
|
|
644
|
+
fname = learner_name + "_tree.svg"
|
|
645
|
+
if fname in tree_viz:
|
|
646
|
+
fout.write(f"\n### Tree #{fold+1}{repeat_str}\n")
|
|
647
|
+
fout.write(f"")
|
|
648
|
+
try:
|
|
649
|
+
fname = os.path.join(model_path, learner_name + "_rules.txt")
|
|
650
|
+
if os.path.exists(fname):
|
|
651
|
+
fout.write("\n\n### Rules\n\n")
|
|
652
|
+
with open(fname, "r") as fin:
|
|
653
|
+
fout.write(fin.read() + "\n\n")
|
|
654
|
+
except Exception as e:
|
|
655
|
+
logger.info("Problem with adding rules to report. " + str(e))
|
|
656
|
+
|
|
657
|
+
@staticmethod
|
|
658
|
+
def add_permutation_importance(fout, model_path, fold_cnt, repeat_cnt):
|
|
659
|
+
# permutation importance
|
|
660
|
+
imp_data = [
|
|
661
|
+
f
|
|
662
|
+
for f in os.listdir(model_path)
|
|
663
|
+
if "_importance.csv" in f and "shap" not in f
|
|
664
|
+
]
|
|
665
|
+
if not len(imp_data):
|
|
666
|
+
return
|
|
667
|
+
|
|
668
|
+
df_all = []
|
|
669
|
+
for repeat in range(repeat_cnt):
|
|
670
|
+
repeat_str = f", Repeat {repeat+1}" if repeat_cnt > 1 else ""
|
|
671
|
+
for fold in range(fold_cnt):
|
|
672
|
+
learner_name = construct_learner_name(fold, repeat, repeat_cnt)
|
|
673
|
+
fname = learner_name + "_importance.csv"
|
|
674
|
+
if fname in imp_data:
|
|
675
|
+
df = pd.read_csv(os.path.join(model_path, fname), index_col=0)
|
|
676
|
+
df.columns = [f"Learner {fold+1}{repeat_str}"]
|
|
677
|
+
df_all += [df]
|
|
678
|
+
|
|
679
|
+
df = pd.concat(df_all, axis=1)
|
|
680
|
+
|
|
681
|
+
df["m"] = df.mean(axis=1)
|
|
682
|
+
df = df.sort_values(by="m", ascending=False)
|
|
683
|
+
df = df.drop("m", axis=1)
|
|
684
|
+
|
|
685
|
+
# limit to max 25 features in the plot
|
|
686
|
+
ax = df.head(25).plot.barh(figsize=(10, 7))
|
|
687
|
+
ax.invert_yaxis()
|
|
688
|
+
ax.set_xlabel("Mean of feature importance")
|
|
689
|
+
fig = ax.get_figure()
|
|
690
|
+
fig.tight_layout(pad=2.0)
|
|
691
|
+
if df.shape[0] > 25:
|
|
692
|
+
ax.set_title("Top-25 important features")
|
|
693
|
+
else:
|
|
694
|
+
ax.set_title("Feature importance")
|
|
695
|
+
|
|
696
|
+
fig.savefig(os.path.join(model_path, "permutation_importance.png"))
|
|
697
|
+
fout.write("\n\n## Permutation-based Importance\n")
|
|
698
|
+
fout.write(f"")
|
|
699
|
+
|
|
700
|
+
if "random_feature" in df.index.tolist():
|
|
701
|
+
df["counter"] = 0
|
|
702
|
+
df = df.fillna(
|
|
703
|
+
0
|
|
704
|
+
) # there might be not-used features between different learners
|
|
705
|
+
max_counter = 0.0
|
|
706
|
+
for col in df.columns:
|
|
707
|
+
if "Learner" not in col:
|
|
708
|
+
continue
|
|
709
|
+
score = max(0, df[col]["random_feature"]) + 1e-6
|
|
710
|
+
df["counter"] += (df[col] <= score).astype(int)
|
|
711
|
+
max_counter += 1.0
|
|
712
|
+
|
|
713
|
+
""" version 1
|
|
714
|
+
df["min_score"] = df.min(axis=1)
|
|
715
|
+
df["max_score"] = df.max(axis=1)
|
|
716
|
+
random_feature_score = max(
|
|
717
|
+
0.0, float(df["max_score"]["random_feature"])
|
|
718
|
+
) # it should be at least 0
|
|
719
|
+
drop_features = df.index[
|
|
720
|
+
df["min_score"] < random_feature_score + 1e-6
|
|
721
|
+
].tolist()
|
|
722
|
+
"""
|
|
723
|
+
|
|
724
|
+
# version 2 - should be better
|
|
725
|
+
threshold = max_counter / 2.0
|
|
726
|
+
drop_features = df.index[df["counter"] >= threshold].tolist()
|
|
727
|
+
|
|
728
|
+
fname = os.path.join(os.path.dirname(model_path), "drop_features.json")
|
|
729
|
+
with open(fname, "w") as fout:
|
|
730
|
+
fout.write(json.dumps(drop_features, indent=4, cls=MLJSONEncoder))
|
|
731
|
+
|
|
732
|
+
fname = os.path.join(
|
|
733
|
+
os.path.dirname(model_path),
|
|
734
|
+
f"features_scores_threshold_{threshold}.csv",
|
|
735
|
+
)
|
|
736
|
+
df.to_csv(fname, index=False)
|
|
737
|
+
|
|
738
|
+
@staticmethod
|
|
739
|
+
def add_shap_importance(fout, model_path, fold_cnt, repeat_cnt):
|
|
740
|
+
try:
|
|
741
|
+
# SHAP Importance
|
|
742
|
+
imp_data = [
|
|
743
|
+
f for f in os.listdir(model_path) if "_shap_importance.csv" in f
|
|
744
|
+
]
|
|
745
|
+
if not len(imp_data):
|
|
746
|
+
return
|
|
747
|
+
|
|
748
|
+
df_all = []
|
|
749
|
+
for repeat in range(repeat_cnt):
|
|
750
|
+
repeat_str = f", Repeat {repeat+1}" if repeat_cnt > 1 else ""
|
|
751
|
+
for fold in range(fold_cnt):
|
|
752
|
+
learner_name = construct_learner_name(fold, repeat, repeat_cnt)
|
|
753
|
+
fname = learner_name + "_shap_importance.csv"
|
|
754
|
+
if fname in imp_data:
|
|
755
|
+
df = pd.read_csv(os.path.join(model_path, fname), index_col=0)
|
|
756
|
+
df.columns = [f"Learner {fold+1}{repeat_str}"]
|
|
757
|
+
df_all += [df]
|
|
758
|
+
|
|
759
|
+
df = pd.concat(df_all, axis=1)
|
|
760
|
+
|
|
761
|
+
df["m"] = df.mean(axis=1)
|
|
762
|
+
df = df.sort_values(by="m", ascending=False)
|
|
763
|
+
df = df.drop("m", axis=1)
|
|
764
|
+
|
|
765
|
+
# limit to max 25 features in the plot
|
|
766
|
+
ax = df.head(25).plot.barh(figsize=(10, 7))
|
|
767
|
+
ax.invert_yaxis()
|
|
768
|
+
ax.set_xlabel("mean(|SHAP value|) average impact on model output magnitude")
|
|
769
|
+
fig = ax.get_figure()
|
|
770
|
+
fig.tight_layout(pad=2.0)
|
|
771
|
+
if df.shape[0] > 25:
|
|
772
|
+
ax.set_title("SHAP Top-25 important features")
|
|
773
|
+
else:
|
|
774
|
+
ax.set_title("SHAP feature importance")
|
|
775
|
+
fig.savefig(os.path.join(model_path, "shap_importance.png"))
|
|
776
|
+
fout.write("\n\n## SHAP Importance\n")
|
|
777
|
+
fout.write(f"")
|
|
778
|
+
except Exception as e:
|
|
779
|
+
logger.error(
|
|
780
|
+
f"Exception while saving SHAP importance. {str(e)}\nContinuing ..."
|
|
781
|
+
)
|
|
782
|
+
|
|
783
|
+
@staticmethod
|
|
784
|
+
def add_shap_binary(fout, model_path, fold_cnt, repeat_cnt):
|
|
785
|
+
try:
|
|
786
|
+
# Dependence SHAP
|
|
787
|
+
dep_plots = [
|
|
788
|
+
f for f in os.listdir(model_path) if "_shap_dependence.png" in f
|
|
789
|
+
]
|
|
790
|
+
if not len(dep_plots):
|
|
791
|
+
return
|
|
792
|
+
|
|
793
|
+
fout.write("\n\n## SHAP Dependence plots\n")
|
|
794
|
+
for repeat in range(repeat_cnt):
|
|
795
|
+
repeat_str = f", Repeat {repeat+1}" if repeat_cnt > 1 else ""
|
|
796
|
+
for fold in range(fold_cnt):
|
|
797
|
+
learner_name = construct_learner_name(fold, repeat, repeat_cnt)
|
|
798
|
+
fname = learner_name + "_shap_dependence.png"
|
|
799
|
+
if fname in dep_plots:
|
|
800
|
+
fout.write(f"\n### Dependence (Fold {fold+1}{repeat_str})\n")
|
|
801
|
+
fout.write(
|
|
802
|
+
f""
|
|
803
|
+
)
|
|
804
|
+
|
|
805
|
+
# SHAP Decisions
|
|
806
|
+
dec_plots = [
|
|
807
|
+
f
|
|
808
|
+
for f in os.listdir(model_path)
|
|
809
|
+
if "_shap_class" in f and "decisions.png" in f
|
|
810
|
+
]
|
|
811
|
+
if not len(dec_plots):
|
|
812
|
+
return
|
|
813
|
+
|
|
814
|
+
fout.write("\n\n## SHAP Decision plots\n")
|
|
815
|
+
for target in [0, 1]:
|
|
816
|
+
for decision_type in ["worst", "best"]:
|
|
817
|
+
for repeat in range(repeat_cnt):
|
|
818
|
+
repeat_str = f", Repeat {repeat+1}" if repeat_cnt > 1 else ""
|
|
819
|
+
for fold in range(fold_cnt):
|
|
820
|
+
learner_name = construct_learner_name(
|
|
821
|
+
fold, repeat, repeat_cnt
|
|
822
|
+
)
|
|
823
|
+
fname = (
|
|
824
|
+
learner_name
|
|
825
|
+
+ f"_shap_class_{target}_{decision_type}_decisions.png"
|
|
826
|
+
)
|
|
827
|
+
if fname in dec_plots:
|
|
828
|
+
fout.write(
|
|
829
|
+
f"\n### Top-10 {decision_type.capitalize()} decisions for class {target} (Fold {fold+1}{repeat_str})\n"
|
|
830
|
+
)
|
|
831
|
+
fout.write(
|
|
832
|
+
f""
|
|
833
|
+
)
|
|
834
|
+
|
|
835
|
+
except Exception as e:
|
|
836
|
+
logger.error(
|
|
837
|
+
f"Exception while saving SHAP explanations. {str(e)}\nContinuing ..."
|
|
838
|
+
)
|
|
839
|
+
|
|
840
|
+
@staticmethod
|
|
841
|
+
def add_shap_regression(fout, model_path, fold_cnt, repeat_cnt):
|
|
842
|
+
try:
|
|
843
|
+
# Dependence SHAP
|
|
844
|
+
dep_plots = [
|
|
845
|
+
f for f in os.listdir(model_path) if "_shap_dependence.png" in f
|
|
846
|
+
]
|
|
847
|
+
if not len(dep_plots):
|
|
848
|
+
return
|
|
849
|
+
|
|
850
|
+
fout.write("\n\n## SHAP Dependence plots\n")
|
|
851
|
+
for repeat in range(repeat_cnt):
|
|
852
|
+
repeat_str = f", Repeat {repeat+1}" if repeat_cnt > 1 else ""
|
|
853
|
+
for fold in range(fold_cnt):
|
|
854
|
+
learner_name = construct_learner_name(fold, repeat, repeat_cnt)
|
|
855
|
+
fname = learner_name + "_shap_dependence.png"
|
|
856
|
+
if fname in dep_plots:
|
|
857
|
+
fout.write(f"\n### Dependence (Fold {fold+1}{repeat_str})\n")
|
|
858
|
+
fout.write(
|
|
859
|
+
f""
|
|
860
|
+
)
|
|
861
|
+
|
|
862
|
+
# SHAP Decisions
|
|
863
|
+
dec_plots = [f for f in os.listdir(model_path) if "decisions.png" in f]
|
|
864
|
+
if not len(dec_plots):
|
|
865
|
+
return
|
|
866
|
+
|
|
867
|
+
fout.write("\n\n## SHAP Decision plots\n")
|
|
868
|
+
for decision_type in ["worst", "best"]:
|
|
869
|
+
for repeat in range(repeat_cnt):
|
|
870
|
+
repeat_str = f", Repeat {repeat+1}" if repeat_cnt > 1 else ""
|
|
871
|
+
for fold in range(fold_cnt):
|
|
872
|
+
learner_name = construct_learner_name(fold, repeat, repeat_cnt)
|
|
873
|
+
fname = learner_name + f"_shap_{decision_type}_decisions.png"
|
|
874
|
+
if fname in dec_plots:
|
|
875
|
+
fout.write(
|
|
876
|
+
f"\n### Top-10 {decision_type.capitalize()} decisions (Fold {fold+1}{repeat_str})\n"
|
|
877
|
+
)
|
|
878
|
+
fout.write(
|
|
879
|
+
f""
|
|
880
|
+
)
|
|
881
|
+
except Exception as e:
|
|
882
|
+
logger.error(
|
|
883
|
+
f"Exception while saving SHAP explanations. {str(e)}\nContinuing ..."
|
|
884
|
+
)
|
|
885
|
+
|
|
886
|
+
@staticmethod
|
|
887
|
+
def add_shap_multiclass(fout, model_path, fold_cnt, repeat_cnt):
|
|
888
|
+
try:
|
|
889
|
+
# Dependence SHAP
|
|
890
|
+
dep_plots = [f for f in os.listdir(model_path) if "_shap_dependence" in f]
|
|
891
|
+
if not len(dep_plots):
|
|
892
|
+
return
|
|
893
|
+
|
|
894
|
+
# get number of classes
|
|
895
|
+
start_ind = 0
|
|
896
|
+
for i, a in enumerate(dep_plots[0].split("_")):
|
|
897
|
+
if a == "class":
|
|
898
|
+
start_ind = i + 1
|
|
899
|
+
break
|
|
900
|
+
|
|
901
|
+
classes = []
|
|
902
|
+
for l in dep_plots:
|
|
903
|
+
a = l.split("_")
|
|
904
|
+
classes += ["".join(a[start_ind:])[:-4]]
|
|
905
|
+
classes = np.unique(classes)
|
|
906
|
+
|
|
907
|
+
fout.write("\n\n## SHAP Dependence plots\n")
|
|
908
|
+
|
|
909
|
+
for repeat in range(repeat_cnt):
|
|
910
|
+
repeat_str = f", Repeat {repeat+1}" if repeat_cnt > 1 else ""
|
|
911
|
+
for fold in range(fold_cnt):
|
|
912
|
+
learner_name = construct_learner_name(fold, repeat, repeat_cnt)
|
|
913
|
+
for t in classes:
|
|
914
|
+
fname = learner_name + f"_shap_dependence_class_{t}.png"
|
|
915
|
+
if fname in dep_plots:
|
|
916
|
+
fout.write(
|
|
917
|
+
f"\n### Dependence {t} (Fold {fold+1}{repeat_str})\n"
|
|
918
|
+
)
|
|
919
|
+
fout.write(
|
|
920
|
+
f""
|
|
921
|
+
)
|
|
922
|
+
|
|
923
|
+
# SHAP Decisions
|
|
924
|
+
dec_plots = [
|
|
925
|
+
f
|
|
926
|
+
for f in os.listdir(model_path)
|
|
927
|
+
if "_sample_" in f and "decisions.png" in f
|
|
928
|
+
]
|
|
929
|
+
if not len(dec_plots):
|
|
930
|
+
return
|
|
931
|
+
|
|
932
|
+
fout.write("\n\n## SHAP Decision plots\n")
|
|
933
|
+
for decision_type in ["worst", "best"]:
|
|
934
|
+
for sample in [0, 1, 2, 3]:
|
|
935
|
+
for repeat in range(repeat_cnt):
|
|
936
|
+
repeat_str = f", Repeat {repeat+1}" if repeat_cnt > 1 else ""
|
|
937
|
+
for fold in range(fold_cnt):
|
|
938
|
+
learner_name = construct_learner_name(
|
|
939
|
+
fold, repeat, repeat_cnt
|
|
940
|
+
)
|
|
941
|
+
fname = (
|
|
942
|
+
learner_name
|
|
943
|
+
+ f"_sample_{sample}_{decision_type}_decisions.png"
|
|
944
|
+
)
|
|
945
|
+
if fname in dec_plots:
|
|
946
|
+
fout.write(
|
|
947
|
+
f"\n### {decision_type.capitalize()} decisions for selected sample {sample+1} (Fold {fold+1}{repeat_str})\n"
|
|
948
|
+
)
|
|
949
|
+
fout.write(
|
|
950
|
+
f""
|
|
951
|
+
)
|
|
952
|
+
except Exception as e:
|
|
953
|
+
logger.error(
|
|
954
|
+
f"Exception while saving SHAP explanations. {str(e)}\nContinuing ..."
|
|
955
|
+
)
|