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,734 @@
|
|
|
1
|
+
import copy
|
|
2
|
+
import gc
|
|
3
|
+
import json
|
|
4
|
+
import logging
|
|
5
|
+
import os
|
|
6
|
+
import time
|
|
7
|
+
import uuid
|
|
8
|
+
|
|
9
|
+
import numpy as np
|
|
10
|
+
import pandas as pd
|
|
11
|
+
|
|
12
|
+
from supervised.algorithms.factory import AlgorithmFactory
|
|
13
|
+
from supervised.algorithms.registry import (
|
|
14
|
+
BINARY_CLASSIFICATION,
|
|
15
|
+
MULTICLASS_CLASSIFICATION,
|
|
16
|
+
REGRESSION,
|
|
17
|
+
AlgorithmsRegistry,
|
|
18
|
+
)
|
|
19
|
+
from supervised.callbacks.callback_list import CallbackList
|
|
20
|
+
from supervised.exceptions import AutoMLException
|
|
21
|
+
from supervised.preprocessing.preprocessing import Preprocessing
|
|
22
|
+
from supervised.utils.additional_metrics import AdditionalMetrics
|
|
23
|
+
from supervised.utils.config import LOG_LEVEL
|
|
24
|
+
from supervised.utils.jsonencoder import MLJSONEncoder
|
|
25
|
+
from supervised.utils.metric import Metric
|
|
26
|
+
from supervised.validation.validation_step import ValidationStep
|
|
27
|
+
|
|
28
|
+
logger = logging.getLogger(__name__)
|
|
29
|
+
logger.setLevel(LOG_LEVEL)
|
|
30
|
+
|
|
31
|
+
import joblib
|
|
32
|
+
|
|
33
|
+
from supervised.tuner.optuna.tuner import OptunaTuner
|
|
34
|
+
from supervised.utils.learning_curves import LearningCurves
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
class ModelFramework:
|
|
38
|
+
def __init__(self, params, callbacks=[]):
|
|
39
|
+
logger.debug("ModelFramework.__init__")
|
|
40
|
+
self.uid = str(uuid.uuid4())
|
|
41
|
+
|
|
42
|
+
for i in ["learner", "validation_strategy"]: # mandatory parameters
|
|
43
|
+
if i not in params:
|
|
44
|
+
msg = "Missing {0} parameter in ModelFramework params".format(i)
|
|
45
|
+
logger.error(msg)
|
|
46
|
+
raise ValueError(msg)
|
|
47
|
+
|
|
48
|
+
self.params = params
|
|
49
|
+
self.callbacks = CallbackList(callbacks)
|
|
50
|
+
|
|
51
|
+
self._name = params.get("name", "model")
|
|
52
|
+
self.additional_params = params.get("additional")
|
|
53
|
+
self.preprocessing_params = params.get("preprocessing")
|
|
54
|
+
self.validation_params = params.get("validation_strategy")
|
|
55
|
+
self.learner_params = params.get("learner")
|
|
56
|
+
|
|
57
|
+
self._ml_task = params.get("ml_task")
|
|
58
|
+
self._explain_level = params.get("explain_level")
|
|
59
|
+
self._is_stacked = params.get("is_stacked", False)
|
|
60
|
+
|
|
61
|
+
self.validation = None
|
|
62
|
+
self.preprocessings = []
|
|
63
|
+
self.learners = []
|
|
64
|
+
|
|
65
|
+
self.train_time = None
|
|
66
|
+
self.final_loss = None
|
|
67
|
+
self.metric_name = None
|
|
68
|
+
self.oof_predictions = None
|
|
69
|
+
self._additional_metrics = None
|
|
70
|
+
self._threshold = None # used only for binary classifiers
|
|
71
|
+
self._max_time_for_learner = params.get("max_time_for_learner", 3600)
|
|
72
|
+
self._oof_predictions_fname = None
|
|
73
|
+
self._single_prediction_time = None # prediction time on single sample
|
|
74
|
+
self._optuna_time_budget = params.get("optuna_time_budget")
|
|
75
|
+
self._optuna_init_params = params.get("optuna_init_params", {})
|
|
76
|
+
self._optuna_verbose = params.get("optuna_verbose", True)
|
|
77
|
+
|
|
78
|
+
self._fairness_metric = params.get("fairness_metric")
|
|
79
|
+
self._fairness_threshold = params.get("fairness_threshold")
|
|
80
|
+
self._privileged_groups = params.get("privileged_groups", [])
|
|
81
|
+
self._underprivileged_groups = params.get("underprivileged_groups", [])
|
|
82
|
+
self._fairness_optimization = params.get("fairness_optimization")
|
|
83
|
+
self._is_fair = None
|
|
84
|
+
|
|
85
|
+
# the automl random state from AutoML constructor, used in Optuna optimizer
|
|
86
|
+
self._automl_random_state = params.get("automl_random_state", 42)
|
|
87
|
+
|
|
88
|
+
def get_train_time(self):
|
|
89
|
+
return self.train_time
|
|
90
|
+
|
|
91
|
+
def predictions(
|
|
92
|
+
self,
|
|
93
|
+
learner,
|
|
94
|
+
preproces,
|
|
95
|
+
X_train,
|
|
96
|
+
y_train,
|
|
97
|
+
sample_weight,
|
|
98
|
+
sensitive_features,
|
|
99
|
+
X_validation,
|
|
100
|
+
y_validation,
|
|
101
|
+
sample_weight_validation,
|
|
102
|
+
sensitive_features_validation,
|
|
103
|
+
):
|
|
104
|
+
y_train_true = y_train
|
|
105
|
+
y_train_predicted = learner.predict(X_train)
|
|
106
|
+
y_validation_true = y_validation
|
|
107
|
+
y_validation_predicted = learner.predict(X_validation)
|
|
108
|
+
|
|
109
|
+
y_train_true = preproces.inverse_scale_target(y_train_true)
|
|
110
|
+
y_train_predicted = preproces.inverse_scale_target(y_train_predicted)
|
|
111
|
+
y_validation_true = preproces.inverse_scale_target(y_validation_true)
|
|
112
|
+
y_validation_predicted = preproces.inverse_scale_target(y_validation_predicted)
|
|
113
|
+
|
|
114
|
+
y_validation_columns = []
|
|
115
|
+
if self._ml_task == MULTICLASS_CLASSIFICATION:
|
|
116
|
+
# y_train_true = preproces.inverse_categorical_target(y_train_true)
|
|
117
|
+
# y_validation_true = preproces.inverse_categorical_target(y_validation_true)
|
|
118
|
+
# get columns, omit the last one (it is label)
|
|
119
|
+
y_validation_columns = preproces.prepare_target_labels(
|
|
120
|
+
y_validation_predicted
|
|
121
|
+
).columns.tolist()[:-1]
|
|
122
|
+
elif self._ml_task == BINARY_CLASSIFICATION:
|
|
123
|
+
class_names = self.preprocessings[-1].get_target_class_names()
|
|
124
|
+
y_validation_columns = "prediction"
|
|
125
|
+
if not ("0" in class_names and "1" in class_names):
|
|
126
|
+
y_validation_columns = (
|
|
127
|
+
f"prediction_0_for_{class_names[0]}_1_for_{class_names[1]}"
|
|
128
|
+
)
|
|
129
|
+
else:
|
|
130
|
+
y_validation_columns = "prediction"
|
|
131
|
+
|
|
132
|
+
return {
|
|
133
|
+
"y_train_true": y_train_true,
|
|
134
|
+
"y_train_predicted": y_train_predicted,
|
|
135
|
+
"sample_weight": sample_weight,
|
|
136
|
+
"sensitive_features": sensitive_features,
|
|
137
|
+
"y_validation_true": y_validation_true,
|
|
138
|
+
"y_validation_predicted": y_validation_predicted,
|
|
139
|
+
"sample_weight_validation": sample_weight_validation,
|
|
140
|
+
"sensitive_features_validation": sensitive_features_validation,
|
|
141
|
+
"validation_index": X_validation.index,
|
|
142
|
+
"validation_columns": y_validation_columns,
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
def train(self, results_path, model_subpath):
|
|
146
|
+
logger.debug(f"ModelFramework.train {self.learner_params.get('model_type')}")
|
|
147
|
+
|
|
148
|
+
start_time = time.time()
|
|
149
|
+
np.random.seed(self.learner_params["seed"])
|
|
150
|
+
|
|
151
|
+
optuna_tuner = None
|
|
152
|
+
if self._optuna_time_budget is not None and OptunaTuner.is_optimizable(
|
|
153
|
+
self.learner_params.get("model_type", "")
|
|
154
|
+
):
|
|
155
|
+
optuna_tuner = OptunaTuner(
|
|
156
|
+
results_path,
|
|
157
|
+
ml_task=self._ml_task,
|
|
158
|
+
eval_metric=self.get_metric(),
|
|
159
|
+
time_budget=self._optuna_time_budget,
|
|
160
|
+
init_params=self._optuna_init_params,
|
|
161
|
+
verbose=self._optuna_verbose,
|
|
162
|
+
n_jobs=self.learner_params.get("n_jobs", -1),
|
|
163
|
+
random_state=self._automl_random_state,
|
|
164
|
+
)
|
|
165
|
+
|
|
166
|
+
self.validation = ValidationStep(self.validation_params)
|
|
167
|
+
|
|
168
|
+
repeats = self.validation.get_repeats()
|
|
169
|
+
for repeat in range(repeats):
|
|
170
|
+
for k_fold in range(self.validation.get_n_splits()):
|
|
171
|
+
train_data, validation_data = self.validation.get_split(k_fold, repeat)
|
|
172
|
+
logger.debug(
|
|
173
|
+
"Data split, train X:{} y:{}, validation X:{}, y:{}".format(
|
|
174
|
+
train_data["X"].shape,
|
|
175
|
+
train_data["y"].shape,
|
|
176
|
+
validation_data["X"].shape,
|
|
177
|
+
validation_data["y"].shape,
|
|
178
|
+
)
|
|
179
|
+
)
|
|
180
|
+
if "sample_weight" in train_data:
|
|
181
|
+
logger.debug("Sample weight available during the training.")
|
|
182
|
+
|
|
183
|
+
# the proprocessing is done at every validation step
|
|
184
|
+
self.preprocessings += [
|
|
185
|
+
Preprocessing(
|
|
186
|
+
self.preprocessing_params, self.get_name(), k_fold, repeat
|
|
187
|
+
)
|
|
188
|
+
]
|
|
189
|
+
|
|
190
|
+
X_train, y_train, sample_weight = self.preprocessings[
|
|
191
|
+
-1
|
|
192
|
+
].fit_and_transform(
|
|
193
|
+
train_data["X"], train_data["y"], train_data.get("sample_weight")
|
|
194
|
+
)
|
|
195
|
+
(
|
|
196
|
+
X_validation,
|
|
197
|
+
y_validation,
|
|
198
|
+
sample_weight_validation,
|
|
199
|
+
) = self.preprocessings[-1].transform(
|
|
200
|
+
validation_data["X"],
|
|
201
|
+
validation_data["y"],
|
|
202
|
+
validation_data.get("sample_weight"),
|
|
203
|
+
)
|
|
204
|
+
|
|
205
|
+
# skip preprocessing for sensitive features
|
|
206
|
+
# TODO: need to add sensitive features in preprocessing because some rows might be skipped (missing target)
|
|
207
|
+
# then we need to skip some rows in sensitive features as well
|
|
208
|
+
# TODO: drop rows if there is missing data in sensitive feature?
|
|
209
|
+
|
|
210
|
+
# get sensitive features from data split
|
|
211
|
+
sensitive_features = train_data.get("sensitive_features")
|
|
212
|
+
sensitive_features_validation = validation_data.get(
|
|
213
|
+
"sensitive_features"
|
|
214
|
+
)
|
|
215
|
+
|
|
216
|
+
if optuna_tuner is not None:
|
|
217
|
+
optuna_start_time = time.time()
|
|
218
|
+
self.learner_params = optuna_tuner.optimize(
|
|
219
|
+
self.learner_params.get("model_type", ""),
|
|
220
|
+
self.params.get("data_type", ""),
|
|
221
|
+
X_train,
|
|
222
|
+
y_train,
|
|
223
|
+
sample_weight,
|
|
224
|
+
X_validation,
|
|
225
|
+
y_validation,
|
|
226
|
+
sample_weight_validation,
|
|
227
|
+
self.learner_params,
|
|
228
|
+
)
|
|
229
|
+
# exclude optuna optimize time from model training
|
|
230
|
+
start_time += time.time() - optuna_start_time
|
|
231
|
+
|
|
232
|
+
self.learner_params["explain_level"] = self._explain_level
|
|
233
|
+
self.learners += [
|
|
234
|
+
AlgorithmFactory.get_algorithm(copy.deepcopy(self.learner_params))
|
|
235
|
+
]
|
|
236
|
+
learner = self.learners[-1]
|
|
237
|
+
learner.set_learner_name(k_fold, repeat, repeats)
|
|
238
|
+
|
|
239
|
+
self.callbacks.add_and_set_learner(learner)
|
|
240
|
+
self.callbacks.on_learner_train_start()
|
|
241
|
+
|
|
242
|
+
log_to_file = os.path.join(
|
|
243
|
+
results_path, model_subpath, f"{learner.name}_training.log"
|
|
244
|
+
)
|
|
245
|
+
|
|
246
|
+
for i in range(learner.max_iters):
|
|
247
|
+
self.callbacks.on_iteration_start()
|
|
248
|
+
|
|
249
|
+
learner.fit(
|
|
250
|
+
X_train,
|
|
251
|
+
y_train,
|
|
252
|
+
sample_weight,
|
|
253
|
+
X_validation,
|
|
254
|
+
y_validation,
|
|
255
|
+
sample_weight_validation,
|
|
256
|
+
log_to_file,
|
|
257
|
+
self._max_time_for_learner,
|
|
258
|
+
)
|
|
259
|
+
|
|
260
|
+
if self.params.get("injected_sample_weight", False):
|
|
261
|
+
# print("Dont use sample weight in model evaluation")
|
|
262
|
+
sample_weight = None
|
|
263
|
+
sample_weight_validation = None
|
|
264
|
+
|
|
265
|
+
self.callbacks.on_iteration_end(
|
|
266
|
+
{"iter_cnt": i},
|
|
267
|
+
self.predictions(
|
|
268
|
+
learner,
|
|
269
|
+
self.preprocessings[-1],
|
|
270
|
+
X_train,
|
|
271
|
+
y_train,
|
|
272
|
+
sample_weight,
|
|
273
|
+
sensitive_features,
|
|
274
|
+
X_validation,
|
|
275
|
+
y_validation,
|
|
276
|
+
sample_weight_validation,
|
|
277
|
+
sensitive_features_validation,
|
|
278
|
+
),
|
|
279
|
+
)
|
|
280
|
+
|
|
281
|
+
if learner.stop_training:
|
|
282
|
+
break
|
|
283
|
+
learner.update({"step": i})
|
|
284
|
+
|
|
285
|
+
# end of learner iters loop
|
|
286
|
+
self.callbacks.on_learner_train_end()
|
|
287
|
+
|
|
288
|
+
model_path = os.path.join(results_path, model_subpath)
|
|
289
|
+
learner.interpret(
|
|
290
|
+
X_train,
|
|
291
|
+
y_train,
|
|
292
|
+
X_validation,
|
|
293
|
+
y_validation,
|
|
294
|
+
model_file_path=model_path,
|
|
295
|
+
learner_name=learner.name,
|
|
296
|
+
class_names=self.preprocessings[-1].get_target_class_names(),
|
|
297
|
+
metric_name=self.get_metric_name(),
|
|
298
|
+
ml_task=self._ml_task,
|
|
299
|
+
explain_level=self._explain_level,
|
|
300
|
+
)
|
|
301
|
+
|
|
302
|
+
# save learner and free the memory
|
|
303
|
+
p = os.path.join(model_path, learner.get_fname())
|
|
304
|
+
learner.save(p)
|
|
305
|
+
del learner.model
|
|
306
|
+
learner.model = None
|
|
307
|
+
# end of learner training
|
|
308
|
+
|
|
309
|
+
# clear data
|
|
310
|
+
del X_train
|
|
311
|
+
del y_train
|
|
312
|
+
del X_validation
|
|
313
|
+
del y_validation
|
|
314
|
+
|
|
315
|
+
if sample_weight is not None:
|
|
316
|
+
del sample_weight
|
|
317
|
+
del train_data["sample_weight"]
|
|
318
|
+
if sample_weight_validation is not None:
|
|
319
|
+
del sample_weight_validation
|
|
320
|
+
del validation_data["sample_weight"]
|
|
321
|
+
|
|
322
|
+
del train_data["X"]
|
|
323
|
+
del train_data["y"]
|
|
324
|
+
del validation_data["X"]
|
|
325
|
+
del validation_data["y"]
|
|
326
|
+
del train_data
|
|
327
|
+
del validation_data
|
|
328
|
+
|
|
329
|
+
gc.collect()
|
|
330
|
+
|
|
331
|
+
# end of validation loop
|
|
332
|
+
self.callbacks.on_framework_train_end()
|
|
333
|
+
# self.get_additional_metrics()
|
|
334
|
+
self._additional_metrics = self.get_additional_metrics()
|
|
335
|
+
|
|
336
|
+
self.train_time = time.time() - start_time
|
|
337
|
+
logger.debug("ModelFramework end of training")
|
|
338
|
+
|
|
339
|
+
def release_learners(self):
|
|
340
|
+
for learner in self.learners:
|
|
341
|
+
if learner.model is not None:
|
|
342
|
+
del learner.model
|
|
343
|
+
learner.model = None
|
|
344
|
+
|
|
345
|
+
def get_metric_name(self):
|
|
346
|
+
if self.metric_name is not None:
|
|
347
|
+
return self.metric_name
|
|
348
|
+
early_stopping = self.callbacks.get("early_stopping")
|
|
349
|
+
if early_stopping is None:
|
|
350
|
+
return None
|
|
351
|
+
self.metric_name = early_stopping.metric.name
|
|
352
|
+
return early_stopping.metric.name
|
|
353
|
+
|
|
354
|
+
def get_metric(self):
|
|
355
|
+
early_stopping = self.callbacks.get("early_stopping")
|
|
356
|
+
if early_stopping:
|
|
357
|
+
return early_stopping.metric
|
|
358
|
+
return Metric({"name": self.get_metric_name()})
|
|
359
|
+
|
|
360
|
+
def get_out_of_folds(self):
|
|
361
|
+
if self.oof_predictions is not None:
|
|
362
|
+
return self.oof_predictions.copy(deep=True)
|
|
363
|
+
|
|
364
|
+
if self._oof_predictions_fname is not None:
|
|
365
|
+
self.oof_predictions = pd.read_csv(self._oof_predictions_fname)
|
|
366
|
+
return self.oof_predictions.copy(deep=True)
|
|
367
|
+
|
|
368
|
+
early_stopping = self.callbacks.get("early_stopping")
|
|
369
|
+
if early_stopping is None:
|
|
370
|
+
return None
|
|
371
|
+
self.oof_predictions = early_stopping.best_y_oof
|
|
372
|
+
|
|
373
|
+
###############################################################
|
|
374
|
+
# in case of one-hot coded multiclass target
|
|
375
|
+
target_cols = [
|
|
376
|
+
c for c in self.oof_predictions.columns.tolist() if "target" in c
|
|
377
|
+
]
|
|
378
|
+
if len(target_cols) > 1:
|
|
379
|
+
target = self.oof_predictions[target_cols[0]].copy()
|
|
380
|
+
target.name = "target"
|
|
381
|
+
for i, t in enumerate(target_cols):
|
|
382
|
+
target[self.oof_predictions[t] == 1] = i
|
|
383
|
+
self.oof_predictions.drop(target_cols, axis=1, inplace=True)
|
|
384
|
+
|
|
385
|
+
self.oof_predictions.insert(0, "target", np.array(target))
|
|
386
|
+
|
|
387
|
+
return early_stopping.best_y_oof
|
|
388
|
+
|
|
389
|
+
def get_final_loss(self):
|
|
390
|
+
if self.final_loss is not None:
|
|
391
|
+
return self.final_loss
|
|
392
|
+
early_stopping = self.callbacks.get("early_stopping")
|
|
393
|
+
if early_stopping is None:
|
|
394
|
+
return None
|
|
395
|
+
self.final_loss = early_stopping.final_loss
|
|
396
|
+
return early_stopping.final_loss
|
|
397
|
+
|
|
398
|
+
"""
|
|
399
|
+
def get_metric_logs(self):
|
|
400
|
+
metric_logger = self.callbacks.get("metric_logger")
|
|
401
|
+
if metric_logger is None:
|
|
402
|
+
return None
|
|
403
|
+
return metric_logger.loss_values
|
|
404
|
+
"""
|
|
405
|
+
|
|
406
|
+
def get_type(self):
|
|
407
|
+
return self.learner_params.get("model_type")
|
|
408
|
+
|
|
409
|
+
def get_name(self):
|
|
410
|
+
return self._name
|
|
411
|
+
|
|
412
|
+
def involved_model_names(self):
|
|
413
|
+
"""Returns the list of all models involved in the current model.
|
|
414
|
+
For single model, it returns the list with the name of the model.
|
|
415
|
+
For ensemble model, it returns the list with the name of the ensemble and all internal models
|
|
416
|
+
(used to build ensemble).
|
|
417
|
+
For single model but trained on stacked data, it returns the list with the name of the model
|
|
418
|
+
(names of models used in stacking are not included)."""
|
|
419
|
+
return [self._name]
|
|
420
|
+
|
|
421
|
+
def is_valid(self):
|
|
422
|
+
"""is_valid is used in Ensemble to check if it has more than 1 model in it.
|
|
423
|
+
If Ensemble has only 1 model in it, then Ensemble shouldn't be used as best model
|
|
424
|
+
"""
|
|
425
|
+
return True
|
|
426
|
+
|
|
427
|
+
def is_fast_enough(self, max_single_prediction_time):
|
|
428
|
+
# dont need to check
|
|
429
|
+
if max_single_prediction_time is None:
|
|
430
|
+
return True
|
|
431
|
+
|
|
432
|
+
# no iformation about prediction time
|
|
433
|
+
if self._single_prediction_time is None:
|
|
434
|
+
return True
|
|
435
|
+
|
|
436
|
+
return self._single_prediction_time < max_single_prediction_time
|
|
437
|
+
|
|
438
|
+
def predict(self, X):
|
|
439
|
+
logger.debug("ModelFramework.predict")
|
|
440
|
+
|
|
441
|
+
if self.learners is None or len(self.learners) == 0:
|
|
442
|
+
raise Exception("Learnes are not initialized")
|
|
443
|
+
# run predict on all learners and return the average
|
|
444
|
+
y_predicted = None # np.zeros((X.shape[0],))
|
|
445
|
+
for ind, learner in enumerate(self.learners):
|
|
446
|
+
# preprocessing goes here
|
|
447
|
+
X_data, _, _ = self.preprocessings[ind].transform(X.copy(), None)
|
|
448
|
+
y_p = learner.predict(X_data)
|
|
449
|
+
y_p = self.preprocessings[ind].inverse_scale_target(y_p)
|
|
450
|
+
|
|
451
|
+
y_predicted = y_p if y_predicted is None else y_predicted + y_p
|
|
452
|
+
|
|
453
|
+
y_predicted_average = y_predicted / float(len(self.learners))
|
|
454
|
+
|
|
455
|
+
y_predicted_final = self.preprocessings[0].prepare_target_labels(
|
|
456
|
+
y_predicted_average
|
|
457
|
+
)
|
|
458
|
+
|
|
459
|
+
return y_predicted_final
|
|
460
|
+
|
|
461
|
+
def get_additional_metrics(self):
|
|
462
|
+
if self._additional_metrics is None:
|
|
463
|
+
logger.debug("Compute additional metrics")
|
|
464
|
+
# 'target' - the target after processing used for model training
|
|
465
|
+
# 'prediction' - out of folds predictions of the model
|
|
466
|
+
oof_predictions = self.get_out_of_folds()
|
|
467
|
+
prediction_cols = [c for c in oof_predictions.columns if "prediction" in c]
|
|
468
|
+
target_cols = [c for c in oof_predictions.columns if "target" in c]
|
|
469
|
+
|
|
470
|
+
target = oof_predictions[target_cols]
|
|
471
|
+
|
|
472
|
+
oof_preds = None
|
|
473
|
+
if self._ml_task == MULTICLASS_CLASSIFICATION:
|
|
474
|
+
oof_preds = self.preprocessings[0].prepare_target_labels(
|
|
475
|
+
oof_predictions[prediction_cols].values
|
|
476
|
+
)
|
|
477
|
+
else:
|
|
478
|
+
oof_preds = oof_predictions[prediction_cols]
|
|
479
|
+
|
|
480
|
+
sample_weight = None
|
|
481
|
+
if "sample_weight" in oof_predictions.columns:
|
|
482
|
+
sample_weight = oof_predictions["sample_weight"]
|
|
483
|
+
|
|
484
|
+
sensitive_features = None
|
|
485
|
+
sensitive_cols = [c for c in oof_predictions.columns if "sensitive" in c]
|
|
486
|
+
if sensitive_cols:
|
|
487
|
+
sensitive_features = oof_predictions[sensitive_cols]
|
|
488
|
+
|
|
489
|
+
self._additional_metrics = AdditionalMetrics.compute(
|
|
490
|
+
target,
|
|
491
|
+
oof_preds,
|
|
492
|
+
sample_weight,
|
|
493
|
+
self._ml_task,
|
|
494
|
+
sensitive_features,
|
|
495
|
+
self._fairness_metric
|
|
496
|
+
if self._ml_task != REGRESSION
|
|
497
|
+
else f"{self._fairness_metric}@{self.get_metric_name()}",
|
|
498
|
+
self._fairness_threshold,
|
|
499
|
+
self._privileged_groups,
|
|
500
|
+
self._underprivileged_groups,
|
|
501
|
+
self._fairness_optimization,
|
|
502
|
+
)
|
|
503
|
+
if self._ml_task == BINARY_CLASSIFICATION:
|
|
504
|
+
self._threshold = float(self._additional_metrics["threshold"])
|
|
505
|
+
return self._additional_metrics
|
|
506
|
+
|
|
507
|
+
def get_sensitive_features_names(self):
|
|
508
|
+
metrics = self.get_additional_metrics()
|
|
509
|
+
fm = metrics.get("fairness_metrics", {})
|
|
510
|
+
return [i for i in list(fm.keys()) if i != "fairness_optimization"]
|
|
511
|
+
|
|
512
|
+
def get_fairness_metric(self, col_name):
|
|
513
|
+
metrics = self.get_additional_metrics()
|
|
514
|
+
fm = metrics.get("fairness_metrics", {})
|
|
515
|
+
return fm.get(col_name, {}).get("fairness_metric_value")
|
|
516
|
+
|
|
517
|
+
def get_fairness_optimization(self):
|
|
518
|
+
metrics = self.get_additional_metrics()
|
|
519
|
+
fm = metrics.get("fairness_metrics", {})
|
|
520
|
+
return fm.get("fairness_optimization", {})
|
|
521
|
+
|
|
522
|
+
def get_worst_fairness(self):
|
|
523
|
+
# We have fairness metrics per sensitive feature.
|
|
524
|
+
# The worst fairness metric is:
|
|
525
|
+
# - for ratio metrics, the lowest fairness value from all sensitive features
|
|
526
|
+
# - for difference metrics, the highest fairness value from all sensitive features
|
|
527
|
+
# It is needed as bias mitigation stop criteria.
|
|
528
|
+
|
|
529
|
+
metrics = self.get_additional_metrics()
|
|
530
|
+
|
|
531
|
+
fm = metrics.get("fairness_metrics", {})
|
|
532
|
+
worst_value = None
|
|
533
|
+
for col_name, values in fm.items():
|
|
534
|
+
if col_name == "fairness_optimization":
|
|
535
|
+
continue
|
|
536
|
+
if "ratio" in self._fairness_metric.lower():
|
|
537
|
+
if worst_value is None:
|
|
538
|
+
worst_value = values.get("fairness_metric_value", 0)
|
|
539
|
+
else:
|
|
540
|
+
worst_value = min(
|
|
541
|
+
worst_value, values.get("fairness_metric_value", 0)
|
|
542
|
+
)
|
|
543
|
+
else:
|
|
544
|
+
if worst_value is None:
|
|
545
|
+
worst_value = values.get("fairness_metric_value", 1)
|
|
546
|
+
else:
|
|
547
|
+
worst_value = max(
|
|
548
|
+
worst_value, values.get("fairness_metric_value", 1)
|
|
549
|
+
)
|
|
550
|
+
|
|
551
|
+
return worst_value
|
|
552
|
+
|
|
553
|
+
def get_best_fairness(self):
|
|
554
|
+
# We have fairness metrics per sensitive feature.
|
|
555
|
+
# The best fairness metric is:
|
|
556
|
+
# - for ratio metrics, the highest fairness value from all sensitive features
|
|
557
|
+
# - for difference metrics, the lowest fairness value from all sensitive features
|
|
558
|
+
# It is needed as bias mitigation stop criteria.
|
|
559
|
+
|
|
560
|
+
metrics = self.get_additional_metrics()
|
|
561
|
+
fm = metrics.get("fairness_metrics", {})
|
|
562
|
+
best_value = None
|
|
563
|
+
for col_name, values in fm.items():
|
|
564
|
+
if col_name == "fairness_optimization":
|
|
565
|
+
continue
|
|
566
|
+
if "ratio" in self._fairness_metric.lower():
|
|
567
|
+
if best_value is None:
|
|
568
|
+
best_value = values.get("fairness_metric_value", 0)
|
|
569
|
+
else:
|
|
570
|
+
best_value = max(best_value, values.get("fairness_metric_value", 0))
|
|
571
|
+
else:
|
|
572
|
+
if best_value is None:
|
|
573
|
+
best_value = values.get("fairness_metric_value", 1)
|
|
574
|
+
else:
|
|
575
|
+
best_value = min(best_value, values.get("fairness_metric_value", 1))
|
|
576
|
+
|
|
577
|
+
return best_value
|
|
578
|
+
|
|
579
|
+
def is_fair(self):
|
|
580
|
+
if self._is_fair is not None:
|
|
581
|
+
return self._is_fair
|
|
582
|
+
metrics = self.get_additional_metrics()
|
|
583
|
+
fm = metrics.get("fairness_metrics", {})
|
|
584
|
+
for col, m in fm.items():
|
|
585
|
+
if col == "fairness_optimization":
|
|
586
|
+
continue
|
|
587
|
+
if not m.get("is_fair", True):
|
|
588
|
+
self._is_fair = False
|
|
589
|
+
return False
|
|
590
|
+
self._is_fair = True
|
|
591
|
+
return False
|
|
592
|
+
|
|
593
|
+
def save(self, results_path, model_subpath):
|
|
594
|
+
start_time = time.time()
|
|
595
|
+
model_path = os.path.join(results_path, model_subpath)
|
|
596
|
+
logger.info(f"Save the model {model_path}")
|
|
597
|
+
|
|
598
|
+
type_of_predictions = (
|
|
599
|
+
"validation" if "k_folds" not in self.validation_params else "out_of_folds"
|
|
600
|
+
)
|
|
601
|
+
predictions_fname = os.path.join(
|
|
602
|
+
model_subpath, f"predictions_{type_of_predictions}.csv"
|
|
603
|
+
)
|
|
604
|
+
self._oof_predictions_fname = os.path.join(results_path, predictions_fname)
|
|
605
|
+
predictions = self.get_out_of_folds()
|
|
606
|
+
predictions.to_csv(self._oof_predictions_fname, index=False)
|
|
607
|
+
|
|
608
|
+
saved = [os.path.join(model_subpath, l.get_fname()) for l in self.learners]
|
|
609
|
+
|
|
610
|
+
with open(os.path.join(model_path, "framework.json"), "w") as fout:
|
|
611
|
+
preprocessing = [p.to_json() for p in self.preprocessings]
|
|
612
|
+
learners_params = [learner.get_params() for learner in self.learners]
|
|
613
|
+
|
|
614
|
+
desc = {
|
|
615
|
+
"uid": self.uid,
|
|
616
|
+
"name": self._name,
|
|
617
|
+
"preprocessing": preprocessing,
|
|
618
|
+
"learners": learners_params,
|
|
619
|
+
"params": self.params,
|
|
620
|
+
"saved": saved,
|
|
621
|
+
"predictions_fname": predictions_fname,
|
|
622
|
+
"metric_name": self.get_metric_name(),
|
|
623
|
+
"final_loss": self.get_final_loss(),
|
|
624
|
+
"train_time": self.get_train_time(),
|
|
625
|
+
"is_stacked": self._is_stacked,
|
|
626
|
+
"joblib_version": joblib.__version__,
|
|
627
|
+
}
|
|
628
|
+
desc["final_loss"] = str(desc["final_loss"])
|
|
629
|
+
if self._threshold is not None:
|
|
630
|
+
desc["threshold"] = self._threshold
|
|
631
|
+
if self._single_prediction_time is not None:
|
|
632
|
+
desc["single_prediction_time"] = self._single_prediction_time
|
|
633
|
+
fout.write(json.dumps(desc, indent=4, cls=MLJSONEncoder))
|
|
634
|
+
|
|
635
|
+
learning_curve_metric = self.learners[0].get_metric_name()
|
|
636
|
+
if learning_curve_metric is None:
|
|
637
|
+
learning_curve_metric = self.get_metric_name()
|
|
638
|
+
|
|
639
|
+
LearningCurves.plot(
|
|
640
|
+
[l.name for l in self.learners],
|
|
641
|
+
learning_curve_metric,
|
|
642
|
+
model_path,
|
|
643
|
+
trees_in_iteration=self.additional_params.get("trees_in_step"),
|
|
644
|
+
)
|
|
645
|
+
|
|
646
|
+
# call additional metics just to be sure they are computed
|
|
647
|
+
self._additional_metrics = self.get_additional_metrics()
|
|
648
|
+
|
|
649
|
+
AdditionalMetrics.save(
|
|
650
|
+
self._additional_metrics, self._ml_task, self.model_markdown(), model_path
|
|
651
|
+
)
|
|
652
|
+
|
|
653
|
+
with open(os.path.join(model_path, "status.txt"), "w") as fout:
|
|
654
|
+
fout.write("ALL OK!")
|
|
655
|
+
# I'm adding save time to total train time
|
|
656
|
+
# there is always save after the training
|
|
657
|
+
self.train_time += time.time() - start_time
|
|
658
|
+
|
|
659
|
+
def model_markdown(self):
|
|
660
|
+
long_name = AlgorithmsRegistry.get_long_name(
|
|
661
|
+
self._ml_task, self.learner_params["model_type"]
|
|
662
|
+
)
|
|
663
|
+
short_name = self.learner_params["model_type"]
|
|
664
|
+
desc = f"# Summary of {self.get_name()}\n\n"
|
|
665
|
+
|
|
666
|
+
desc += "[<< Go back](../README.md)\n\n"
|
|
667
|
+
|
|
668
|
+
if long_name == short_name:
|
|
669
|
+
desc += f"\n## {short_name}\n"
|
|
670
|
+
else:
|
|
671
|
+
desc += f"\n## {long_name} ({short_name})\n"
|
|
672
|
+
for k, v in self.learner_params.items():
|
|
673
|
+
if k in ["model_type", "ml_task", "seed"]:
|
|
674
|
+
continue
|
|
675
|
+
desc += f"- **{k}**: {v}\n"
|
|
676
|
+
desc += "\n## Validation\n"
|
|
677
|
+
for k, v in self.validation_params.items():
|
|
678
|
+
if "path" not in k:
|
|
679
|
+
desc += f" - **{k}**: {v}\n"
|
|
680
|
+
desc += "\n## Optimized metric\n"
|
|
681
|
+
desc += f"{self.get_metric_name()}\n"
|
|
682
|
+
desc += "\n## Training time\n"
|
|
683
|
+
desc += f"\n{np.round(self.train_time,1)} seconds\n"
|
|
684
|
+
return desc
|
|
685
|
+
|
|
686
|
+
@staticmethod
|
|
687
|
+
def load(results_path, model_subpath, lazy_load=True):
|
|
688
|
+
model_path = os.path.join(results_path, model_subpath)
|
|
689
|
+
logger.info(f"Loading model framework from {model_path}")
|
|
690
|
+
|
|
691
|
+
with open(os.path.join(model_path, "framework.json")) as file:
|
|
692
|
+
json_desc = json.load(file)
|
|
693
|
+
|
|
694
|
+
joblib_version_computer = joblib.__version__
|
|
695
|
+
joblib_version_framework = json_desc.get("joblib_version")
|
|
696
|
+
|
|
697
|
+
if (
|
|
698
|
+
joblib_version_framework is not None
|
|
699
|
+
and joblib_version_computer != joblib_version_framework
|
|
700
|
+
):
|
|
701
|
+
raise AutoMLException(
|
|
702
|
+
f"Joblib version mismatch. Computer: {joblib_version_computer}, Framework: {joblib_version_framework}. Change to Framework version!"
|
|
703
|
+
)
|
|
704
|
+
|
|
705
|
+
mf = ModelFramework(json_desc["params"])
|
|
706
|
+
mf.uid = json_desc.get("uid", mf.uid)
|
|
707
|
+
mf._name = json_desc.get("name", mf._name)
|
|
708
|
+
mf._threshold = json_desc.get("threshold")
|
|
709
|
+
mf.train_time = json_desc.get("train_time", mf.train_time)
|
|
710
|
+
mf.final_loss = json_desc.get("final_loss", mf.final_loss)
|
|
711
|
+
mf.metric_name = json_desc.get("metric_name", mf.metric_name)
|
|
712
|
+
mf._is_stacked = json_desc.get("is_stacked", mf._is_stacked)
|
|
713
|
+
mf._single_prediction_time = json_desc.get(
|
|
714
|
+
"single_prediction_time", mf._single_prediction_time
|
|
715
|
+
)
|
|
716
|
+
predictions_fname = json_desc.get("predictions_fname")
|
|
717
|
+
if predictions_fname is not None:
|
|
718
|
+
mf._oof_predictions_fname = os.path.join(results_path, predictions_fname)
|
|
719
|
+
|
|
720
|
+
mf.learners = []
|
|
721
|
+
for learner_desc, learner_subpath in zip(
|
|
722
|
+
json_desc.get("learners"), json_desc.get("saved")
|
|
723
|
+
):
|
|
724
|
+
learner_path = os.path.join(results_path, learner_subpath)
|
|
725
|
+
l = AlgorithmFactory.load(learner_desc, learner_path, lazy_load)
|
|
726
|
+
mf.learners += [l]
|
|
727
|
+
|
|
728
|
+
mf.preprocessings = []
|
|
729
|
+
for p in json_desc.get("preprocessing"):
|
|
730
|
+
ps = Preprocessing()
|
|
731
|
+
ps.from_json(p, results_path)
|
|
732
|
+
mf.preprocessings += [ps]
|
|
733
|
+
|
|
734
|
+
return mf
|