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
supervised/ensemble.py
ADDED
|
@@ -0,0 +1,583 @@
|
|
|
1
|
+
import copy
|
|
2
|
+
import json
|
|
3
|
+
import logging
|
|
4
|
+
import os
|
|
5
|
+
import time
|
|
6
|
+
import uuid
|
|
7
|
+
|
|
8
|
+
import numpy as np
|
|
9
|
+
import pandas as pd
|
|
10
|
+
|
|
11
|
+
from supervised.algorithms.registry import (
|
|
12
|
+
BINARY_CLASSIFICATION,
|
|
13
|
+
MULTICLASS_CLASSIFICATION,
|
|
14
|
+
REGRESSION,
|
|
15
|
+
)
|
|
16
|
+
from supervised.exceptions import NotTrainedException
|
|
17
|
+
from supervised.model_framework import ModelFramework
|
|
18
|
+
from supervised.utils.additional_metrics import AdditionalMetrics
|
|
19
|
+
from supervised.utils.config import LOG_LEVEL
|
|
20
|
+
from supervised.utils.jsonencoder import MLJSONEncoder
|
|
21
|
+
from supervised.utils.metric import Metric
|
|
22
|
+
|
|
23
|
+
logger = logging.getLogger(__name__)
|
|
24
|
+
logger.setLevel(LOG_LEVEL)
|
|
25
|
+
|
|
26
|
+
from tabulate import tabulate
|
|
27
|
+
|
|
28
|
+
from supervised.utils.learning_curves import LearningCurves
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
class Ensemble:
|
|
32
|
+
algorithm_name = "Greedy Ensemble"
|
|
33
|
+
algorithm_short_name = "Ensemble"
|
|
34
|
+
|
|
35
|
+
def __init__(
|
|
36
|
+
self,
|
|
37
|
+
optimize_metric="logloss",
|
|
38
|
+
ml_task=BINARY_CLASSIFICATION,
|
|
39
|
+
is_stacked=False,
|
|
40
|
+
max_single_prediction_time=None,
|
|
41
|
+
fairness_metric=None,
|
|
42
|
+
fairness_threshold=None,
|
|
43
|
+
privileged_groups=None,
|
|
44
|
+
underprivileged_groups=None,
|
|
45
|
+
):
|
|
46
|
+
self.library_version = "0.1"
|
|
47
|
+
self.uid = str(uuid.uuid4())
|
|
48
|
+
|
|
49
|
+
self.metric = Metric({"name": optimize_metric})
|
|
50
|
+
self.best_loss = self.metric.get_maximum() # the best loss obtained by ensemble
|
|
51
|
+
self.models_map = None
|
|
52
|
+
self.selected_models = []
|
|
53
|
+
self.train_time = None
|
|
54
|
+
self.total_best_sum = None # total sum of predictions, the oof of ensemble
|
|
55
|
+
self.target = None
|
|
56
|
+
self.target_columns = None
|
|
57
|
+
self.sample_weight = None
|
|
58
|
+
self._ml_task = ml_task
|
|
59
|
+
self._optimize_metric = optimize_metric
|
|
60
|
+
self._is_stacked = is_stacked
|
|
61
|
+
|
|
62
|
+
self._additional_metrics = None
|
|
63
|
+
self._threshold = None
|
|
64
|
+
self._name = "Ensemble_Stacked" if is_stacked else "Ensemble"
|
|
65
|
+
self._scores = []
|
|
66
|
+
self.oof_predictions = None
|
|
67
|
+
self._oof_predictions_fname = None
|
|
68
|
+
self._single_prediction_time = None # prediction time on single sample
|
|
69
|
+
self._max_single_prediction_time = max_single_prediction_time
|
|
70
|
+
self.model_prediction_time = {}
|
|
71
|
+
|
|
72
|
+
self._fairness_metric = fairness_metric
|
|
73
|
+
self._fairness_threshold = fairness_threshold
|
|
74
|
+
self._privileged_groups = privileged_groups
|
|
75
|
+
self._underprivileged_groups = underprivileged_groups
|
|
76
|
+
self._is_fair = None
|
|
77
|
+
self.sensitive_features = None
|
|
78
|
+
|
|
79
|
+
def get_train_time(self):
|
|
80
|
+
return self.train_time
|
|
81
|
+
|
|
82
|
+
def get_final_loss(self):
|
|
83
|
+
return self.best_loss
|
|
84
|
+
|
|
85
|
+
def is_valid(self):
|
|
86
|
+
return len(self.selected_models) > 1
|
|
87
|
+
|
|
88
|
+
def is_fast_enough(self, max_single_prediction_time):
|
|
89
|
+
# dont need to check
|
|
90
|
+
if max_single_prediction_time is None:
|
|
91
|
+
return True
|
|
92
|
+
|
|
93
|
+
# no iformation about prediction time
|
|
94
|
+
if self._single_prediction_time is None:
|
|
95
|
+
return True
|
|
96
|
+
|
|
97
|
+
return self._single_prediction_time < max_single_prediction_time
|
|
98
|
+
|
|
99
|
+
def get_type(self):
|
|
100
|
+
prefix = "" # "Stacked" if self._is_stacked else ""
|
|
101
|
+
return prefix + self.algorithm_short_name
|
|
102
|
+
|
|
103
|
+
def get_name(self):
|
|
104
|
+
return self._name
|
|
105
|
+
|
|
106
|
+
def involved_model_names(self):
|
|
107
|
+
"""Returns the list of all models involved in the current model.
|
|
108
|
+
For single model, it returns the list with the name of the model.
|
|
109
|
+
For ensemble model, it returns the list with the name of the ensemble and all internal models
|
|
110
|
+
(used to build ensemble).
|
|
111
|
+
For single model but trained on stacked data, it returns the list with the name of the model
|
|
112
|
+
(names of models used in stacking are not included)."""
|
|
113
|
+
if self.selected_models is None or not self.selected_models:
|
|
114
|
+
return [self._name]
|
|
115
|
+
l = []
|
|
116
|
+
for m in self.selected_models:
|
|
117
|
+
l += m["model"].involved_model_names()
|
|
118
|
+
return [self._name] + l
|
|
119
|
+
|
|
120
|
+
def get_metric_name(self):
|
|
121
|
+
return self.metric.name
|
|
122
|
+
|
|
123
|
+
def get_metric(self):
|
|
124
|
+
return self.metric
|
|
125
|
+
|
|
126
|
+
def get_out_of_folds(self):
|
|
127
|
+
"""Needed when ensemble is treated as model and we want to compute additional metrics for it"""
|
|
128
|
+
# single prediction (in case of binary classification and regression)
|
|
129
|
+
if self.oof_predictions is not None:
|
|
130
|
+
return self.oof_predictions.copy(deep=True)
|
|
131
|
+
|
|
132
|
+
if self._oof_predictions_fname is not None:
|
|
133
|
+
self.oof_predictions = pd.read_csv(self._oof_predictions_fname)
|
|
134
|
+
return self.oof_predictions.copy(deep=True)
|
|
135
|
+
|
|
136
|
+
ensemble_oof = pd.DataFrame(
|
|
137
|
+
data=self.total_best_sum, columns=self.total_best_sum.columns
|
|
138
|
+
)
|
|
139
|
+
ensemble_oof["target"] = self.target
|
|
140
|
+
if self.sample_weight is not None:
|
|
141
|
+
ensemble_oof["sample_weight"] = self.sample_weight
|
|
142
|
+
|
|
143
|
+
# if self.sensitive_features is not None:
|
|
144
|
+
# for col in self.sensitive_features.columns:
|
|
145
|
+
# ensemble_oof[col] = self.sensitive_features[col]
|
|
146
|
+
|
|
147
|
+
self.oof_predictions = ensemble_oof
|
|
148
|
+
return ensemble_oof
|
|
149
|
+
|
|
150
|
+
def _get_mean(self, oof_selected, best_sum, best_count):
|
|
151
|
+
resp = copy.deepcopy(oof_selected)
|
|
152
|
+
if best_count > 1:
|
|
153
|
+
resp += best_sum
|
|
154
|
+
resp /= float(best_count)
|
|
155
|
+
return resp
|
|
156
|
+
|
|
157
|
+
def get_oof_matrix(self, models):
|
|
158
|
+
# remember models, will be needed in predictions
|
|
159
|
+
self.models_map = {m.get_name(): m for m in models}
|
|
160
|
+
|
|
161
|
+
if self._max_single_prediction_time is not None:
|
|
162
|
+
self.model_prediction_time = {
|
|
163
|
+
m.get_name(): m._single_prediction_time for m in models
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
if not [
|
|
167
|
+
m for m in models if m.is_fast_enough(self._max_single_prediction_time)
|
|
168
|
+
]:
|
|
169
|
+
raise NotTrainedException(
|
|
170
|
+
"Can't contruct ensemble with prediction time smaller than limit."
|
|
171
|
+
)
|
|
172
|
+
|
|
173
|
+
# check if we can construct fair ensemble
|
|
174
|
+
if self._fairness_metric is not None:
|
|
175
|
+
if not [m for m in models if m.is_fair()]:
|
|
176
|
+
raise NotTrainedException("Can't contruct fair ensemble.")
|
|
177
|
+
|
|
178
|
+
oofs = {}
|
|
179
|
+
sensitive_features = None
|
|
180
|
+
for m in models:
|
|
181
|
+
# do not use model with RandomFeature
|
|
182
|
+
if "RandomFeature" in m.get_name():
|
|
183
|
+
continue
|
|
184
|
+
|
|
185
|
+
# ensemble only the same level of stack
|
|
186
|
+
# if m._is_stacked != self._is_stacked:
|
|
187
|
+
# continue
|
|
188
|
+
oof = m.get_out_of_folds()
|
|
189
|
+
prediction_cols = [c for c in oof.columns if "prediction" in c]
|
|
190
|
+
oofs[m.get_name()] = oof[prediction_cols] # oof["prediction"]
|
|
191
|
+
if self.target is None:
|
|
192
|
+
self.target_columns = [c for c in oof.columns if "target" in c]
|
|
193
|
+
self.target = oof[
|
|
194
|
+
self.target_columns
|
|
195
|
+
] # it will be needed for computing advance model statistics
|
|
196
|
+
|
|
197
|
+
if self.sample_weight is None and "sample_weight" in oof.columns:
|
|
198
|
+
self.sample_weight = oof["sample_weight"]
|
|
199
|
+
|
|
200
|
+
sensitive_cols = [c for c in oof.columns if "sensitive" in c]
|
|
201
|
+
if sensitive_cols and sensitive_features is None:
|
|
202
|
+
sensitive_features = oof[sensitive_cols]
|
|
203
|
+
|
|
204
|
+
return oofs, self.target, self.sample_weight, sensitive_features
|
|
205
|
+
|
|
206
|
+
def get_additional_metrics(self):
|
|
207
|
+
if self._additional_metrics is None:
|
|
208
|
+
logger.debug("Get additional metrics for Ensemble")
|
|
209
|
+
# 'target' - the target after processing used for model training
|
|
210
|
+
# 'prediction' - out of folds predictions of the model
|
|
211
|
+
oof_predictions = self.get_out_of_folds()
|
|
212
|
+
prediction_cols = [c for c in oof_predictions.columns if "prediction" in c]
|
|
213
|
+
target_cols = [c for c in oof_predictions.columns if "target" in c]
|
|
214
|
+
|
|
215
|
+
oof_preds = oof_predictions[prediction_cols]
|
|
216
|
+
if self._ml_task == MULTICLASS_CLASSIFICATION:
|
|
217
|
+
cols = oof_preds.columns.tolist()
|
|
218
|
+
# prediction_
|
|
219
|
+
labels = {i: v[11:] for i, v in enumerate(cols)}
|
|
220
|
+
|
|
221
|
+
oof_preds["label"] = np.argmax(
|
|
222
|
+
np.array(oof_preds[prediction_cols]), axis=1
|
|
223
|
+
)
|
|
224
|
+
oof_preds["label"] = oof_preds["label"].map(labels)
|
|
225
|
+
|
|
226
|
+
sample_weight = None
|
|
227
|
+
if "sample_weight" in oof_predictions.columns:
|
|
228
|
+
sample_weight = oof_predictions["sample_weight"]
|
|
229
|
+
|
|
230
|
+
self._additional_metrics = AdditionalMetrics.compute(
|
|
231
|
+
oof_predictions[target_cols],
|
|
232
|
+
oof_preds,
|
|
233
|
+
sample_weight,
|
|
234
|
+
self._ml_task,
|
|
235
|
+
self.sensitive_features,
|
|
236
|
+
self._fairness_metric
|
|
237
|
+
if self._ml_task != REGRESSION
|
|
238
|
+
else f"{self._fairness_metric}@{self.get_metric_name()}",
|
|
239
|
+
self._fairness_threshold,
|
|
240
|
+
self._privileged_groups,
|
|
241
|
+
self._underprivileged_groups,
|
|
242
|
+
)
|
|
243
|
+
if self._ml_task == BINARY_CLASSIFICATION:
|
|
244
|
+
self._threshold = float(self._additional_metrics["threshold"])
|
|
245
|
+
|
|
246
|
+
return self._additional_metrics
|
|
247
|
+
|
|
248
|
+
def get_sensitive_features_names(self):
|
|
249
|
+
metrics = self.get_additional_metrics()
|
|
250
|
+
fm = metrics.get("fairness_metrics", {})
|
|
251
|
+
return [i for i in list(fm.keys()) if i != "fairness_optimization"]
|
|
252
|
+
|
|
253
|
+
def get_fairness_metric(self, col_name):
|
|
254
|
+
metrics = self.get_additional_metrics()
|
|
255
|
+
fm = metrics.get("fairness_metrics", {})
|
|
256
|
+
return fm.get(col_name, {}).get("fairness_metric_value")
|
|
257
|
+
|
|
258
|
+
def get_fairness_optimization(self):
|
|
259
|
+
metrics = self.get_additional_metrics()
|
|
260
|
+
fm = metrics.get("fairness_metrics", {})
|
|
261
|
+
return fm.get("fairness_optimization", {})
|
|
262
|
+
|
|
263
|
+
def get_worst_fairness(self):
|
|
264
|
+
# We have fairness metrics per sensitive feature.
|
|
265
|
+
# The worst fairness metric is:
|
|
266
|
+
# - for ratio metrics, the lowest fairness value from all sensitive features
|
|
267
|
+
# - for difference metrics, the highest fairness value from all sensitive features
|
|
268
|
+
# It is needed as bias mitigation stop criteria.
|
|
269
|
+
|
|
270
|
+
metrics = self.get_additional_metrics()
|
|
271
|
+
|
|
272
|
+
fm = metrics.get("fairness_metrics", {})
|
|
273
|
+
worst_value = None
|
|
274
|
+
for col_name, values in fm.items():
|
|
275
|
+
if col_name == "fairness_optimization":
|
|
276
|
+
continue
|
|
277
|
+
if "ratio" in self._fairness_metric.lower():
|
|
278
|
+
if worst_value is None:
|
|
279
|
+
worst_value = values.get("fairness_metric_value", 0)
|
|
280
|
+
else:
|
|
281
|
+
worst_value = min(
|
|
282
|
+
worst_value, values.get("fairness_metric_value", 0)
|
|
283
|
+
)
|
|
284
|
+
else:
|
|
285
|
+
if worst_value is None:
|
|
286
|
+
worst_value = values.get("fairness_metric_value", 1)
|
|
287
|
+
else:
|
|
288
|
+
worst_value = max(
|
|
289
|
+
worst_value, values.get("fairness_metric_value", 1)
|
|
290
|
+
)
|
|
291
|
+
|
|
292
|
+
return worst_value
|
|
293
|
+
|
|
294
|
+
def get_best_fairness(self):
|
|
295
|
+
# We have fairness metrics per sensitive feature.
|
|
296
|
+
# The best fairness metric is:
|
|
297
|
+
# - for ratio metrics, the highest fairness value from all sensitive features
|
|
298
|
+
# - for difference metrics, the lowest fairness value from all sensitive features
|
|
299
|
+
# It is needed as bias mitigation stop criteria.
|
|
300
|
+
|
|
301
|
+
metrics = self.get_additional_metrics()
|
|
302
|
+
fm = metrics.get("fairness_metrics", {})
|
|
303
|
+
best_value = None
|
|
304
|
+
for col_name, values in fm.items():
|
|
305
|
+
if col_name == "fairness_optimization":
|
|
306
|
+
continue
|
|
307
|
+
if "ratio" in self._fairness_metric.lower():
|
|
308
|
+
if best_value is None:
|
|
309
|
+
best_value = values.get("fairness_metric_value", 0)
|
|
310
|
+
else:
|
|
311
|
+
best_value = max(best_value, values.get("fairness_metric_value", 0))
|
|
312
|
+
else:
|
|
313
|
+
if best_value is None:
|
|
314
|
+
best_value = values.get("fairness_metric_value", 1)
|
|
315
|
+
else:
|
|
316
|
+
best_value = min(best_value, values.get("fairness_metric_value", 1))
|
|
317
|
+
|
|
318
|
+
return best_value
|
|
319
|
+
|
|
320
|
+
def is_fair(self):
|
|
321
|
+
if self._is_fair is not None:
|
|
322
|
+
return self._is_fair
|
|
323
|
+
metrics = self.get_additional_metrics()
|
|
324
|
+
fm = metrics.get("fairness_metrics", {})
|
|
325
|
+
for col, m in fm.items():
|
|
326
|
+
if col == "fairness_optimization":
|
|
327
|
+
continue
|
|
328
|
+
if not m.get("is_fair", True):
|
|
329
|
+
self._is_fair = False
|
|
330
|
+
return False
|
|
331
|
+
self._is_fair = True
|
|
332
|
+
return False
|
|
333
|
+
|
|
334
|
+
def fit(self, oofs, y, sample_weight=None, sensitive_features=None):
|
|
335
|
+
logger.debug("Ensemble.fit")
|
|
336
|
+
self.sensitive_features = sensitive_features
|
|
337
|
+
start_time = time.time()
|
|
338
|
+
selected_algs_cnt = 0 # number of selected algorithms
|
|
339
|
+
self.best_algs = [] # selected algoritms indices from each loop
|
|
340
|
+
|
|
341
|
+
total_prediction_time = 0
|
|
342
|
+
best_sum = None # sum of best algorihtms
|
|
343
|
+
for j in range(len(oofs)): # iterate over all solutions
|
|
344
|
+
min_score = self.metric.get_maximum()
|
|
345
|
+
best_model = None
|
|
346
|
+
# try to add some algorithm to the best_sum to minimize metric
|
|
347
|
+
for model_name in oofs.keys():
|
|
348
|
+
if (
|
|
349
|
+
self._max_single_prediction_time
|
|
350
|
+
and model_name in self.model_prediction_time
|
|
351
|
+
):
|
|
352
|
+
if (
|
|
353
|
+
total_prediction_time + self.model_prediction_time[model_name]
|
|
354
|
+
> self._max_single_prediction_time
|
|
355
|
+
):
|
|
356
|
+
continue
|
|
357
|
+
# skip unfair models
|
|
358
|
+
if (
|
|
359
|
+
self._fairness_metric is not None
|
|
360
|
+
and not self.models_map[model_name].is_fair()
|
|
361
|
+
):
|
|
362
|
+
continue
|
|
363
|
+
y_ens = self._get_mean(oofs[model_name], best_sum, j + 1)
|
|
364
|
+
score = self.metric(y, y_ens, sample_weight)
|
|
365
|
+
if self.metric.improvement(previous=min_score, current=score):
|
|
366
|
+
min_score = score
|
|
367
|
+
best_model = model_name
|
|
368
|
+
|
|
369
|
+
if best_model is None:
|
|
370
|
+
continue
|
|
371
|
+
# there is improvement, save it
|
|
372
|
+
# save scores for plotting learning curve
|
|
373
|
+
# if we optimize negative, then we need to multiply by -1.0
|
|
374
|
+
# to save correct values in the learning curve
|
|
375
|
+
sign = -1.0 if Metric.optimize_negative(self.metric.name) else 1.0
|
|
376
|
+
self._scores += [sign * min_score]
|
|
377
|
+
|
|
378
|
+
if self.metric.improvement(previous=self.best_loss, current=min_score):
|
|
379
|
+
self.best_loss = min_score
|
|
380
|
+
selected_algs_cnt = j
|
|
381
|
+
|
|
382
|
+
self.best_algs.append(best_model) # save the best algoritm
|
|
383
|
+
# update best_sum value
|
|
384
|
+
best_sum = (
|
|
385
|
+
oofs[best_model] if best_sum is None else best_sum + oofs[best_model]
|
|
386
|
+
)
|
|
387
|
+
if j == selected_algs_cnt:
|
|
388
|
+
self.total_best_sum = copy.deepcopy(best_sum)
|
|
389
|
+
|
|
390
|
+
# update prediction time estimate
|
|
391
|
+
if self._max_single_prediction_time is not None:
|
|
392
|
+
total_prediction_time = np.sum(
|
|
393
|
+
[
|
|
394
|
+
self.model_prediction_time[name]
|
|
395
|
+
for name in np.unique(self.best_algs)
|
|
396
|
+
]
|
|
397
|
+
)
|
|
398
|
+
# end of main loop #
|
|
399
|
+
|
|
400
|
+
if not self.best_algs:
|
|
401
|
+
raise NotTrainedException("Ensemble wasn't fitted.")
|
|
402
|
+
|
|
403
|
+
# keep oof predictions of ensemble
|
|
404
|
+
self.total_best_sum /= float(selected_algs_cnt + 1)
|
|
405
|
+
self.best_algs = self.best_algs[: (selected_algs_cnt + 1)]
|
|
406
|
+
|
|
407
|
+
logger.debug("Selected models for ensemble:")
|
|
408
|
+
for model_name in np.unique(self.best_algs):
|
|
409
|
+
self.selected_models += [
|
|
410
|
+
{
|
|
411
|
+
"model": self.models_map[model_name],
|
|
412
|
+
"repeat": float(self.best_algs.count(model_name)),
|
|
413
|
+
}
|
|
414
|
+
]
|
|
415
|
+
logger.debug(f"{model_name} {self.best_algs.count(model_name)}")
|
|
416
|
+
|
|
417
|
+
self._additional_metrics = self.get_additional_metrics()
|
|
418
|
+
|
|
419
|
+
self.train_time = time.time() - start_time
|
|
420
|
+
|
|
421
|
+
def predict(self, X, X_stacked=None):
|
|
422
|
+
logger.debug(
|
|
423
|
+
"Ensemble.predict with {} models".format(len(self.selected_models))
|
|
424
|
+
)
|
|
425
|
+
y_predicted_ensemble = None
|
|
426
|
+
total_repeat = 0.0
|
|
427
|
+
|
|
428
|
+
for selected in self.selected_models:
|
|
429
|
+
model = selected["model"]
|
|
430
|
+
repeat = selected["repeat"]
|
|
431
|
+
total_repeat += repeat
|
|
432
|
+
|
|
433
|
+
if model._is_stacked:
|
|
434
|
+
y_predicted_from_model = model.predict(X_stacked)
|
|
435
|
+
else:
|
|
436
|
+
y_predicted_from_model = model.predict(X)
|
|
437
|
+
|
|
438
|
+
prediction_cols = []
|
|
439
|
+
if self._ml_task in [BINARY_CLASSIFICATION, MULTICLASS_CLASSIFICATION]:
|
|
440
|
+
prediction_cols = [
|
|
441
|
+
c for c in y_predicted_from_model.columns if "prediction_" in c
|
|
442
|
+
]
|
|
443
|
+
else: # REGRESSION
|
|
444
|
+
prediction_cols = ["prediction"]
|
|
445
|
+
y_predicted_from_model = y_predicted_from_model[prediction_cols]
|
|
446
|
+
y_predicted_ensemble = (
|
|
447
|
+
y_predicted_from_model * repeat
|
|
448
|
+
if y_predicted_ensemble is None
|
|
449
|
+
else y_predicted_ensemble + y_predicted_from_model * repeat
|
|
450
|
+
)
|
|
451
|
+
|
|
452
|
+
y_predicted_ensemble /= total_repeat
|
|
453
|
+
|
|
454
|
+
if self._ml_task == MULTICLASS_CLASSIFICATION:
|
|
455
|
+
cols = y_predicted_ensemble.columns.tolist()
|
|
456
|
+
# prediction_
|
|
457
|
+
labels = {i: v[11:] for i, v in enumerate(cols)}
|
|
458
|
+
|
|
459
|
+
y_predicted_ensemble["label"] = np.argmax(
|
|
460
|
+
np.array(y_predicted_ensemble[prediction_cols]), axis=1
|
|
461
|
+
)
|
|
462
|
+
y_predicted_ensemble["label"] = y_predicted_ensemble["label"].map(labels)
|
|
463
|
+
|
|
464
|
+
return y_predicted_ensemble
|
|
465
|
+
|
|
466
|
+
def to_json(self):
|
|
467
|
+
models_json = []
|
|
468
|
+
for selected in self.selected_models:
|
|
469
|
+
model = selected["model"]
|
|
470
|
+
repeat = selected["repeat"]
|
|
471
|
+
models_json += [{"model": model.to_json(), "repeat": repeat}]
|
|
472
|
+
|
|
473
|
+
json_desc = {
|
|
474
|
+
"library_version": self.library_version,
|
|
475
|
+
"algorithm_name": self.algorithm_name,
|
|
476
|
+
"algorithm_short_name": self.algorithm_short_name,
|
|
477
|
+
"uid": self.uid,
|
|
478
|
+
"models": models_json,
|
|
479
|
+
}
|
|
480
|
+
return json_desc
|
|
481
|
+
|
|
482
|
+
def from_json(self, json_desc):
|
|
483
|
+
self.library_version = json_desc.get("library_version", self.library_version)
|
|
484
|
+
self.algorithm_name = json_desc.get("algorithm_name", self.algorithm_name)
|
|
485
|
+
self.algorithm_short_name = json_desc.get(
|
|
486
|
+
"algorithm_short_name", self.algorithm_short_name
|
|
487
|
+
)
|
|
488
|
+
self.uid = json_desc.get("uid", self.uid)
|
|
489
|
+
self.selected_models = []
|
|
490
|
+
models_json = json_desc.get("models")
|
|
491
|
+
for selected in models_json:
|
|
492
|
+
model = selected["model"]
|
|
493
|
+
repeat = selected["repeat"]
|
|
494
|
+
|
|
495
|
+
il = ModelFramework(model.get("params"))
|
|
496
|
+
il.from_json(model)
|
|
497
|
+
self.selected_models += [
|
|
498
|
+
# {"model": LearnerFactory.load(model), "repeat": repeat}
|
|
499
|
+
{"model": il, "repeat": repeat}
|
|
500
|
+
]
|
|
501
|
+
|
|
502
|
+
def save(self, results_path, model_subpath):
|
|
503
|
+
model_path = os.path.join(results_path, model_subpath)
|
|
504
|
+
logger.info(f"Save the ensemble to {model_path}")
|
|
505
|
+
|
|
506
|
+
predictions = self.get_out_of_folds()
|
|
507
|
+
predictions_fname = os.path.join(model_subpath, f"predictions_ensemble.csv")
|
|
508
|
+
self._oof_predictions_fname = os.path.join(results_path, predictions_fname)
|
|
509
|
+
predictions.to_csv(self._oof_predictions_fname, index=False)
|
|
510
|
+
|
|
511
|
+
with open(os.path.join(model_path, "ensemble.json"), "w") as fout:
|
|
512
|
+
ms = []
|
|
513
|
+
for selected in self.selected_models:
|
|
514
|
+
ms += [{"model": selected["model"]._name, "repeat": selected["repeat"]}]
|
|
515
|
+
|
|
516
|
+
desc = {
|
|
517
|
+
"name": self._name,
|
|
518
|
+
"ml_task": self._ml_task,
|
|
519
|
+
"optimize_metric": self._optimize_metric,
|
|
520
|
+
"selected_models": ms,
|
|
521
|
+
"predictions_fname": predictions_fname,
|
|
522
|
+
"metric_name": self.get_metric_name(),
|
|
523
|
+
"final_loss": self.get_final_loss(),
|
|
524
|
+
"train_time": self.get_train_time(),
|
|
525
|
+
"is_stacked": self._is_stacked,
|
|
526
|
+
}
|
|
527
|
+
|
|
528
|
+
if self._threshold is not None:
|
|
529
|
+
desc["threshold"] = self._threshold
|
|
530
|
+
fout.write(json.dumps(desc, indent=4, cls=MLJSONEncoder))
|
|
531
|
+
|
|
532
|
+
LearningCurves.plot_for_ensemble(self._scores, self.metric.name, model_path)
|
|
533
|
+
|
|
534
|
+
# call additional metics just to be sure they are computed
|
|
535
|
+
self._additional_metrics = self.get_additional_metrics()
|
|
536
|
+
|
|
537
|
+
AdditionalMetrics.save(
|
|
538
|
+
self._additional_metrics, self._ml_task, self.model_markdown(), model_path
|
|
539
|
+
)
|
|
540
|
+
|
|
541
|
+
with open(os.path.join(model_path, "status.txt"), "w") as fout:
|
|
542
|
+
fout.write("ALL OK!")
|
|
543
|
+
|
|
544
|
+
def model_markdown(self):
|
|
545
|
+
select_models_desc = []
|
|
546
|
+
for selected in self.selected_models:
|
|
547
|
+
select_models_desc += [
|
|
548
|
+
{"model": selected["model"]._name, "repeat": selected["repeat"]}
|
|
549
|
+
]
|
|
550
|
+
desc = f"# Summary of {self.get_name()}\n\n"
|
|
551
|
+
desc += "[<< Go back](../README.md)\n\n"
|
|
552
|
+
desc += "\n## Ensemble structure\n"
|
|
553
|
+
selected = pd.DataFrame(select_models_desc)
|
|
554
|
+
desc += tabulate(selected.values, ["Model", "Weight"], tablefmt="pipe")
|
|
555
|
+
desc += "\n"
|
|
556
|
+
return desc
|
|
557
|
+
|
|
558
|
+
@staticmethod
|
|
559
|
+
def load(results_path, model_subpath, models_map):
|
|
560
|
+
model_path = os.path.join(results_path, model_subpath)
|
|
561
|
+
logger.info(f"Loading ensemble from {model_path}")
|
|
562
|
+
|
|
563
|
+
with open(os.path.join(model_path, "ensemble.json")) as file:
|
|
564
|
+
json_desc = json.load(file)
|
|
565
|
+
|
|
566
|
+
ensemble = Ensemble(json_desc.get("optimize_metric"), json_desc.get("ml_task"))
|
|
567
|
+
ensemble._name = json_desc.get("name", ensemble._name)
|
|
568
|
+
ensemble._threshold = json_desc.get("threshold", ensemble._threshold)
|
|
569
|
+
for m in json_desc.get("selected_models", []):
|
|
570
|
+
ensemble.selected_models += [
|
|
571
|
+
{"model": models_map[m["model"]], "repeat": m["repeat"]}
|
|
572
|
+
]
|
|
573
|
+
|
|
574
|
+
ensemble.best_loss = json_desc.get("final_loss", ensemble.best_loss)
|
|
575
|
+
ensemble.train_time = json_desc.get("train_time", ensemble.train_time)
|
|
576
|
+
ensemble._is_stacked = json_desc.get("is_stacked", ensemble._is_stacked)
|
|
577
|
+
predictions_fname = json_desc.get("predictions_fname")
|
|
578
|
+
if predictions_fname is not None:
|
|
579
|
+
ensemble._oof_predictions_fname = os.path.join(
|
|
580
|
+
results_path, predictions_fname
|
|
581
|
+
)
|
|
582
|
+
|
|
583
|
+
return ensemble
|
supervised/exceptions.py
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import logging
|
|
2
|
+
|
|
3
|
+
from supervised.utils.config import LOG_LEVEL
|
|
4
|
+
|
|
5
|
+
logging.basicConfig(
|
|
6
|
+
format="%(asctime)s %(name)s %(levelname)s %(message)s", level=logging.ERROR
|
|
7
|
+
)
|
|
8
|
+
logger = logging.getLogger(__name__)
|
|
9
|
+
logger.setLevel(LOG_LEVEL)
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class AutoMLException(Exception):
|
|
13
|
+
def __init__(self, message):
|
|
14
|
+
super(AutoMLException, self).__init__(message)
|
|
15
|
+
logger.error(message)
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class NotTrainedException(Exception):
|
|
19
|
+
def __init__(self, message):
|
|
20
|
+
super(NotTrainedException, self).__init__(message)
|
|
21
|
+
logger.debug(message)
|
|
File without changes
|