mljar-supervised 1.2.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (94) hide show
  1. mljar_supervised-1.2.1.dist-info/METADATA +657 -0
  2. mljar_supervised-1.2.1.dist-info/RECORD +94 -0
  3. mljar_supervised-1.2.1.dist-info/WHEEL +5 -0
  4. mljar_supervised-1.2.1.dist-info/licenses/LICENSE +21 -0
  5. mljar_supervised-1.2.1.dist-info/top_level.txt +1 -0
  6. supervised/__init__.py +14 -0
  7. supervised/algorithms/__init__.py +0 -0
  8. supervised/algorithms/algorithm.py +151 -0
  9. supervised/algorithms/baseline.py +90 -0
  10. supervised/algorithms/catboost.py +436 -0
  11. supervised/algorithms/decision_tree.py +305 -0
  12. supervised/algorithms/extra_trees.py +176 -0
  13. supervised/algorithms/factory.py +28 -0
  14. supervised/algorithms/knn.py +137 -0
  15. supervised/algorithms/lightgbm.py +406 -0
  16. supervised/algorithms/linear.py +211 -0
  17. supervised/algorithms/nn.py +180 -0
  18. supervised/algorithms/random_forest.py +181 -0
  19. supervised/algorithms/registry.py +76 -0
  20. supervised/algorithms/sklearn.py +197 -0
  21. supervised/algorithms/xgboost.py +413 -0
  22. supervised/automl.py +568 -0
  23. supervised/base_automl.py +2542 -0
  24. supervised/callbacks/__init__.py +0 -0
  25. supervised/callbacks/callback.py +25 -0
  26. supervised/callbacks/callback_list.py +33 -0
  27. supervised/callbacks/early_stopping.py +213 -0
  28. supervised/callbacks/learner_time_constraint.py +47 -0
  29. supervised/callbacks/max_iters_constraint.py +16 -0
  30. supervised/callbacks/metric_logger.py +48 -0
  31. supervised/callbacks/terminate_on_nan.py +28 -0
  32. supervised/callbacks/total_time_constraint.py +79 -0
  33. supervised/ensemble.py +583 -0
  34. supervised/exceptions.py +21 -0
  35. supervised/fairness/__init__.py +0 -0
  36. supervised/fairness/metrics.py +654 -0
  37. supervised/fairness/optimization.py +414 -0
  38. supervised/fairness/plots.py +131 -0
  39. supervised/fairness/report.py +116 -0
  40. supervised/fairness/utils.py +40 -0
  41. supervised/model_framework.py +734 -0
  42. supervised/preprocessing/__init__.py +0 -0
  43. supervised/preprocessing/datetime_transformer.py +106 -0
  44. supervised/preprocessing/encoding_selector.py +30 -0
  45. supervised/preprocessing/exclude_missing_target.py +46 -0
  46. supervised/preprocessing/goldenfeatures_transformer.py +310 -0
  47. supervised/preprocessing/kmeans_transformer.py +115 -0
  48. supervised/preprocessing/label_binarizer.py +81 -0
  49. supervised/preprocessing/label_encoder.py +54 -0
  50. supervised/preprocessing/preprocessing.py +652 -0
  51. supervised/preprocessing/preprocessing_categorical.py +117 -0
  52. supervised/preprocessing/preprocessing_missing.py +97 -0
  53. supervised/preprocessing/preprocessing_utils.py +136 -0
  54. supervised/preprocessing/scale.py +92 -0
  55. supervised/preprocessing/text_transformer.py +73 -0
  56. supervised/tuner/__init__.py +0 -0
  57. supervised/tuner/data_info.py +64 -0
  58. supervised/tuner/hill_climbing.py +80 -0
  59. supervised/tuner/mljar_tuner.py +1501 -0
  60. supervised/tuner/optuna/__init__.py +0 -0
  61. supervised/tuner/optuna/catboost.py +148 -0
  62. supervised/tuner/optuna/extra_trees.py +80 -0
  63. supervised/tuner/optuna/knn.py +64 -0
  64. supervised/tuner/optuna/lightgbm.py +165 -0
  65. supervised/tuner/optuna/nn.py +66 -0
  66. supervised/tuner/optuna/random_forest.py +77 -0
  67. supervised/tuner/optuna/tuner.py +335 -0
  68. supervised/tuner/optuna/xgboost.py +130 -0
  69. supervised/tuner/preprocessing_tuner.py +137 -0
  70. supervised/tuner/random_parameters.py +22 -0
  71. supervised/tuner/time_controller.py +273 -0
  72. supervised/utils/__init__.py +11 -0
  73. supervised/utils/additional_metrics.py +955 -0
  74. supervised/utils/additional_plots.py +228 -0
  75. supervised/utils/automl_plots.py +368 -0
  76. supervised/utils/common.py +39 -0
  77. supervised/utils/config.py +25 -0
  78. supervised/utils/constants.py +4 -0
  79. supervised/utils/data_validation.py +48 -0
  80. supervised/utils/importance.py +93 -0
  81. supervised/utils/jsonencoder.py +33 -0
  82. supervised/utils/leaderboard_plots.py +137 -0
  83. supervised/utils/learning_curves.py +145 -0
  84. supervised/utils/metric.py +450 -0
  85. supervised/utils/report_structured.py +525 -0
  86. supervised/utils/shap.py +373 -0
  87. supervised/utils/subsample.py +17 -0
  88. supervised/utils/utils.py +29 -0
  89. supervised/validation/__init__.py +0 -0
  90. supervised/validation/validation_step.py +37 -0
  91. supervised/validation/validator_base.py +17 -0
  92. supervised/validation/validator_custom.py +112 -0
  93. supervised/validation/validator_kfold.py +153 -0
  94. supervised/validation/validator_split.py +143 -0
@@ -0,0 +1,2542 @@
1
+ import json
2
+ import logging
3
+ import os
4
+ import shutil
5
+ import time
6
+ import types
7
+ import uuid
8
+ from abc import ABC
9
+ from copy import deepcopy
10
+
11
+ import joblib
12
+ import numpy as np
13
+ import pandas as pd
14
+ from sklearn.base import BaseEstimator
15
+ from sklearn.metrics import accuracy_score, r2_score
16
+ from sklearn.utils.validation import check_array
17
+ from tabulate import tabulate
18
+
19
+ from supervised.algorithms.registry import (
20
+ BINARY_CLASSIFICATION,
21
+ MULTICLASS_CLASSIFICATION,
22
+ REGRESSION,
23
+ AlgorithmsRegistry,
24
+ )
25
+ from supervised.callbacks.early_stopping import EarlyStopping
26
+ from supervised.callbacks.total_time_constraint import TotalTimeConstraint
27
+ from supervised.ensemble import Ensemble
28
+ from supervised.exceptions import AutoMLException, NotTrainedException
29
+ from supervised.model_framework import ModelFramework
30
+ from supervised.preprocessing.exclude_missing_target import ExcludeRowsMissingTarget
31
+ # disable EDA
32
+ # from supervised.preprocessing.eda import EDA
33
+ from supervised.preprocessing.preprocessing_utils import PreprocessingUtils
34
+ from supervised.tuner.data_info import DataInfo
35
+ from supervised.tuner.mljar_tuner import MljarTuner
36
+ from supervised.tuner.time_controller import TimeController
37
+ from supervised.utils.automl_plots import AutoMLPlots
38
+ from supervised.utils.config import LOG_LEVEL
39
+ from supervised.utils.data_validation import (
40
+ check_bool,
41
+ check_greater_than_zero_integer,
42
+ check_greater_than_zero_integer_or_float,
43
+ check_integer,
44
+ check_positive_integer,
45
+ )
46
+ from supervised.utils.jsonencoder import MLJSONEncoder
47
+ from supervised.utils.leaderboard_plots import LeaderboardPlots
48
+ from supervised.utils.metric import Metric, UserDefinedEvalMetric
49
+ from supervised.utils.report_structured import (
50
+ build_structured_report,
51
+ save_structured_report,
52
+ to_markdown,
53
+ )
54
+ from supervised.utils.utils import dump_data, load_data
55
+
56
+ logger = logging.getLogger(__name__)
57
+ logger.setLevel(LOG_LEVEL)
58
+
59
+
60
+ class BaseAutoML(BaseEstimator, ABC):
61
+ """
62
+ Automated Machine Learning for supervised tasks (binary classification, multiclass classification, regression).
63
+ Warning: This class should not be used directly. Use derived classes instead.
64
+ """
65
+
66
+ def __init__(self):
67
+ logger.debug("BaseAutoML.__init__")
68
+ self._mode = None
69
+ self._ml_task = None
70
+ self._results_path = None
71
+ self._total_time_limit = None
72
+ self._model_time_limit = None
73
+ self._algorithms = []
74
+ self._train_ensemble = False
75
+ self._stack_models = False
76
+ self._eval_metric = None
77
+ self._validation_strategy = None
78
+ self._verbose = None
79
+ self._explain_level = None
80
+ self._golden_features = None
81
+ self._features_selection = None
82
+ self._start_random_models = None
83
+ self._hill_climbing_steps = None
84
+ self._top_models_to_improve = None
85
+ self._random_state = 1234
86
+ self._models = [] # instances of iterative learner framework or ensemble
87
+ self._best_model = None
88
+ self._verbose = True
89
+ self._threshold = None # used only in classification
90
+ self._metrics_details = None
91
+ self._max_metrics = None
92
+ self._confusion_matrix = None
93
+ self._X_path, self._y_path = None, None
94
+ self._data_info = None
95
+ self._model_subpaths = []
96
+ self._stacked_models = None
97
+ self._fit_level = None
98
+ self._start_time = time.time()
99
+ self._time_ctrl = None
100
+ self._all_params = {}
101
+ # https://scikit-learn.org/stable/developers/develop.html#universal-attributes
102
+ self.n_features_in_ = None # for scikit-learn api
103
+ self.tuner = None
104
+ self._boost_on_errors = None
105
+ self._kmeans_features = None
106
+ self._mix_encoding = None
107
+ self._max_single_prediction_time = None
108
+ self._optuna_time_budget = None
109
+ self._optuna_init_params = {}
110
+ self._fairness_metric = None
111
+ self._fairness_threshold = None
112
+ self._privileged_groups = []
113
+ self._underprivileged_groups = []
114
+ self._optuna_verbose = True
115
+ self._n_jobs = -1
116
+ self._id = str(uuid.uuid4())
117
+
118
+ def _get_tuner_params(
119
+ self, start_random_models, hill_climbing_steps, top_models_to_improve
120
+ ):
121
+ return {
122
+ "start_random_models": start_random_models,
123
+ "hill_climbing_steps": hill_climbing_steps,
124
+ "top_models_to_improve": top_models_to_improve,
125
+ }
126
+
127
+ def _check_can_load(self):
128
+ """Checks if AutoML can be loaded from a folder"""
129
+ if self.results_path is not None:
130
+ # Dir exists and can be loaded
131
+ if os.path.exists(self.results_path) and os.path.exists(
132
+ os.path.join(self.results_path, "params.json")
133
+ ):
134
+ self.load(self.results_path)
135
+ self._results_path = self.results_path
136
+
137
+ def load(self, path):
138
+ logger.info("Loading AutoML models ...")
139
+ try:
140
+ with open(os.path.join(path, "params.json")) as file:
141
+ params = json.load(file)
142
+
143
+ self._model_subpaths = params["saved"]
144
+ self._mode = params.get("mode", self._mode)
145
+ self._ml_task = params.get("ml_task", self._ml_task)
146
+ self._results_path = params.get("results_path", self._results_path)
147
+ self._total_time_limit = params.get(
148
+ "total_time_limit", self._total_time_limit
149
+ )
150
+ self._model_time_limit = params.get(
151
+ "model_time_limit", self._model_time_limit
152
+ )
153
+ self._algorithms = params.get("algorithms", self._algorithms)
154
+ self._train_ensemble = params.get("train_ensemble", self._train_ensemble)
155
+ self._stack_models = params.get("stack_models", self._stack_models)
156
+ self._eval_metric = params.get("eval_metric", self._eval_metric)
157
+ self._validation_strategy = params.get(
158
+ "validation_strategy", self._validation_strategy
159
+ )
160
+ self._verbose = params.get("verbose", self._verbose)
161
+ self._explain_level = params.get("explain_level", self._explain_level)
162
+ self._golden_features = params.get("golden_features", self._golden_features)
163
+ self._features_selection = params.get(
164
+ "features_selection", self._features_selection
165
+ )
166
+ self._start_random_models = params.get(
167
+ "start_random_models", self._start_random_models
168
+ )
169
+ self._hill_climbing_steps = params.get(
170
+ "hill_climbing_steps", self._hill_climbing_steps
171
+ )
172
+ self._top_models_to_improve = params.get(
173
+ "top_models_to_improve", self._top_models_to_improve
174
+ )
175
+ self._boost_on_errors = params.get("boost_on_errors", self._boost_on_errors)
176
+ self._kmeans_features = params.get("kmeans_features", self._kmeans_features)
177
+ self._mix_encoding = params.get("mix_encoding", self._mix_encoding)
178
+ self._max_single_prediction_time = params.get(
179
+ "max_single_prediction_time", self._max_single_prediction_time
180
+ )
181
+ self._n_jobs = params.get("n_jobs", self._n_jobs)
182
+ self._random_state = params.get("random_state", self._random_state)
183
+ stacked_models = params.get("stacked")
184
+
185
+ best_model_name = params.get("best_model")
186
+ load_on_predict = params.get("load_on_predict")
187
+ self._fit_level = params.get("fit_level")
188
+ lazy_load = not (
189
+ self._fit_level is not None and self._fit_level == "finished"
190
+ )
191
+ load_models = self._model_subpaths
192
+ if load_on_predict is not None and self._fit_level == "finished":
193
+ load_models = load_on_predict
194
+ # just in case there is check for which models should be loaded
195
+ # fix https://github.com/mljar/mljar-supervised/issues/395
196
+ models_needed = self.models_needed_on_predict(best_model_name)
197
+ # join them and return unique list
198
+ load_models = list(np.unique(load_models + models_needed))
199
+
200
+ models_map = {}
201
+
202
+ for model_subpath in load_models:
203
+ if model_subpath.endswith("Ensemble") or model_subpath.endswith(
204
+ "Ensemble_Stacked"
205
+ ):
206
+ ens = Ensemble.load(path, model_subpath, models_map)
207
+ self._models += [ens]
208
+ models_map[ens.get_name()] = ens
209
+ else:
210
+ m = ModelFramework.load(path, model_subpath, lazy_load)
211
+ self._models += [m]
212
+ models_map[m.get_name()] = m
213
+
214
+ self._best_model = None
215
+ if best_model_name is not None:
216
+ self._best_model = models_map.get(best_model_name)
217
+
218
+ if stacked_models is not None and (
219
+ self._best_model._is_stacked or self._fit_level != "finished"
220
+ ):
221
+ self._stacked_models = []
222
+ for stacked_model_name in stacked_models:
223
+ self._stacked_models += [models_map[stacked_model_name]]
224
+
225
+ data_info_path = os.path.join(path, "data_info.json")
226
+ with open(data_info_path, "r") as file:
227
+ self._data_info = json.load(file)
228
+ self.n_features_in_ = self._data_info["n_features"]
229
+
230
+ if "n_classes" in self._data_info:
231
+ self.n_classes = self._data_info["n_classes"]
232
+
233
+ except Exception as e:
234
+ raise AutoMLException(f"Cannot load AutoML directory. {str(e)}")
235
+
236
+ def get_leaderboard(
237
+ self, filter_random_feature=False, original_metric_values=False
238
+ ):
239
+ ldb = {
240
+ "name": [],
241
+ "model_type": [],
242
+ "metric_type": [],
243
+ "metric_value": [],
244
+ "train_time": [],
245
+ }
246
+ if self._max_single_prediction_time is not None:
247
+ ldb["single_prediction_time"] = []
248
+
249
+ sensitive_features_names = []
250
+ if self._fairness_metric is not None and len(self._models):
251
+ sensitive_features_names = self._models[0].get_sensitive_features_names()
252
+ ldb["fairness_metric"] = []
253
+ for sf in sensitive_features_names:
254
+ ldb[f"fairness_{sf}"] = []
255
+ ldb["is_fair"] = []
256
+
257
+ for m in self._models:
258
+ # filter model with random feature
259
+ if filter_random_feature and "RandomFeature" in m.get_name():
260
+ continue
261
+ ldb["name"] += [m.get_name()]
262
+ ldb["model_type"] += [m.get_type()]
263
+ ldb["metric_type"] += [self._eval_metric]
264
+ ldb["metric_value"] += [m.get_final_loss()]
265
+ ldb["train_time"] += [np.round(m.get_train_time(), 2)]
266
+ if self._max_single_prediction_time is not None:
267
+ if m._single_prediction_time is not None:
268
+ ldb["single_prediction_time"] += [
269
+ np.round(m._single_prediction_time, 4)
270
+ ]
271
+ else:
272
+ ldb["single_prediction_time"] += [None]
273
+ if self._fairness_metric is not None:
274
+ ldb["fairness_metric"] += [self._fairness_metric]
275
+ for sf in sensitive_features_names:
276
+ ldb[f"fairness_{sf}"] += [m.get_fairness_metric(sf)]
277
+ ldb["is_fair"] += [m.is_fair()]
278
+
279
+ ldb = pd.DataFrame(ldb)
280
+ # need to add argument for sorting
281
+ # minimize_direction = m.get_metric().get_minimize_direction()
282
+ # ldb = ldb.sort_values("metric_value", ascending=minimize_direction)
283
+
284
+ if original_metric_values:
285
+ if Metric.optimize_negative(self._eval_metric):
286
+ ldb["metric_value"] *= -1.0
287
+
288
+ return ldb
289
+
290
+ def keep_model(self, model, model_subpath):
291
+ if model is None:
292
+ return
293
+
294
+ if self._max_single_prediction_time is not None:
295
+ # let's check the prediction time ...
296
+ # load 2x because of model reloading during the training
297
+ for _ in range(2):
298
+ start_time = time.time()
299
+ self._base_predict(self._one_sample, model)
300
+ model._single_prediction_time = (
301
+ time.time() - start_time
302
+ ) # prediction time on single sample
303
+ # again release learners from models
304
+ if "Ensemble" not in model.get_type():
305
+ model.release_learners()
306
+
307
+ self._models += [model]
308
+ self._model_subpaths += [model_subpath]
309
+ self.select_and_save_best()
310
+
311
+ sign = -1.0 if Metric.optimize_negative(self._eval_metric) else 1.0
312
+ msg = "{} {} {} trained in {} seconds".format(
313
+ model.get_name(),
314
+ self._eval_metric,
315
+ np.round(sign * model.get_final_loss(), 6),
316
+ np.round(model.get_train_time(), 2),
317
+ )
318
+ if model._single_prediction_time is not None:
319
+ msg += f" (1-sample predict time {np.round(model._single_prediction_time,4)} seconds)"
320
+ self.verbose_print(msg)
321
+ self._time_ctrl.log_time(
322
+ model.get_name(), model.get_type(), self._fit_level, model.get_train_time()
323
+ )
324
+
325
+ self.tuner.add_key(model)
326
+
327
+ def create_dir(self, model_path):
328
+ if not os.path.exists(model_path):
329
+ try:
330
+ os.mkdir(model_path)
331
+ except Exception as e:
332
+ raise AutoMLException(f"Cannot create directory {model_path}. {str(e)}")
333
+
334
+ def _expected_learners_cnt(self):
335
+ try:
336
+ repeats = self._validation_strategy.get("repeats", 1)
337
+ folds = self._validation_strategy.get("k_folds", 1)
338
+ return repeats * folds
339
+ except Exception as e:
340
+ pass
341
+ return 1
342
+
343
+ def train_model(self, params):
344
+ # do we have enough time to train?
345
+ # if not, skip
346
+ if not self._time_ctrl.enough_time(
347
+ params["learner"]["model_type"], self._fit_level
348
+ ):
349
+ logger.info(f"Cannot train {params['name']} because of the time constraint")
350
+ return False
351
+ # let's create directory to log all training artifacts
352
+ results_path, model_subpath = self._results_path, params["name"]
353
+ model_path = os.path.join(results_path, model_subpath)
354
+ self.create_dir(model_path)
355
+
356
+ # prepare callbacks
357
+ early_stop = EarlyStopping(
358
+ {"metric": {"name": self._eval_metric}, "log_to_dir": model_path}
359
+ )
360
+
361
+ # disable for now
362
+ max_time_for_learner = 3600
363
+ if self._total_time_limit is not None:
364
+ k_folds = self._validation_strategy.get("k_folds", 1.0)
365
+ at_least_algorithms = 10.0
366
+
367
+ max_time_for_learner = max(
368
+ self._total_time_limit / k_folds / at_least_algorithms, 60
369
+ )
370
+
371
+ params["max_time_for_learner"] = max_time_for_learner
372
+
373
+ total_time_constraint = TotalTimeConstraint(
374
+ {
375
+ "total_time_limit": self._total_time_limit
376
+ if self._model_time_limit is None
377
+ else None,
378
+ "total_time_start": self._start_time,
379
+ "expected_learners_cnt": self._expected_learners_cnt(),
380
+ }
381
+ )
382
+
383
+ # create model framework
384
+ mf = ModelFramework(
385
+ params,
386
+ callbacks=[early_stop, total_time_constraint],
387
+ )
388
+
389
+ # start training
390
+ logger.info(
391
+ f"Train model #{len(self._models)+1} / Model name: {params['name']}"
392
+ )
393
+ mf.train(results_path, model_subpath)
394
+
395
+ # keep info about the model
396
+ self.keep_model(mf, model_subpath)
397
+
398
+ # save the model
399
+ mf.save(results_path, model_subpath)
400
+
401
+ return True
402
+
403
+ def verbose_print(self, msg):
404
+ if self._verbose > 0:
405
+ # self._progress_bar.write(msg)
406
+ print(msg)
407
+
408
+ def ensemble_step(self, is_stacked=False):
409
+ if self._train_ensemble and len(self._models) > 1:
410
+ ensemble_subpath = "Ensemble_Stacked" if is_stacked else "Ensemble"
411
+ ensemble_path = os.path.join(self._results_path, ensemble_subpath)
412
+ self.create_dir(ensemble_path)
413
+
414
+ self.ensemble = Ensemble(
415
+ self._eval_metric,
416
+ self._ml_task,
417
+ is_stacked=is_stacked,
418
+ max_single_prediction_time=self._max_single_prediction_time,
419
+ fairness_metric=self._fairness_metric,
420
+ fairness_threshold=self._fairness_threshold,
421
+ privileged_groups=self._privileged_groups,
422
+ underprivileged_groups=self._underprivileged_groups,
423
+ )
424
+ (
425
+ oofs,
426
+ target,
427
+ sample_weight,
428
+ sensitive_features,
429
+ ) = self.ensemble.get_oof_matrix(self._models)
430
+ self.ensemble.fit(oofs, target, sample_weight, sensitive_features)
431
+ self.keep_model(self.ensemble, ensemble_subpath)
432
+ self.ensemble.save(self._results_path, ensemble_subpath)
433
+ return True
434
+ return False
435
+
436
+ def can_we_stack_them(self, y):
437
+ # if multiclass and too many classes then No
438
+ return True
439
+
440
+ def get_stacked_data(self, X, mode="training"):
441
+ # mode can be `training` or `predict`
442
+ if self._stacked_models is None:
443
+ return X
444
+ all_oofs = []
445
+ for m in self._stacked_models:
446
+ oof = None
447
+ if mode == "training":
448
+ oof = m.get_out_of_folds()
449
+ else:
450
+ oof = m.predict(X)
451
+ if self._ml_task == BINARY_CLASSIFICATION:
452
+ cols = [f for f in oof.columns if "prediction" in f]
453
+ if len(cols) == 2:
454
+ oof = pd.DataFrame({"prediction": oof[cols[1]]})
455
+
456
+ cols = [f for f in oof.columns if "prediction" in f]
457
+ oof = oof[cols]
458
+ oof.columns = [f"{m.get_name()}_{c}" for c in cols]
459
+ all_oofs += [oof]
460
+
461
+ org_index = X.index.copy()
462
+ X.reset_index(drop=True, inplace=True)
463
+ X_stacked = pd.concat([X] + all_oofs, axis=1)
464
+
465
+ X_stacked.index = org_index.copy()
466
+ X.index = org_index.copy()
467
+ return X_stacked
468
+
469
+ def _perform_model_stacking(self):
470
+ if self._stacked_models is not None:
471
+ return
472
+
473
+ ldb = self.get_leaderboard(filter_random_feature=True)
474
+ if self._fairness_metric is not None:
475
+ # get only fair models if we train with sensitive features
476
+ ldb = ldb[ldb["is_fair"]]
477
+ ldb = ldb.sort_values(by="metric_value", ascending=True)
478
+ models_map = {m.get_name(): m for m in self._models if not m._is_stacked}
479
+ self._stacked_models = []
480
+ models_limit = 10
481
+
482
+ for model_type in np.unique(ldb.model_type):
483
+ if model_type in ["Baseline"]:
484
+ continue
485
+ ds = ldb[ldb.model_type == model_type].copy()
486
+ ds.sort_values(by="metric_value", inplace=True)
487
+
488
+ for n in list(ds.name.iloc[:models_limit].values):
489
+ self._stacked_models += [models_map[n]]
490
+
491
+ scores = [m.get_final_loss() for m in self._stacked_models]
492
+ self._stacked_models = [
493
+ self._stacked_models[i] for i in np.argsort(scores).tolist()
494
+ ]
495
+
496
+ def get_stacking_minimum_time_needed(self):
497
+ try:
498
+ ldb = self.get_leaderboard(filter_random_feature=True)
499
+ ldb = ldb.sort_values(by="metric_value", ascending=True)
500
+ return min(2.0 * ldb.iloc[0]["train_time"], 60)
501
+ except Exception as e:
502
+ return 60
503
+
504
+ def prepare_for_stacking(self):
505
+ # print("Stacked models ....")
506
+ # do we have enough models?
507
+ if len(self._models) < 5:
508
+ return
509
+ # do we have time?
510
+ if self._total_time_limit is not None:
511
+ time_left = self._total_time_limit - (time.time() - self._start_time)
512
+ # we need some time to start stacking
513
+ # it should be at least 60 seconds for larger data
514
+ # but for small data it can be less
515
+ if time_left < self.get_stacking_minimum_time_needed():
516
+ return
517
+ # too many classes and models
518
+ if self._ml_task == MULTICLASS_CLASSIFICATION:
519
+ if self.n_classes * len(self._models) > 1000:
520
+ return
521
+ # if we are training with sensitive features
522
+ # then we will stack only fair models
523
+ # if there are no fair models then we skip this step
524
+ if self._fairness_metric is not None:
525
+ if not [m for m in self._models if m.is_fair()]:
526
+ self.verbose_print("Skip stacking. We can stack only fair models.")
527
+ return
528
+
529
+ self._perform_model_stacking()
530
+
531
+ X_stacked_path = os.path.join(self._results_path, "X_stacked.data")
532
+ if os.path.exists(X_stacked_path):
533
+ return
534
+
535
+ X = load_data(self._X_path)
536
+ org_columns = X.columns.tolist()
537
+ X_stacked = self.get_stacked_data(X)
538
+ new_columns = X_stacked.columns.tolist()
539
+ added_columns = [c for c in new_columns if c not in org_columns]
540
+
541
+ # save stacked train data
542
+ dump_data(X_stacked_path, X_stacked)
543
+
544
+ """
545
+ # resue old params
546
+ for m in self._stacked_models:
547
+ # print(m.get_type())
548
+ # use only Xgboost, LightGBM and CatBoost as stacked models
549
+ if m.get_type() not in ["Xgboost", "LightGBM", "CatBoost"]:
550
+ continue
551
+ params = copy.deepcopy(m.params)
552
+ params["validation"]["X_train_path"] = X_train_stacked_path
553
+ params["name"] = params["name"] + "_Stacked"
554
+ params["is_stacked"] = True
555
+ # print(params)
556
+ if "model_architecture_json" in params["learner"]:
557
+ # the new model will be created with wider input size
558
+ del params["learner"]["model_architecture_json"]
559
+ if self._ml_task == REGRESSION:
560
+ # scale added predictions in regression if the target was scaled (in the case of NN)
561
+ target_preprocessing = params["preprocessing"]["target_preprocessing"]
562
+ scale = None
563
+ if "scale_log_and_normal" in target_preprocessing:
564
+ scale = "scale_log_and_normal"
565
+ elif "scale_normal" in target_preprocessing:
566
+ scale = "scale_normal"
567
+ if scale is not None:
568
+ for col in added_columns:
569
+ params["preprocessing"]["columns_preprocessing"][col] = [
570
+ scale]
571
+ self.train_model(params)
572
+ """
573
+
574
+ def _save_data(self, X, y, sample_weight=None, cv=None, sensitive_features=None):
575
+ # save information about original data
576
+ self._save_data_info(X, y, sample_weight, sensitive_features)
577
+
578
+ # handle drastic imbalance
579
+ # assure at least 20 samples of each class
580
+ # for binary and multiclass classification
581
+ self._handle_drastic_imbalance(X, y, sample_weight, sensitive_features)
582
+
583
+ # prepare path for saving files
584
+ self._X_path = os.path.join(self._results_path, "X.data")
585
+ self._y_path = os.path.join(self._results_path, "y.data")
586
+ self._sample_weight_path = None
587
+ if sample_weight is not None:
588
+ self._sample_weight_path = os.path.join(
589
+ self._results_path, "sample_weight.data"
590
+ )
591
+ dump_data(
592
+ self._sample_weight_path, pd.DataFrame({"sample_weight": sample_weight})
593
+ )
594
+ self._sensitive_features_path = None
595
+ if sensitive_features is not None:
596
+ self._sensitive_features_path = os.path.join(
597
+ self._results_path, "sensitive_features.data"
598
+ )
599
+ dump_data(self._sensitive_features_path, sensitive_features)
600
+
601
+ dump_data(self._X_path, X)
602
+
603
+ if self._ml_task == MULTICLASS_CLASSIFICATION:
604
+ y = y.astype(str)
605
+
606
+ dump_data(self._y_path, pd.DataFrame({"target": y}))
607
+
608
+ # set paths in validation parameters
609
+ self._validation_strategy["X_path"] = self._X_path
610
+ self._validation_strategy["y_path"] = self._y_path
611
+ self._validation_strategy["results_path"] = self._results_path
612
+ if sample_weight is not None:
613
+ self._validation_strategy["sample_weight_path"] = self._sample_weight_path
614
+ if sensitive_features is not None:
615
+ self._validation_strategy[
616
+ "sensitive_features_path"
617
+ ] = self._sensitive_features_path
618
+
619
+ if cv is not None:
620
+ self._validation_strategy["cv_path"] = os.path.join(
621
+ self._results_path, "cv.data"
622
+ )
623
+ joblib.dump(cv, self._validation_strategy["cv_path"])
624
+
625
+ if self._max_single_prediction_time is not None:
626
+ self._one_sample = X.iloc[:1].copy(deep=True)
627
+
628
+ def _handle_drastic_imbalance(
629
+ self, X, y, sample_weight=None, sensitive_features=None
630
+ ):
631
+ if self._ml_task == REGRESSION:
632
+ return
633
+ classes, cnts = np.unique(y, return_counts=True)
634
+ min_samples_per_class = 20
635
+ if self._validation_strategy is not None:
636
+ min_samples_per_class = max(
637
+ min_samples_per_class, self._validation_strategy.get("k_folds", 0)
638
+ )
639
+ for i in range(len(classes)):
640
+ if cnts[i] < min_samples_per_class:
641
+ append_samples = min_samples_per_class - cnts[i]
642
+ new_X = (
643
+ X[y == classes[i]]
644
+ .sample(n=append_samples, replace=True, random_state=1)
645
+ .reset_index(drop=True)
646
+ )
647
+ if sample_weight is not None:
648
+ new_sample_weight = (
649
+ sample_weight[y == classes[i]]
650
+ .sample(n=append_samples, replace=True, random_state=1)
651
+ .reset_index(drop=True)
652
+ )
653
+ if sensitive_features is not None:
654
+ new_sensitive_features = (
655
+ sensitive_features[y == classes[i]]
656
+ .sample(n=append_samples, replace=True, random_state=1)
657
+ .reset_index(drop=True)
658
+ )
659
+ for j in range(new_X.shape[0]):
660
+ X.loc[X.shape[0]] = new_X.loc[j]
661
+ y.loc[y.shape[0]] = classes[i]
662
+ if sample_weight is not None:
663
+ sample_weight.loc[
664
+ sample_weight.shape[0]
665
+ ] = new_sample_weight.loc[j]
666
+ if sensitive_features is not None:
667
+ sensitive_features.loc[
668
+ sensitive_features.shape[0]
669
+ ] = new_sensitive_features.loc[j]
670
+
671
+ def _save_data_info(self, X, y, sample_weight=None, sensitive_features=None):
672
+ target_is_numeric = pd.api.types.is_numeric_dtype(y)
673
+ if self._ml_task == MULTICLASS_CLASSIFICATION:
674
+ y = y.astype(str)
675
+
676
+ columns_and_target_info = DataInfo.compute(X, y, self._ml_task)
677
+
678
+ self.n_features_in_ = X.shape[1]
679
+ self.n_classes = len(np.unique(y[~pd.isnull(y)]))
680
+
681
+ self._data_info = {
682
+ "columns": X.columns.tolist(),
683
+ "rows": y.shape[0],
684
+ "cols": X.shape[1],
685
+ "target_is_numeric": target_is_numeric,
686
+ "columns_info": columns_and_target_info["columns_info"],
687
+ "target_info": columns_and_target_info["target_info"],
688
+ "n_features": self.n_features_in_,
689
+ "is_sample_weighted": sample_weight is not None,
690
+ "is_fairness_applied": sensitive_features is not None,
691
+ }
692
+ # Add n_classes if not regression
693
+ if self._ml_task != REGRESSION:
694
+ self._data_info["n_classes"] = self.n_classes
695
+
696
+ if columns_and_target_info.get("num_class") is not None:
697
+ self._data_info["num_class"] = columns_and_target_info["num_class"]
698
+ data_info_path = os.path.join(self._results_path, "data_info.json")
699
+ with open(data_info_path, "w") as fout:
700
+ fout.write(json.dumps(self._data_info, indent=4, cls=MLJSONEncoder))
701
+
702
+ def save_progress(self, step=None, generated_params=None):
703
+ if step is not None and generated_params is not None:
704
+ self._all_params[step] = generated_params
705
+
706
+ state = {}
707
+
708
+ state["fit_level"] = self._fit_level
709
+ state["time_controller"] = self._time_ctrl.to_json()
710
+ state["all_params"] = self._all_params
711
+ state["adjust_validation"] = self._adjust_validation
712
+
713
+ fname = os.path.join(self._results_path, "progress.json")
714
+ with open(fname, "w") as fout:
715
+ fout.write(json.dumps(state, indent=4, cls=MLJSONEncoder))
716
+
717
+ def load_progress(self):
718
+ state = {}
719
+ fname = os.path.join(self._results_path, "progress.json")
720
+ if not os.path.exists(fname):
721
+ return
722
+ with open(fname, "r") as file:
723
+ state = json.load(file)
724
+ self._fit_level = state.get("fit_level", self._fit_level)
725
+ self._all_params = state.get("all_params", self._all_params)
726
+ self._time_ctrl = TimeController.from_json(state.get("time_controller"))
727
+ self._adjust_validation = state.get("adjust_validation", False)
728
+
729
+ def _validate_X_predict(self, X):
730
+ """Validate X whenever one tries to predict, apply, predict_proba"""
731
+ # X = check_array(X, ensure_2d=False)
732
+ X = np.atleast_2d(X)
733
+ n_features = X.shape[1]
734
+ if self.n_features_in_ != n_features:
735
+ raise ValueError(
736
+ f"Number of features of the model must match the input. Model n_features_in_ is {self.n_features_in_} and input n_features is {n_features}. Reshape your data."
737
+ )
738
+
739
+ # This method builds pandas.Dataframe from input. The input can be numpy.ndarray, matrix, or pandas.Dataframe
740
+ # This method is used to build dataframes in `fit()` and in `predict`. That's the reason y can be None (`predict()` method)
741
+ def _build_dataframe(self, X, y=None, sample_weight=None, sensitive_features=None):
742
+ if X is None or X.shape[0] == 0:
743
+ raise AutoMLException("Empty input dataset")
744
+ # If Inputs are not pandas dataframes use scikit-learn validation for X array
745
+ if not isinstance(X, pd.DataFrame):
746
+ # Validate X as array
747
+ X = check_array(X, ensure_2d=False, ensure_all_finite=False)
748
+ # Force X to be 2D
749
+ X = np.atleast_2d(X)
750
+ # Create Pandas dataframe from np.arrays, columns get names with the schema: feature_{index}
751
+ X = pd.DataFrame(
752
+ X, columns=["feature_" + str(i) for i in range(1, len(X[0]) + 1)]
753
+ )
754
+ # Enforce column names
755
+ # Enforce X_train columns to be string
756
+ X.columns = X.columns.astype(str)
757
+
758
+ X.reset_index(drop=True, inplace=True)
759
+
760
+ if y is None:
761
+ return X
762
+
763
+ # Check if y is np.ndarray, transform to pd.Series
764
+ if isinstance(y, np.ndarray):
765
+ y = check_array(
766
+ y,
767
+ ensure_2d=False,
768
+ dtype="str" if PreprocessingUtils.is_categorical(y) else "numeric",
769
+ )
770
+ y = pd.Series(np.array(y), name="target")
771
+ # if pd.DataFrame, slice first column
772
+ elif isinstance(y, pd.DataFrame):
773
+ y = np.array(y.iloc[:, 0])
774
+ y = check_array(y, ensure_2d=False)
775
+ y = pd.Series(np.array(y), name="target")
776
+
777
+ if sample_weight is not None:
778
+ if isinstance(sample_weight, np.ndarray):
779
+ sample_weight = check_array(sample_weight, ensure_2d=False)
780
+ sample_weight = pd.Series(np.array(sample_weight), name="sample_weight")
781
+ elif isinstance(sample_weight, pd.DataFrame):
782
+ sample_weight = np.array(sample_weight.iloc[:, 0])
783
+ sample_weight = check_array(sample_weight, ensure_2d=False)
784
+ sample_weight = pd.Series(np.array(sample_weight), name="sample_weight")
785
+
786
+ if sensitive_features is not None:
787
+ if isinstance(sensitive_features, np.ndarray):
788
+ sensitive_features = check_array(sensitive_features, ensure_2d=False)
789
+ sensitive_features = pd.DataFrame(
790
+ sensitive_features,
791
+ columns=[
792
+ "sensitive_" + str(i)
793
+ for i in range(1, len(sensitive_features[0]) + 1)
794
+ ],
795
+ )
796
+ elif isinstance(sensitive_features, pd.Series):
797
+ sensitive_features = pd.DataFrame(sensitive_features)
798
+
799
+ X, y, sample_weight, sensitive_features = ExcludeRowsMissingTarget.transform(
800
+ X, y, sample_weight, sensitive_features, warn=True
801
+ )
802
+
803
+ X.reset_index(drop=True, inplace=True)
804
+ y.reset_index(drop=True, inplace=True)
805
+
806
+ if sample_weight is not None:
807
+ sample_weight.reset_index(drop=True, inplace=True)
808
+
809
+ if sensitive_features is not None:
810
+ sensitive_features.reset_index(drop=True, inplace=True)
811
+
812
+ for col in sensitive_features.columns:
813
+ if pd.api.types.is_numeric_dtype(sensitive_features[col].dtype):
814
+ self.verbose_print("Sensitive features should be categorical")
815
+ self.verbose_print(
816
+ f"Apply automatic binarization for feature {col}"
817
+ )
818
+ sensitive_features[col] = pd.DataFrame(
819
+ pd.qcut(sensitive_features[col], q=2).astype(str)
820
+ )
821
+ self.verbose_print(
822
+ f"New values {list(sensitive_features[col].unique())} for feature {col} are applied"
823
+ )
824
+
825
+ return X, y, sample_weight, sensitive_features
826
+
827
+ def _apply_constraints(self):
828
+ if "Neural Network" in self._algorithms and self._n_jobs != -1:
829
+ self._algorithms.remove("Neural Network")
830
+ self.verbose_print(
831
+ "Neural Network algorithm was disabled because it doesn't support n_jobs parameter."
832
+ )
833
+ if "Linear" in self._algorithms and not (
834
+ self.n_rows_in_ < 10000 and self.n_features_in_ < 1000
835
+ ):
836
+ self._algorithms.remove("Linear")
837
+ self.verbose_print("Linear algorithm was disabled.")
838
+
839
+ # remove algorithms in the case of multiclass
840
+ # and too many classes and columns
841
+ if self._ml_task == MULTICLASS_CLASSIFICATION:
842
+ if self.n_classes >= 10 and self.n_features_in_ * self.n_classes > 500:
843
+ if self.algorithms == "auto":
844
+ for a in ["CatBoost"]:
845
+ if a in self._algorithms:
846
+ self._algorithms.remove(a)
847
+
848
+ if self.n_features_in_ * self.n_classes > 1000:
849
+ if self.algorithms == "auto":
850
+ for a in ["Xgboost", "CatBoost"]:
851
+ if a in self._algorithms:
852
+ self._algorithms.remove(a)
853
+ if self.validation_strategy == "auto":
854
+ self._validation_strategy = {
855
+ "validation_type": "split",
856
+ "train_ratio": 0.9,
857
+ "shuffle": True,
858
+ }
859
+ if self._get_ml_task() != REGRESSION:
860
+ self._validation_strategy["stratify"] = True
861
+
862
+ if self.n_features_in_ * self.n_classes > 10000:
863
+ if self.algorithms == "auto":
864
+ for a in ["Random Forest", "Extra Trees"]:
865
+ if a in self._algorithms:
866
+ self._algorithms.remove(a)
867
+
868
+ # Adjust the validation type based on speed of Decision Tree learning
869
+ if (
870
+ self._get_mode() == "Compete"
871
+ and self._total_time_limit is not None
872
+ and self.validation_strategy == "auto"
873
+ and self._validation_strategy["validation_type"]
874
+ != "split" # split is the fastest validation type, no need to change
875
+ ):
876
+ # the validation will be adjusted after first Decision Tree learning on
877
+ # train/test split (1-fold)
878
+ self._adjust_validation = True
879
+ self._validation_strategy = self._fastest_validation()
880
+
881
+ def _fastest_validation(self):
882
+ strategy = {"validation_type": "split", "train_ratio": 0.9, "shuffle": True}
883
+ if self._get_ml_task() != REGRESSION:
884
+ strategy["stratify"] = True
885
+ return strategy
886
+
887
+ def _set_adjusted_validation(self):
888
+ if self._validation_strategy["validation_type"] != "split":
889
+ return
890
+ train_time = self._models[-1].get_train_time()
891
+ # the time of Decision Tree training multiply by 5.0
892
+ # to get the rough estimation how much time is needed for
893
+ # other algorithms
894
+ one_fold_time = train_time * 5.0
895
+ # it will be good to train at least 10 models
896
+ min_model_cnt = 10.0
897
+ # the number of folds we can afford during the training
898
+ folds_cnt = np.round(self._total_time_limit / one_fold_time / min_model_cnt)
899
+
900
+ # adjust the validation if possible
901
+ if folds_cnt >= 5.0:
902
+ self.verbose_print(f"Adjust validation. Remove: {self._model_subpaths[0]}")
903
+ k_folds = 5
904
+ if folds_cnt >= 15:
905
+ k_folds = 10
906
+ # too small dataset for stacking
907
+ if self.n_rows_in_ < 500:
908
+ self._stack_models = False
909
+ self.verbose_print(
910
+ "*** Disable stacking for small dataset (nrows < 500)"
911
+ )
912
+
913
+ self._validation_strategy["validation_type"] = "kfold"
914
+ del self._validation_strategy["train_ratio"]
915
+ self._validation_strategy["k_folds"] = k_folds
916
+ self.tuner._validation_strategy = self._validation_strategy
917
+ shutil.rmtree(
918
+ os.path.join(self._results_path, self._model_subpaths[0]),
919
+ ignore_errors=True,
920
+ )
921
+ del self._models[0]
922
+ del self._model_subpaths[0]
923
+ del self.tuner._unique_params_keys[0]
924
+ self._adjust_validation = False
925
+ cv = []
926
+ if self._validation_strategy.get("shuffle", False):
927
+ cv += ["Shuffle"]
928
+ if self._validation_strategy.get("stratify", False):
929
+ cv += ["Stratify"]
930
+ self.select_and_save_best() # save validation strategy
931
+
932
+ self.verbose_print(f"Validation strategy: {k_folds}-fold CV {','.join(cv)}")
933
+ else:
934
+ # cant stack models for train/test split
935
+ self._stack_models = False
936
+ self.verbose_print("Disable stacking for split validation")
937
+
938
+ self._apply_constraints_stack_models()
939
+
940
+ def _apply_constraints_stack_models(self):
941
+ if self._validation_strategy["validation_type"] == "split":
942
+ if self._stack_models:
943
+ self.verbose_print("Disable stacking for split validation")
944
+ self._stack_models = False
945
+ self._boost_on_errors = False
946
+ if "repeats" in self._validation_strategy:
947
+ if self._stack_models:
948
+ self.verbose_print("Disable stacking for repeated validation")
949
+ self._stack_models = False
950
+ self._boost_on_errors = False
951
+
952
+ # update Tuner
953
+ if self.tuner is not None:
954
+ self.tuner._stack_models = self._stack_models
955
+ self.tuner._boost_on_errors = self._boost_on_errors
956
+
957
+ # update Time Controler
958
+ if self._time_ctrl is not None:
959
+ self._time_ctrl._is_stacking = self._stack_models
960
+
961
+ if "stack" in self._time_ctrl._steps and not self._stack_models:
962
+ self._time_ctrl._steps.remove("stack")
963
+ if (
964
+ "boost_on_errors" in self._time_ctrl._steps
965
+ and not self._boost_on_errors
966
+ ):
967
+ self._time_ctrl._steps.remove("boost_on_errors")
968
+
969
+ def _fit(self, X, y, sample_weight=None, cv=None, sensitive_features=None):
970
+ """Fits the AutoML model with data"""
971
+ if self._fit_level == "finished":
972
+ print(
973
+ "This model has already been fitted. You can use predict methods or select a new 'results_path' for a new a 'fit()'."
974
+ )
975
+ return
976
+ # Validate input and build dataframes
977
+ X, y, sample_weight, sensitive_features = self._build_dataframe(
978
+ X, y, sample_weight, sensitive_features
979
+ )
980
+
981
+ self.n_rows_in_ = X.shape[0]
982
+ self.n_features_in_ = X.shape[1]
983
+ self.n_classes = len(np.unique(y[~pd.isnull(y)]))
984
+
985
+ # Get attributes (__init__ params)
986
+ self._mode = self._get_mode()
987
+ self._ml_task = self._get_ml_task()
988
+ self._results_path = self._get_results_path()
989
+ self._total_time_limit = self._get_total_time_limit()
990
+ self._model_time_limit = self._get_model_time_limit()
991
+ self._algorithms = self._get_algorithms()
992
+ self._train_ensemble = self._get_train_ensemble()
993
+ self._stack_models = self._get_stack_models()
994
+ self._eval_metric = self._get_eval_metric()
995
+ self._validation_strategy = self._get_validation_strategy()
996
+ self._verbose = self._get_verbose()
997
+ self._explain_level = self._get_explain_level()
998
+ self._golden_features = self._get_golden_features()
999
+ self._features_selection = self._get_features_selection()
1000
+ self._start_random_models = self._get_start_random_models()
1001
+ self._hill_climbing_steps = self._get_hill_climbing_steps()
1002
+ self._top_models_to_improve = self._get_top_models_to_improve()
1003
+ self._boost_on_errors = self._get_boost_on_errors()
1004
+ self._kmeans_features = self._get_kmeans_features()
1005
+ self._mix_encoding = self._get_mix_encoding()
1006
+ self._max_single_prediction_time = self._get_max_single_prediction_time()
1007
+ self._optuna_time_budget = self._get_optuna_time_budget()
1008
+ self._optuna_init_params = self._get_optuna_init_params()
1009
+ self._optuna_verbose = self._get_optuna_verbose()
1010
+ self._n_jobs = self._get_n_jobs()
1011
+ self._random_state = self._get_random_state()
1012
+
1013
+ if sensitive_features is not None:
1014
+ self._fairness_metric = self._get_fairness_metric()
1015
+ self._fairness_threshold = self._get_fairness_threshold()
1016
+ self._privileged_groups = self._get_privileged_groups()
1017
+ self._underprivileged_groups = self._get_underprivileged_groups()
1018
+
1019
+ self._adjust_validation = False
1020
+ self._apply_constraints()
1021
+ if not self._adjust_validation:
1022
+ # if there is no validation adjustement
1023
+ # then we can apply stack_models constraints immediately
1024
+ # if there is validation adjustement
1025
+ # then we will apply contraints after the adjustement
1026
+ self._apply_constraints_stack_models()
1027
+
1028
+ try:
1029
+ self.load_progress()
1030
+ if self._fit_level == "finished":
1031
+ print(
1032
+ "This model has already been fitted. You can use predict methods or select a new 'results_path' for a new 'fit()'."
1033
+ )
1034
+ return
1035
+ self._check_can_load()
1036
+
1037
+ self.verbose_print(f"AutoML directory: {self._results_path}")
1038
+ if self._mode == "Optuna":
1039
+ ttl = int(len(self._algorithms) * self._optuna_time_budget)
1040
+ self.verbose_print("Expected computing time:")
1041
+ self.verbose_print(
1042
+ f"Time for tuning with Optuna: len(algorithms) * optuna_time_budget = {int(len(self._algorithms) * self._optuna_time_budget)} seconds"
1043
+ )
1044
+ self.verbose_print(
1045
+ f"There is no time limit for ML model training after Optuna tuning (total_time_limit parameter is ignored)."
1046
+ )
1047
+
1048
+ self.verbose_print(
1049
+ f"The task is {self._ml_task} with evaluation metric {self._eval_metric}"
1050
+ )
1051
+ self.verbose_print(f"AutoML will use algorithms: {self._algorithms}")
1052
+ if self._stack_models:
1053
+ self.verbose_print("AutoML will stack models")
1054
+ if self._train_ensemble:
1055
+ self.verbose_print("AutoML will ensemble available models")
1056
+
1057
+ self._start_time = time.time()
1058
+ if self._time_ctrl is not None:
1059
+ self._start_time -= self._time_ctrl.already_spend()
1060
+
1061
+ # Automatic Exloratory Data Analysis
1062
+ # I disabled EDA, because it won't be supported
1063
+ # I recomend use pandas_profiling or Sweetviz
1064
+ # if self._explain_level == 2:
1065
+ # EDA.compute(X, y, os.path.join(self._results_path, "EDA"))
1066
+
1067
+ # Save data
1068
+
1069
+ self._save_data(
1070
+ X.copy(deep=False),
1071
+ y.copy(deep=False),
1072
+ None if sample_weight is None else sample_weight.copy(deep=False),
1073
+ cv,
1074
+ None
1075
+ if sensitive_features is None
1076
+ else sensitive_features.copy(deep=False),
1077
+ )
1078
+
1079
+ tuner = MljarTuner(
1080
+ self._get_tuner_params(
1081
+ self._start_random_models,
1082
+ self._hill_climbing_steps,
1083
+ self._top_models_to_improve,
1084
+ ),
1085
+ self._algorithms,
1086
+ self._ml_task,
1087
+ self._eval_metric,
1088
+ self._validation_strategy,
1089
+ self._explain_level,
1090
+ self._data_info,
1091
+ self._golden_features,
1092
+ self._features_selection,
1093
+ self._train_ensemble,
1094
+ self._stack_models,
1095
+ self._adjust_validation,
1096
+ self._boost_on_errors,
1097
+ self._kmeans_features,
1098
+ self._mix_encoding,
1099
+ self._optuna_time_budget,
1100
+ self._optuna_init_params,
1101
+ self._optuna_verbose,
1102
+ self._n_jobs,
1103
+ self._random_state,
1104
+ self._fairness_metric,
1105
+ self._fairness_threshold,
1106
+ self._privileged_groups,
1107
+ self._underprivileged_groups,
1108
+ )
1109
+ self.tuner = tuner
1110
+
1111
+ steps = tuner.steps()
1112
+ self.verbose_print(
1113
+ f'AutoML steps: {[s for s in steps if "update_" not in s]}'
1114
+ )
1115
+ if self._time_ctrl is None:
1116
+ self._time_ctrl = TimeController(
1117
+ self._start_time,
1118
+ self._total_time_limit,
1119
+ self._model_time_limit,
1120
+ steps,
1121
+ self._algorithms,
1122
+ )
1123
+
1124
+ self._time_ctrl.log_time(
1125
+ "prepare_data",
1126
+ "prepare_data",
1127
+ "prepare_data",
1128
+ time.time() - self._start_time,
1129
+ )
1130
+
1131
+ for step in steps:
1132
+ self._fit_level = step
1133
+ start = time.time()
1134
+ # self._time_start[step] = start
1135
+
1136
+ if step in ["stack", "ensemble_stacked"] and not self._stack_models:
1137
+ continue
1138
+
1139
+ if step == "stack":
1140
+ self.prepare_for_stacking()
1141
+ if "hill_climbing" in step or step in ["ensemble", "stack"]:
1142
+ if len(self._models) == 0:
1143
+ raise AutoMLException(
1144
+ "No models produced. \nPlease check your data or"
1145
+ " submit a Github issue at https://github.com/mljar/mljar-supervised/issues/new."
1146
+ )
1147
+
1148
+ generated_params = []
1149
+ if step in self._all_params:
1150
+ generated_params = self._all_params[step]
1151
+ else:
1152
+ generated_params = tuner.generate_params(
1153
+ step,
1154
+ self._models,
1155
+ self._results_path,
1156
+ self._stacked_models,
1157
+ self._total_time_limit,
1158
+ )
1159
+
1160
+ if generated_params is None or not generated_params:
1161
+ if "_update_" not in step:
1162
+ self.verbose_print(
1163
+ f"Skip {step} because no parameters were generated."
1164
+ )
1165
+ continue
1166
+ if generated_params:
1167
+ if not self._time_ctrl.enough_time_for_step(self._fit_level):
1168
+ self.verbose_print(f"Skip {step} because of the time limit.")
1169
+ continue
1170
+ else:
1171
+ model_str = "models" if len(generated_params) > 1 else "model"
1172
+ self.verbose_print(
1173
+ f"* Step {step} will try to check up to {len(generated_params)} {model_str}"
1174
+ )
1175
+
1176
+ for params in generated_params:
1177
+ if params.get("status", "") in ["trained", "skipped", "error"]:
1178
+ self.verbose_print(f"{params['name']}: {params['status']}.")
1179
+ continue
1180
+
1181
+ try:
1182
+ trained = False
1183
+ if "ensemble" in step:
1184
+ trained = self.ensemble_step(
1185
+ is_stacked=params["is_stacked"]
1186
+ )
1187
+ else:
1188
+ trained = self.train_model(params)
1189
+ params["status"] = "trained" if trained else "skipped"
1190
+ params["final_loss"] = self._models[-1].get_final_loss()
1191
+ params["train_time"] = self._models[-1].get_train_time()
1192
+
1193
+ if (
1194
+ self._adjust_validation
1195
+ and len(self._models) == 1
1196
+ and step == "adjust_validation"
1197
+ ):
1198
+ self._set_adjusted_validation()
1199
+
1200
+ except NotTrainedException as e:
1201
+ params["status"] = "error"
1202
+ self.verbose_print(
1203
+ params.get("name") + " not trained. " + str(e)
1204
+ )
1205
+ except Exception as e:
1206
+ import traceback
1207
+
1208
+ self._update_errors_report(
1209
+ params.get("name"), str(e) + "\n" + traceback.format_exc()
1210
+ )
1211
+ params["status"] = "error"
1212
+
1213
+ self.save_progress(step, generated_params)
1214
+
1215
+ if not self._models:
1216
+ raise AutoMLException("No models produced.")
1217
+ self._fit_level = "finished"
1218
+ self.save_progress()
1219
+ self.select_and_save_best(show_warnings=True)
1220
+
1221
+ self.verbose_print(
1222
+ f"AutoML fit time: {np.round(time.time() - self._start_time,2)} seconds"
1223
+ )
1224
+ self.verbose_print(f"AutoML best model: {self._best_model.get_name()}")
1225
+
1226
+ if self._fairness_metric is not None:
1227
+ # check if we have fair model
1228
+ has_fair_model = False
1229
+ for m in self._models:
1230
+ if m.is_fair():
1231
+ has_fair_model = True
1232
+ break
1233
+ if not has_fair_model:
1234
+ self.verbose_print(
1235
+ "AutoML can't construct model that meets your fairness criteria."
1236
+ )
1237
+ self.verbose_print("What you can do?")
1238
+ self.verbose_print(
1239
+ "1. Please include more samples that are not biased."
1240
+ )
1241
+ self.verbose_print(
1242
+ "2. Please examine the most unfairly treated samples."
1243
+ )
1244
+ self.verbose_print("3. Please change fairness threshold.")
1245
+
1246
+ except Exception as e:
1247
+ raise e
1248
+
1249
+ return self
1250
+
1251
+ def _update_errors_report(self, model_name, error_msg):
1252
+ """Append error message to errors.md file."""
1253
+ errors_filename = os.path.join(self._get_results_path(), "errors.md")
1254
+ with open(errors_filename, "a") as fout:
1255
+ self.verbose_print(f"There was an error during {model_name} training.")
1256
+ self.verbose_print(f"Please check {errors_filename} for details.")
1257
+ fout.write(f"## Error for {model_name}\n\n")
1258
+ fout.write(error_msg)
1259
+ link = "https://github.com/mljar/mljar-supervised/issues/new"
1260
+ fout.write(
1261
+ f"\n\nPlease set a GitHub issue with above error message at: {link}"
1262
+ )
1263
+ fout.write("\n\n")
1264
+
1265
+ def select_and_save_best(self, show_warnings=False):
1266
+ # Select best model based on the lowest loss
1267
+ self._best_model = None
1268
+
1269
+ if self._models:
1270
+ if self._fairness_metric is not None:
1271
+ models = [
1272
+ m
1273
+ for m in self._models
1274
+ if m.is_valid()
1275
+ # and m.is_fast_enough(self._max_single_prediction_time)
1276
+ and m.is_fair()
1277
+ ]
1278
+
1279
+ if models:
1280
+ # if there are fair models, we select the one with best performance
1281
+ self._best_model = min(
1282
+ models,
1283
+ key=lambda x: x.get_final_loss(),
1284
+ )
1285
+ else:
1286
+ # if no models are fair, we select the most fair model
1287
+ if "ratio" in self._fairness_metric.lower():
1288
+ self._best_model = max(
1289
+ [m for m in self._models if m.is_valid()],
1290
+ key=lambda x: x.get_best_fairness(),
1291
+ )
1292
+ else:
1293
+ self._best_model = min(
1294
+ [m for m in self._models if m.is_valid()],
1295
+ key=lambda x: x.get_best_fairness(),
1296
+ )
1297
+
1298
+ else:
1299
+ model_list = [
1300
+ m
1301
+ for m in self._models
1302
+ if m.is_valid()
1303
+ and m.is_fast_enough(self._max_single_prediction_time)
1304
+ ]
1305
+ if model_list:
1306
+ self._best_model = min(
1307
+ model_list,
1308
+ key=lambda x: x.get_final_loss(),
1309
+ )
1310
+ # if none selected please select again and warn the user
1311
+ if (
1312
+ len(self._models)
1313
+ and self._best_model is None
1314
+ and self._max_single_prediction_time is not None
1315
+ ):
1316
+ if show_warnings:
1317
+ msg = (
1318
+ "*" * 64
1319
+ + "\nThere were no model with prediction time smaller than the limit.\n"
1320
+ + "Please increase the prediction time for single sample,\n"
1321
+ + "or please to use train/test split for validation\n"
1322
+ + "*" * 64
1323
+ )
1324
+ self.verbose_print(msg)
1325
+
1326
+ self._best_model = min(
1327
+ [m for m in self._models if m.is_valid()],
1328
+ key=lambda x: x.get_final_loss(),
1329
+ )
1330
+
1331
+ with open(os.path.join(self._results_path, "params.json"), "w") as fout:
1332
+ params = {
1333
+ "mode": self._mode,
1334
+ "ml_task": self._ml_task,
1335
+ "results_path": self._results_path,
1336
+ "total_time_limit": self._total_time_limit,
1337
+ "model_time_limit": self._model_time_limit,
1338
+ "algorithms": self._algorithms,
1339
+ "train_ensemble": self._train_ensemble,
1340
+ "stack_models": self._stack_models,
1341
+ "eval_metric": self._eval_metric,
1342
+ "validation_strategy": self._validation_strategy,
1343
+ "verbose": self._verbose,
1344
+ "explain_level": self._explain_level,
1345
+ "golden_features": self._golden_features,
1346
+ "features_selection": self._features_selection,
1347
+ "start_random_models": self._start_random_models,
1348
+ "hill_climbing_steps": self._hill_climbing_steps,
1349
+ "top_models_to_improve": self._top_models_to_improve,
1350
+ "boost_on_errors": self._boost_on_errors,
1351
+ "kmeans_features": self._kmeans_features,
1352
+ "mix_encoding": self._mix_encoding,
1353
+ "max_single_prediction_time": self._max_single_prediction_time,
1354
+ "n_jobs": self._n_jobs,
1355
+ "random_state": self._random_state,
1356
+ "saved": self._model_subpaths,
1357
+ "fit_level": self._fit_level,
1358
+ }
1359
+ if self._best_model is not None:
1360
+ params["best_model"] = self._best_model.get_name()
1361
+ load_on_predict = []
1362
+ load_on_predict += self._best_model.involved_model_names()
1363
+ if self._best_model._is_stacked and self._stacked_models is not None:
1364
+ for m in self._stacked_models:
1365
+ load_on_predict += m.involved_model_names()
1366
+ params["load_on_predict"] = list(np.unique(load_on_predict))
1367
+
1368
+ if self._stacked_models is not None:
1369
+ params["stacked"] = [m.get_name() for m in self._stacked_models]
1370
+ fout.write(json.dumps(params, indent=4, cls=MLJSONEncoder))
1371
+
1372
+ if self._models:
1373
+ ldb = self.get_leaderboard(original_metric_values=True)
1374
+ ldb.to_csv(os.path.join(self._results_path, "leaderboard.csv"), index=False)
1375
+
1376
+ # save report
1377
+ ldb.insert(loc=0, column="Best model", value="")
1378
+ ldb.loc[
1379
+ ldb.name == self._best_model.get_name(), "Best model"
1380
+ ] = "**the best**"
1381
+ ldb["name"] = [f"[{m}]({m}/README.md)" for m in ldb["name"].values]
1382
+
1383
+ with open(os.path.join(self._results_path, "README.md"), "w") as fout:
1384
+ fout.write(f"# AutoML Leaderboard\n\n")
1385
+ fout.write(tabulate(ldb.values, ldb.columns, tablefmt="pipe"))
1386
+ LeaderboardPlots.compute(
1387
+ ldb, self._results_path, fout, self._fairness_threshold
1388
+ )
1389
+
1390
+ if self._fit_level == "finished":
1391
+ AutoMLPlots.add(self._results_path, self._models, fout)
1392
+
1393
+ def get_ensemble_models(self, ensemble_name="Ensemble"):
1394
+ try:
1395
+ with open(os.path.join(self.results_path, ensemble_name, "ensemble.json")) as file:
1396
+ params = json.load(file)
1397
+ return [m["model"] for m in params["selected_models"]]
1398
+ except Exception as e:
1399
+ return []
1400
+
1401
+ def models_needed_on_predict(self, required_model_name):
1402
+ with open(os.path.join(self.results_path, "params.json")) as file:
1403
+ params = json.load(file)
1404
+ saved_models = params.get("saved", [])
1405
+ stacked_models = params.get("stacked", [])
1406
+
1407
+ if required_model_name not in saved_models:
1408
+ raise AutoMLException(
1409
+ f"Can't load model {required_model_name}. Please check if the model's name is correct."
1410
+ )
1411
+ # single model needed
1412
+ if (
1413
+ "Stacked" not in required_model_name
1414
+ and "Ensemble" not in required_model_name
1415
+ ):
1416
+ return [required_model_name]
1417
+ ensemble_models = self.get_ensemble_models("Ensemble")
1418
+ # ensemble of single models
1419
+ if required_model_name == "Ensemble":
1420
+ return ensemble_models + [required_model_name]
1421
+ # single model on stacked data
1422
+ if required_model_name != "Stacked_Ensemble":
1423
+ return list(
1424
+ np.unique(
1425
+ ensemble_models
1426
+ + ["Ensemble"]
1427
+ + stacked_models
1428
+ + [required_model_name]
1429
+ )
1430
+ )
1431
+ # must be stacked ensemble
1432
+ stacked_ensemble_models = self.get_ensemble_models("Stacked_Ensemble")
1433
+ return list(
1434
+ np.unique(
1435
+ ensemble_models
1436
+ + ["Ensemble"]
1437
+ + stacked_models
1438
+ + stacked_ensemble_models
1439
+ + [required_model_name]
1440
+ )
1441
+ )
1442
+
1443
+ def _base_predict(self, X, model=None):
1444
+ if model is None:
1445
+ if self._best_model is None:
1446
+ self.load(self.results_path)
1447
+ model = self._best_model
1448
+
1449
+ if model is None:
1450
+ raise AutoMLException(
1451
+ "This model has not been fitted yet. Please call `fit()` first."
1452
+ )
1453
+
1454
+ X = self._build_dataframe(X)
1455
+ if not isinstance(X.columns[0], str):
1456
+ X.columns = [str(c) for c in X.columns]
1457
+
1458
+ input_columns = X.columns.tolist()
1459
+ for column in self._data_info["columns"]:
1460
+ if column not in input_columns:
1461
+ raise AutoMLException(
1462
+ f"Missing column: {column} in input data. Cannot predict"
1463
+ )
1464
+
1465
+ X = X[self._data_info["columns"]]
1466
+ self._validate_X_predict(X)
1467
+
1468
+ # is stacked model
1469
+ if model._is_stacked:
1470
+ self._perform_model_stacking()
1471
+ X_stacked = self.get_stacked_data(X, mode="predict")
1472
+
1473
+ if model.get_type() == "Ensemble":
1474
+ # Ensemble is using both original and stacked data
1475
+ predictions = model.predict(X, X_stacked)
1476
+ else:
1477
+ predictions = model.predict(X_stacked)
1478
+ else:
1479
+ predictions = model.predict(X)
1480
+
1481
+ if self._ml_task == BINARY_CLASSIFICATION:
1482
+ # need to predict the label based on predictions and threshold
1483
+ neg_label, pos_label = (
1484
+ predictions.columns[0][11:],
1485
+ predictions.columns[1][11:],
1486
+ )
1487
+
1488
+ if neg_label == "0" and pos_label == "1":
1489
+ neg_label, pos_label = 0, 1
1490
+ target_is_numeric = self._data_info.get("target_is_numeric", False)
1491
+ if target_is_numeric:
1492
+ neg_label = int(neg_label)
1493
+ pos_label = int(pos_label)
1494
+ # assume that it is binary classification
1495
+ predictions["label"] = predictions.iloc[:, 1] > model._threshold
1496
+ predictions["label"] = predictions["label"].map(
1497
+ {True: pos_label, False: neg_label}
1498
+ )
1499
+ return predictions
1500
+ elif self._ml_task == MULTICLASS_CLASSIFICATION:
1501
+ target_is_numeric = self._data_info.get("target_is_numeric", False)
1502
+ if target_is_numeric:
1503
+ try:
1504
+ predictions["label"] = predictions["label"].astype(int)
1505
+ except Exception as e:
1506
+ predictions["label"] = predictions["label"].astype(float)
1507
+ return predictions
1508
+ # Regression
1509
+ else:
1510
+ return predictions
1511
+
1512
+ def _predict(self, X):
1513
+ predictions = self._base_predict(X)
1514
+ # Return predictions
1515
+ # If classification task the result is in column 'label'
1516
+ # If regression task the result is in column 'prediction'
1517
+ return (
1518
+ predictions["label"].to_numpy()
1519
+ if self._ml_task != REGRESSION
1520
+ else predictions["prediction"].to_numpy()
1521
+ )
1522
+
1523
+ def _predict_proba(self, X):
1524
+ # Check is task type is correct
1525
+ if self._ml_task == REGRESSION:
1526
+ raise AutoMLException(
1527
+ f"Method `predict_proba()` can only be used when in classification tasks. Current task: '{self._ml_task}'."
1528
+ )
1529
+
1530
+ # Make and return predictions
1531
+ # If classification task the result is in column 'label'
1532
+ # Need to drop `label` column.
1533
+ return self._base_predict(X).drop(["label"], axis=1).to_numpy()
1534
+
1535
+ def _predict_all(self, X):
1536
+ # Make and return predictions
1537
+ return self._base_predict(X)
1538
+
1539
+ def _score(self, X, y=None, sample_weight=None):
1540
+ # y default must be None for scikit-learn compatibility
1541
+
1542
+ # Check if y is None
1543
+ if y is None:
1544
+ raise AutoMLException("y must be specified.")
1545
+
1546
+ predictions = self._predict(X)
1547
+ return (
1548
+ r2_score(y, predictions, sample_weight=sample_weight)
1549
+ if self._ml_task == REGRESSION
1550
+ else accuracy_score(y, predictions, sample_weight=sample_weight)
1551
+ )
1552
+
1553
+ def _get_mode(self):
1554
+ """Gets the current mode"""
1555
+ self._validate_mode()
1556
+ return deepcopy(self.mode)
1557
+
1558
+ def _get_ml_task(self):
1559
+ """Gets the current ml_task. If "auto" it is determined"""
1560
+ self._validate_ml_task()
1561
+ if self.ml_task == "auto":
1562
+ classes_number = self.n_classes
1563
+ if classes_number == 2:
1564
+ self._estimator_type = "classifier" # for sk-learn api
1565
+ return BINARY_CLASSIFICATION
1566
+ elif classes_number <= 20:
1567
+ self._estimator_type = "classifier" # for sk-learn api
1568
+ return MULTICLASS_CLASSIFICATION
1569
+ else:
1570
+ self._estimator_type = "regressor" # for sk-learn api
1571
+ return REGRESSION
1572
+ else:
1573
+ return deepcopy(self.ml_task)
1574
+
1575
+ def _get_results_path(self):
1576
+ """Gets the current results_path"""
1577
+ # if we already have the results path set, please return it
1578
+ if self._results_path is not None:
1579
+ return self._results_path
1580
+
1581
+ self._validate_results_path()
1582
+
1583
+ path = self.results_path
1584
+
1585
+ if path is None:
1586
+ for i in range(1, 10001):
1587
+ name = f"AutoML_{i}"
1588
+ if not os.path.exists(name):
1589
+ self.create_dir(name)
1590
+ self._results_path = name
1591
+ return name
1592
+ # If it got here, could not create, raise expection
1593
+ raise AutoMLException("Cannot create directory for AutoML results")
1594
+ elif os.path.exists(self.results_path) and os.path.exists(
1595
+ os.path.join(self.results_path, "params.json")
1596
+ ): # AutoML already loaded, return path
1597
+ self._results_path = path
1598
+ return path
1599
+ # Dir does not exist, create it
1600
+ elif not os.path.exists(path):
1601
+ self.create_dir(path)
1602
+ self._results_path = path
1603
+ return path
1604
+ # Dir exists and is empty, use it
1605
+ elif os.path.exists(path) and not len(os.listdir(path)):
1606
+ self._results_path = path
1607
+ return path
1608
+ elif os.path.exists(path) and len(os.listdir(path)):
1609
+ raise AutoMLException(
1610
+ f"Cannot set directory for AutoML. Directory '{path}' is not empty."
1611
+ )
1612
+
1613
+ raise AutoMLException("Cannot set directory for AutoML results")
1614
+
1615
+ def _get_total_time_limit(self):
1616
+ """Gets the current total_time_limit"""
1617
+ self._validate_total_time_limit()
1618
+ if self._get_mode() == "Optuna":
1619
+ return None # there no training limit for model in the Optuna mode
1620
+ # just train and be happy with super models :)
1621
+ return deepcopy(self.total_time_limit)
1622
+
1623
+ def _get_model_time_limit(self):
1624
+ """Gets the current model_time_limit"""
1625
+ self._validate_model_time_limit()
1626
+ return deepcopy(self.model_time_limit)
1627
+
1628
+ def _get_algorithms(self):
1629
+ """Gets the current algorithms. If "auto" it is determined"""
1630
+ self._validate_algorithms()
1631
+ if self.algorithms == "auto":
1632
+ if self._get_mode() == "Explain":
1633
+ return [
1634
+ "Baseline",
1635
+ "Linear",
1636
+ "Decision Tree",
1637
+ "Random Forest",
1638
+ "Xgboost",
1639
+ "Neural Network",
1640
+ ]
1641
+ if self._get_mode() == "Perform":
1642
+ return [
1643
+ "Linear",
1644
+ "Random Forest",
1645
+ "LightGBM",
1646
+ "Xgboost",
1647
+ "CatBoost",
1648
+ "Neural Network",
1649
+ ]
1650
+ if self._get_mode() == "Compete":
1651
+ return [
1652
+ "Decision Tree",
1653
+ "Linear",
1654
+ "Random Forest",
1655
+ "Extra Trees",
1656
+ "LightGBM",
1657
+ "Xgboost",
1658
+ "CatBoost",
1659
+ "Neural Network",
1660
+ "Nearest Neighbors",
1661
+ ]
1662
+ if self._get_mode() == "Optuna":
1663
+ return [
1664
+ "Random Forest",
1665
+ "Extra Trees",
1666
+ "LightGBM",
1667
+ "Xgboost",
1668
+ "CatBoost",
1669
+ "Neural Network",
1670
+ ]
1671
+ else:
1672
+ return deepcopy(self.algorithms)
1673
+
1674
+ def _get_train_ensemble(self):
1675
+ """Gets the current train_ensemble"""
1676
+ self._validate_train_ensemble()
1677
+ return deepcopy(self.train_ensemble)
1678
+
1679
+ def _get_stack_models(self):
1680
+ """Gets the current stack_models"""
1681
+ self._validate_stack_models()
1682
+ if self.stack_models == "auto":
1683
+ val = self._get_validation_strategy()
1684
+ if val.get("validation_type", "") == "custom":
1685
+ return False
1686
+ return True if self.mode in ["Compete", "Optuna"] else False
1687
+ else:
1688
+ return deepcopy(self.stack_models)
1689
+
1690
+ def _get_eval_metric(self):
1691
+ """Gets the current eval_metric"""
1692
+ self._validate_eval_metric()
1693
+ if isinstance(self.eval_metric, types.FunctionType):
1694
+ UserDefinedEvalMetric().set_metric(self.eval_metric)
1695
+ return "user_defined_metric"
1696
+
1697
+ if self.eval_metric == "auto":
1698
+ if self._get_ml_task() == BINARY_CLASSIFICATION:
1699
+ return "logloss"
1700
+ elif self._get_ml_task() == MULTICLASS_CLASSIFICATION:
1701
+ return "logloss"
1702
+ elif self._get_ml_task() == REGRESSION:
1703
+ return "rmse"
1704
+ else:
1705
+ return deepcopy(self.eval_metric)
1706
+
1707
+ def _get_validation_strategy(self):
1708
+ """Gets the current validation_strategy"""
1709
+ strat = {}
1710
+ self._validate_validation_strategy()
1711
+ if self.validation_strategy == "auto":
1712
+ if self._get_mode() == "Explain":
1713
+ strat = {
1714
+ "validation_type": "split",
1715
+ "train_ratio": 0.75,
1716
+ "shuffle": True,
1717
+ "stratify": True,
1718
+ }
1719
+ elif self._get_mode() == "Perform":
1720
+ strat = {
1721
+ "validation_type": "kfold",
1722
+ "k_folds": 5,
1723
+ "shuffle": True,
1724
+ "stratify": True,
1725
+ }
1726
+ elif self._get_mode() in ["Compete", "Optuna"]:
1727
+ strat = {
1728
+ "validation_type": "kfold",
1729
+ "k_folds": 10,
1730
+ "shuffle": True,
1731
+ "stratify": True,
1732
+ }
1733
+ if self._get_ml_task() == REGRESSION:
1734
+ if "stratify" in strat:
1735
+ # it's better to always check
1736
+ # before delete (trust me)
1737
+ del strat["stratify"]
1738
+ return strat
1739
+ else:
1740
+ strat = deepcopy(self.validation_strategy)
1741
+ if self._get_ml_task() == REGRESSION:
1742
+ if "stratify" in strat:
1743
+ del strat["stratify"]
1744
+ return strat
1745
+
1746
+ def _get_verbose(self):
1747
+ """Gets the current verbose"""
1748
+ self._validate_verbose()
1749
+ return deepcopy(self.verbose)
1750
+
1751
+ def _get_explain_level(self):
1752
+ """Gets the current explain_level"""
1753
+ self._validate_explain_level()
1754
+ if self.explain_level == "auto":
1755
+ if self._get_mode() == "Explain":
1756
+ return 2
1757
+ if self._get_mode() == "Perform":
1758
+ return 1
1759
+ if self._get_mode() == "Compete":
1760
+ return 0
1761
+ if self._get_mode() == "Optuna":
1762
+ return 0
1763
+ else:
1764
+ return deepcopy(self.explain_level)
1765
+
1766
+ def _get_golden_features(self):
1767
+ self._validate_golden_features()
1768
+ if self.golden_features == "auto":
1769
+ if self._get_mode() == "Explain":
1770
+ return False
1771
+ if self._get_mode() == "Perform":
1772
+ return True
1773
+ if self._get_mode() == "Compete":
1774
+ return True
1775
+ if self._get_mode() == "Optuna":
1776
+ return False
1777
+ else:
1778
+ return deepcopy(self.golden_features)
1779
+
1780
+ def _get_features_selection(self):
1781
+ """Gets the current features_selection"""
1782
+ self._validate_features_selection()
1783
+ if self.features_selection == "auto":
1784
+ if self._get_mode() == "Explain":
1785
+ return False
1786
+ if self._get_mode() == "Perform":
1787
+ return True
1788
+ if self._get_mode() == "Compete":
1789
+ return True
1790
+ if self._get_mode() == "Optuna":
1791
+ return False
1792
+ else:
1793
+ return deepcopy(self.features_selection)
1794
+
1795
+ def _get_start_random_models(self):
1796
+ """Gets the current start_random_models"""
1797
+ self._validate_start_random_models()
1798
+ if self.start_random_models == "auto":
1799
+ if self._get_mode() == "Explain":
1800
+ return 1
1801
+ if self._get_mode() == "Perform":
1802
+ return 5
1803
+ if self._get_mode() == "Compete":
1804
+ return 10
1805
+ if self._get_mode() == "Optuna":
1806
+ return 1 # just 1, because it will be tuned by Optuna
1807
+ else:
1808
+ return deepcopy(self.start_random_models)
1809
+
1810
+ def _get_hill_climbing_steps(self):
1811
+ """Gets the current hill_climbing_steps"""
1812
+ self._validate_hill_climbing_steps()
1813
+ if self.hill_climbing_steps == "auto":
1814
+ if self._get_mode() == "Explain":
1815
+ return 0
1816
+ if self._get_mode() == "Perform":
1817
+ return 2
1818
+ if self._get_mode() == "Compete":
1819
+ return 2
1820
+ if self._get_mode() == "Optuna":
1821
+ return 0 # all tuning is done in Optuna
1822
+ else:
1823
+ return deepcopy(self.hill_climbing_steps)
1824
+
1825
+ def _get_top_models_to_improve(self):
1826
+ """Gets the current top_models_to_improve"""
1827
+ self._validate_top_models_to_improve()
1828
+ if self.top_models_to_improve == "auto":
1829
+ if self._get_mode() == "Explain":
1830
+ return 0
1831
+ if self._get_mode() == "Perform":
1832
+ return 2
1833
+ if self._get_mode() == "Compete":
1834
+ return 3
1835
+ if self._get_mode() == "Optuna":
1836
+ return 0
1837
+ else:
1838
+ return deepcopy(self.top_models_to_improve)
1839
+
1840
+ def _get_boost_on_errors(self):
1841
+ """Gets the current boost_on_errors"""
1842
+ self._validate_boost_on_errors()
1843
+ if self.boost_on_errors == "auto":
1844
+ val = self._get_validation_strategy()
1845
+ if val.get("validation_type", "") == "custom":
1846
+ return False
1847
+ if self._get_mode() == "Explain":
1848
+ return False
1849
+ if self._get_mode() == "Perform":
1850
+ return False
1851
+ if self._get_mode() == "Compete":
1852
+ return True
1853
+ if self._get_mode() == "Optuna":
1854
+ return False
1855
+ else:
1856
+ return deepcopy(self.boost_on_errors)
1857
+
1858
+ def _get_kmeans_features(self):
1859
+ """Gets the current kmeans_features"""
1860
+ self._validate_kmeans_features()
1861
+ if self.kmeans_features == "auto":
1862
+ if self._get_mode() == "Explain":
1863
+ return False
1864
+ if self._get_mode() == "Perform":
1865
+ return False
1866
+ if self._get_mode() == "Compete":
1867
+ return True
1868
+ if self._get_mode() == "Optuna":
1869
+ return False
1870
+ else:
1871
+ return deepcopy(self.kmeans_features)
1872
+
1873
+ def _get_mix_encoding(self):
1874
+ """Gets the current mix_encoding"""
1875
+ self._validate_mix_encoding()
1876
+ if self.mix_encoding == "auto":
1877
+ if self._get_mode() == "Explain":
1878
+ return False
1879
+ if self._get_mode() == "Perform":
1880
+ return False
1881
+ if self._get_mode() == "Compete":
1882
+ return True
1883
+ if self._get_mode() == "Optuna":
1884
+ return False
1885
+ else:
1886
+ return deepcopy(self.mix_encoding)
1887
+
1888
+ def _get_max_single_prediction_time(self):
1889
+ """Gets the current max_single_prediction_time"""
1890
+ self._validate_max_single_prediction_time()
1891
+ if self.max_single_prediction_time is None:
1892
+ if self._get_mode() == "Perform":
1893
+ return 0.5 # prediction time should be under 0.5 second
1894
+ return None
1895
+ else:
1896
+ return deepcopy(self.max_single_prediction_time)
1897
+
1898
+ def _get_optuna_time_budget(self):
1899
+ """Gets the current optuna_time_budget"""
1900
+ self._validate_optuna_time_budget()
1901
+
1902
+ if self.optuna_time_budget is None:
1903
+ if self._get_mode() == "Optuna":
1904
+ return 3600
1905
+ return None
1906
+ else:
1907
+ if self._get_mode() != "Optuna":
1908
+ # use only for mode Optuna
1909
+ return None
1910
+ return deepcopy(self.optuna_time_budget)
1911
+
1912
+ def _get_optuna_init_params(self):
1913
+ """Gets the current optuna_init_params"""
1914
+ self._validate_optuna_init_params()
1915
+ if self._get_mode() != "Optuna":
1916
+ # use only for mode Optuna
1917
+ return {}
1918
+ return deepcopy(self.optuna_init_params)
1919
+
1920
+ def _get_optuna_verbose(self):
1921
+ """Gets the current optuna_verbose"""
1922
+ self._validate_optuna_verbose()
1923
+ # use only for mode Optuna
1924
+ if self._get_mode() != "Optuna":
1925
+ return True
1926
+ return deepcopy(self.optuna_verbose)
1927
+
1928
+ def _get_n_jobs(self):
1929
+ """Gets the current n_jobs"""
1930
+ self._validate_n_jobs()
1931
+ return deepcopy(self.n_jobs)
1932
+
1933
+ def _get_random_state(self):
1934
+ """Gets the current random_state"""
1935
+ self._validate_random_state()
1936
+ return deepcopy(self.random_state)
1937
+
1938
+ def _validate_mode(self):
1939
+ """Validates mode parameter"""
1940
+ valid_modes = ["Explain", "Perform", "Compete", "Optuna"]
1941
+ if self.mode not in valid_modes:
1942
+ raise ValueError(
1943
+ f"Expected 'mode' to be {' or '.join(valid_modes)}, got '{self.mode}'"
1944
+ )
1945
+
1946
+ def _validate_ml_task(self):
1947
+ """Validates ml_task parameter"""
1948
+ if isinstance(self.ml_task, str) and self.ml_task == "auto":
1949
+ return
1950
+
1951
+ if self.ml_task not in AlgorithmsRegistry.get_supported_ml_tasks():
1952
+ raise ValueError(
1953
+ f"Expected 'ml_task' to be {' or '.join(AlgorithmsRegistry.get_supported_ml_tasks())}, got '{self.ml_task}''"
1954
+ )
1955
+
1956
+ def _validate_results_path(self):
1957
+ """Validates path parameter"""
1958
+ if self.results_path is None or isinstance(self.results_path, str):
1959
+ return
1960
+
1961
+ raise ValueError(
1962
+ f"Expected 'results_path' to be of type string, got '{type(self.results_path)}''"
1963
+ )
1964
+
1965
+ def _validate_total_time_limit(self):
1966
+ """Validates total_time_limit parameter"""
1967
+ if self.total_time_limit is None:
1968
+ return
1969
+ if self.total_time_limit is not None:
1970
+ check_greater_than_zero_integer(self.total_time_limit, "total_time_limit")
1971
+
1972
+ def _validate_model_time_limit(self):
1973
+ """Validates model_time_limit parameter"""
1974
+ if self.model_time_limit is not None:
1975
+ check_greater_than_zero_integer(self.model_time_limit, "model_time_limit")
1976
+
1977
+ def _validate_algorithms(self):
1978
+ """Validates algorithms parameter"""
1979
+ if isinstance(self.algorithms, str) and self.algorithms == "auto":
1980
+ return
1981
+
1982
+ for algo in self.algorithms:
1983
+ if algo not in list(AlgorithmsRegistry.registry[self._ml_task].keys()):
1984
+ raise ValueError(
1985
+ f"The algorithm {algo} is not allowed to use for ML task: {self._ml_task}. Allowed algorithms: {list(AlgorithmsRegistry.registry[self._ml_task].keys())}"
1986
+ )
1987
+
1988
+ def _validate_train_ensemble(self):
1989
+ """Validates train_ensemble parameter"""
1990
+ # `train_ensemble` defaults to True, no further checking required
1991
+ check_bool(self.train_ensemble, "train_ensemble")
1992
+
1993
+ def _validate_stack_models(self):
1994
+ """Validates stack_models parameter"""
1995
+ # `stack_models` defaults to "auto". If "auto" return, else check if is valid bool
1996
+ if isinstance(self.stack_models, str) and self.stack_models == "auto":
1997
+ return
1998
+
1999
+ check_bool(self.stack_models, "stack_models")
2000
+
2001
+ def _validate_eval_metric(self):
2002
+ """Validates eval_metric parameter"""
2003
+ if isinstance(self.eval_metric, types.FunctionType):
2004
+ return
2005
+
2006
+ if isinstance(self.eval_metric, str) and self.eval_metric == "auto":
2007
+ return
2008
+
2009
+ if (self._get_ml_task() == BINARY_CLASSIFICATION) and self.eval_metric not in [
2010
+ "logloss",
2011
+ "auc",
2012
+ "f1",
2013
+ "average_precision",
2014
+ "accuracy",
2015
+ ]:
2016
+ raise ValueError(
2017
+ f"Metric {self.eval_metric} is not allowed in ML task: {self._get_ml_task()}. \
2018
+ Use 'logloss', 'auc', 'f1', 'average_precision', or 'accuracy'"
2019
+ )
2020
+
2021
+ elif (
2022
+ self._get_ml_task() == MULTICLASS_CLASSIFICATION
2023
+ ) and self.eval_metric not in ["logloss", "f1", "accuracy"]:
2024
+ raise ValueError(
2025
+ f"Metric {self.eval_metric} is not allowed in ML task: {self._get_ml_task()}. \
2026
+ Use 'logloss', 'f1', or 'accuracy'"
2027
+ )
2028
+
2029
+ elif self._get_ml_task() == REGRESSION and self.eval_metric not in [
2030
+ "rmse",
2031
+ "mse",
2032
+ "mae",
2033
+ "r2",
2034
+ "mape",
2035
+ "spearman",
2036
+ "pearson",
2037
+ ]:
2038
+ raise ValueError(
2039
+ f"Metric {self.eval_metric} is not allowed in ML task: {self._get_ml_task()}. \
2040
+ Use 'rmse', 'mse', 'mae', 'r2', 'mape', 'spearman', or 'pearson'"
2041
+ )
2042
+
2043
+ def _validate_validation_strategy(self):
2044
+ """Validates validation parameter"""
2045
+ if (
2046
+ isinstance(self.validation_strategy, str)
2047
+ and self.validation_strategy == "auto"
2048
+ ):
2049
+ return
2050
+
2051
+ # only validation_type is mandatory
2052
+ # other parameters of validations
2053
+ # have defaults set in their constructors
2054
+ required_keys = ["validation_type"]
2055
+ if type(self.validation_strategy) is not dict:
2056
+ raise ValueError(
2057
+ f"Expected 'validation_strategy' to be a dict, got '{type(self.validation_strategy)}'"
2058
+ )
2059
+ if not all(key in self.validation_strategy for key in required_keys):
2060
+ raise ValueError(f"Expected dict with keys: {' , '.join(required_keys)}")
2061
+
2062
+ def _validate_verbose(self):
2063
+ """Validates verbose parameter"""
2064
+ check_positive_integer(self.verbose, "verbose")
2065
+
2066
+ def _validate_explain_level(self):
2067
+ """Validates explain_level parameter"""
2068
+ if isinstance(self.explain_level, str) and self.explain_level == "auto":
2069
+ return
2070
+ valid_explain_levels = [0, 1, 2]
2071
+ # Check if explain level is 0 or greater integer
2072
+ if not (
2073
+ isinstance(self.explain_level, int)
2074
+ and self.explain_level in valid_explain_levels
2075
+ ):
2076
+ raise ValueError(
2077
+ f"Expected 'explain_level' to be {' or '.join([str(x) for x in valid_explain_levels])}, got '{self.explain_level}'"
2078
+ )
2079
+
2080
+ def _validate_golden_features(self):
2081
+ """Validates golden_features parameter"""
2082
+ if isinstance(self.golden_features, str) and self.golden_features == "auto":
2083
+ return
2084
+ if isinstance(self.golden_features, int):
2085
+ return
2086
+ check_bool(self.golden_features, "golden_features")
2087
+
2088
+ def _validate_features_selection(self):
2089
+ """Validates features_selection parameter"""
2090
+ if (
2091
+ isinstance(self.features_selection, str)
2092
+ and self.features_selection == "auto"
2093
+ ):
2094
+ return
2095
+ check_bool(self.features_selection, "features_selection")
2096
+
2097
+ def _validate_start_random_models(self):
2098
+ """Validates start_random_models parameter"""
2099
+ if (
2100
+ isinstance(self.start_random_models, str)
2101
+ and self.start_random_models == "auto"
2102
+ ):
2103
+ return
2104
+ check_greater_than_zero_integer(self.start_random_models, "start_random_models")
2105
+
2106
+ def _validate_hill_climbing_steps(self):
2107
+ """Validates hill_climbing_steps parameter"""
2108
+ if (
2109
+ isinstance(self.hill_climbing_steps, str)
2110
+ and self.hill_climbing_steps == "auto"
2111
+ ):
2112
+ return
2113
+ check_positive_integer(self.hill_climbing_steps, "hill_climbing_steps")
2114
+
2115
+ def _validate_top_models_to_improve(self):
2116
+ """Validates top_models_to_improve parameter"""
2117
+ if (
2118
+ isinstance(self.top_models_to_improve, str)
2119
+ and self.top_models_to_improve == "auto"
2120
+ ):
2121
+ return
2122
+ check_positive_integer(self.top_models_to_improve, "top_models_to_improve")
2123
+
2124
+ def _validate_boost_on_errors(self):
2125
+ """Validates boost_on_errors parameter"""
2126
+ if isinstance(self.boost_on_errors, str) and self.boost_on_errors == "auto":
2127
+ return
2128
+ check_bool(self.boost_on_errors, "boost_on_errors")
2129
+
2130
+ def _validate_kmeans_features(self):
2131
+ """Validates kmeans_features parameter"""
2132
+ if isinstance(self.kmeans_features, str) and self.kmeans_features == "auto":
2133
+ return
2134
+ check_bool(self.kmeans_features, "kmeans_features")
2135
+
2136
+ def _validate_mix_encoding(self):
2137
+ """Validates mix_encoding parameter"""
2138
+ if isinstance(self.mix_encoding, str) and self.mix_encoding == "auto":
2139
+ return
2140
+ check_bool(self.mix_encoding, "mix_encoding")
2141
+
2142
+ def _validate_max_single_prediction_time(self):
2143
+ """Validates max_single_prediction_time parameter"""
2144
+ if self.max_single_prediction_time is None:
2145
+ return
2146
+ check_greater_than_zero_integer_or_float(
2147
+ self.max_single_prediction_time, "max_single_prediction_time"
2148
+ )
2149
+
2150
+ def _validate_optuna_time_budget(self):
2151
+ """Validates optuna_time_budget parameter"""
2152
+ if self.optuna_time_budget is None:
2153
+ return
2154
+ check_greater_than_zero_integer(self.optuna_time_budget, "optuna_time_budget")
2155
+
2156
+ def _validate_optuna_init_params(self):
2157
+ """Validates optuna_init_params parameter"""
2158
+ if self.optuna_init_params is None:
2159
+ return
2160
+ if type(self.optuna_init_params) is not dict:
2161
+ raise ValueError(
2162
+ f"Expected 'optuna_init_params' to be a dict, got '{type(self.optuna_init_params)}'"
2163
+ )
2164
+
2165
+ def _validate_optuna_verbose(self):
2166
+ """Validates optuna_verbose parameter"""
2167
+ if self.optuna_verbose is None:
2168
+ return
2169
+ check_bool(self.optuna_verbose, "optuna_verbose")
2170
+
2171
+ def _validate_n_jobs(self):
2172
+ """Validates mix_encoding parameter"""
2173
+ check_integer(self.n_jobs, "n_jobs")
2174
+
2175
+ def _validate_random_state(self):
2176
+ """Validates random_state parameter"""
2177
+ check_positive_integer(self.random_state, "random_state")
2178
+
2179
+ def _validate_fairness_metric(self):
2180
+ """Validates fariness_metric parameter"""
2181
+ if isinstance(self.fairness_metric, str) and self.fairness_metric == "auto":
2182
+ return
2183
+
2184
+ if (
2185
+ self._get_ml_task() in [BINARY_CLASSIFICATION, MULTICLASS_CLASSIFICATION]
2186
+ ) and self.fairness_metric not in [
2187
+ "demographic_parity_difference",
2188
+ "demographic_parity_ratio",
2189
+ "equalized_odds_difference",
2190
+ "equalized_odds_ratio",
2191
+ ]:
2192
+ raise ValueError(
2193
+ f"Metric {self.fairness_metric} is not allowed in ML task: {self._get_ml_task()}. \
2194
+ Use `demographic_parity_difference`, `demographic_parity_ratio`, `equalized_odds_difference` or `equalized_odds_ratio`"
2195
+ )
2196
+ if (self._get_ml_task() == REGRESSION) and self.fairness_metric not in [
2197
+ "group_loss_difference",
2198
+ "group_loss_ratio",
2199
+ ]:
2200
+ raise ValueError(
2201
+ f"Metric {self.fairness_metric} is not allowed in ML task: {self._get_ml_task()}. \
2202
+ Use `group_loss`"
2203
+ )
2204
+
2205
+ def _get_fairness_metric(self):
2206
+ """Gets the fairness metric"""
2207
+ self._validate_fairness_metric()
2208
+ if self.fairness_metric == "auto":
2209
+ if self._get_ml_task() == BINARY_CLASSIFICATION:
2210
+ return "demographic_parity_ratio"
2211
+ if self._get_ml_task() == REGRESSION:
2212
+ return "group_loss_ratio"
2213
+ if self._get_ml_task() == MULTICLASS_CLASSIFICATION:
2214
+ return "demographic_parity_ratio"
2215
+ else:
2216
+ return deepcopy(self.fairness_metric)
2217
+
2218
+ def _get_fairness_threshold(self):
2219
+ """Gets the fairness threshold"""
2220
+ if self.fairness_threshold == "auto":
2221
+ if self._get_ml_task() in [
2222
+ BINARY_CLASSIFICATION,
2223
+ MULTICLASS_CLASSIFICATION,
2224
+ ]:
2225
+ thresholds = {
2226
+ "demographic_parity_difference": 0.1,
2227
+ "demographic_parity_ratio": 0.8,
2228
+ "equalized_odds_difference": 0.1,
2229
+ "equalized_odds_ratio": 0.8,
2230
+ }
2231
+ return thresholds.get(self._fairness_metric, 0.8)
2232
+ elif self._get_ml_task() == REGRESSION:
2233
+ thresholds = {
2234
+ "group_loss_ratio": 0.8,
2235
+ }
2236
+ if self._fairness_metric == "group_loss_difference":
2237
+ raise AutoMLException(
2238
+ "We can't set default fairness threshold value. Please set `fairness_threshold` value in AutoML constructor."
2239
+ )
2240
+ return thresholds.get(self._fairness_metric, 0.8)
2241
+ else:
2242
+ return deepcopy(self.fairness_threshold)
2243
+
2244
+ def _get_privileged_groups(self):
2245
+ """Gets privileged groups for fair training"""
2246
+ if self.privileged_groups == "auto":
2247
+ return []
2248
+ else:
2249
+ return deepcopy(self.privileged_groups)
2250
+
2251
+ def _get_underprivileged_groups(self):
2252
+ """Gets underprivileged groups for fair training"""
2253
+ if self.underprivileged_groups == "auto":
2254
+ return []
2255
+ else:
2256
+ return deepcopy(self.underprivileged_groups)
2257
+
2258
+ def to_json(self):
2259
+ if self._best_model is None:
2260
+ return None
2261
+
2262
+ return {
2263
+ "best_model": self._best_model.to_json(),
2264
+ "threshold": self._threshold,
2265
+ "ml_task": self._ml_task,
2266
+ }
2267
+
2268
+ def from_json(self, json_data):
2269
+ if json_data["best_model"]["algorithm_short_name"] == "Ensemble":
2270
+ self._best_model = Ensemble()
2271
+ self._best_model.from_json(json_data["best_model"])
2272
+ else:
2273
+ self._best_model = ModelFramework(json_data["best_model"].get("params"))
2274
+ self._best_model.from_json(json_data["best_model"])
2275
+ self._threshold = json_data.get("threshold")
2276
+
2277
+ self._ml_task = json_data.get("ml_task")
2278
+
2279
+ report_style = f"""
2280
+ .styled-table {{
2281
+ border-collapse: collapse;
2282
+ font-size: 0.9em;
2283
+ font-family: Courier New;
2284
+ }}
2285
+
2286
+ .styled-table td, .styled-table th {{
2287
+ border: 1px solid #ddd;
2288
+ padding: 8px;
2289
+ }}
2290
+
2291
+ .styled-table tr:nth-child(even){{background-color: #f2f2f2;}}
2292
+
2293
+ .styled-table tr:hover {{background-color: #e0ecf5;}}
2294
+
2295
+ .styled-table thead {{
2296
+ padding-top: 6px;
2297
+ padding-bottom: 6px;
2298
+ text-align: left;
2299
+ background-color: #0099cc;
2300
+ color: white;
2301
+ }}
2302
+
2303
+ .mljar-automl-report {{
2304
+ font-family: ui-sans-serif, system-ui, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji";
2305
+ background-color: rgba(236, 243, 249, 0.15);
2306
+
2307
+
2308
+ h1 {{
2309
+ color: #004666;
2310
+ border-bottom: 1px solid rgba(0,70,102,0.3)
2311
+ }}
2312
+ h2 {{
2313
+ color: #004666;
2314
+ padding-bottom: 5px;
2315
+ margin-bottom: 0px;
2316
+ }}
2317
+
2318
+ ul {{
2319
+ margin-top: 0px;
2320
+ }}
2321
+
2322
+ p {{
2323
+ margin-top: 5px;
2324
+ }}
2325
+
2326
+ h3 {{
2327
+ color: #004666;
2328
+ padding-bottom: 5px;
2329
+ margin-bottom: 0px;
2330
+ }}
2331
+ a {{
2332
+ font-weight: bold;
2333
+ color: #004666;
2334
+ }}
2335
+
2336
+ a:hover {{
2337
+ cursor: pointer;
2338
+ color: #0099CC;
2339
+ }}
2340
+ }}
2341
+
2342
+ """
2343
+
2344
+ def _md_to_html(self, md_fname, page_type, dir_path, me=None):
2345
+ import base64
2346
+
2347
+ import markdown
2348
+
2349
+ if not os.path.exists(md_fname):
2350
+ return None
2351
+ content = ""
2352
+ with open(md_fname) as fin:
2353
+ content = fin.read()
2354
+
2355
+ content = content.replace("README.md", "README.html")
2356
+ content_html = markdown.markdown(
2357
+ content, extensions=["markdown.extensions.tables"]
2358
+ )
2359
+ content_html = content_html.replace("<img ", '<img style="width:750px" ')
2360
+ content_html = content_html.replace("<table>", '<table class="styled-table">')
2361
+ content_html = content_html.replace("<tr>", '<tr style="text-align: right;">')
2362
+
2363
+ # replace png figures to base64
2364
+ for f in os.listdir(dir_path):
2365
+ if ".png" in f:
2366
+ encoded_string = ""
2367
+ with open(os.path.join(dir_path, f), "rb") as image_file:
2368
+ encoded_string = base64.b64encode(image_file.read())
2369
+ encoded_string = encoded_string.decode("utf-8")
2370
+ encoded_figure = f"data:image/png;base64, {encoded_string}"
2371
+ content_html = content_html.replace(f, encoded_figure)
2372
+
2373
+ # insert svg figures
2374
+ for f in os.listdir(dir_path):
2375
+ if ".svg" in f:
2376
+ with open(os.path.join(dir_path, f), "rb") as image_file:
2377
+ svg_plot = image_file.read()
2378
+ svg_plot = svg_plot.decode("utf-8")
2379
+
2380
+ arr = content_html.split("\n")
2381
+ new_content = []
2382
+ for i in arr:
2383
+ if f in i:
2384
+ new_content += [f"<p>{svg_plot}</p>"]
2385
+ else:
2386
+ new_content += [i]
2387
+ content_html = "\n".join(new_content)
2388
+
2389
+ # change links
2390
+ if page_type == f"automl-report-main-{self._id}":
2391
+ for f in os.listdir(dir_path):
2392
+ if os.path.exists(os.path.join(dir_path, f, "README.md")):
2393
+ old = f'href="{f}/README.html"'
2394
+ new = f"onclick=\"toggleShow('{f}-{self._id}');toggleShow('automl-report-main-{self._id}')\" "
2395
+ content_html = content_html.replace(old, new)
2396
+
2397
+ # other links
2398
+ if me is not None:
2399
+ old = 'href="../README.html"'
2400
+ new = f"onclick=\"toggleShow('{me}-{self._id}');toggleShow('automl-report-main-{self._id}')\" "
2401
+ content_html = content_html.replace(old, new)
2402
+
2403
+ beginning = ""
2404
+
2405
+ if page_type == f"automl-report-main-{self._id}":
2406
+ beginning += """<img src="https://raw.githubusercontent.com/mljar/visual-identity/main/media/mljar_AutomatedML.png" style="height:128px; margin-left: auto;
2407
+ margin-right: auto;display: block;"/>\n\n"""
2408
+ if os.path.exists(os.path.join(self._results_path, "optuna/README.md")):
2409
+ beginning += f"<h2><a onclick=\"toggleShow('optuna');toggleShow('automl-report-main-{self._id}')\" >&#187; Optuna Params Tuning Report</a></h2>"
2410
+
2411
+ content_html = beginning + content_html
2412
+
2413
+ return content_html
2414
+
2415
+ def _show_report(self, main_readme_html, width=900, height=1200):
2416
+ from IPython.display import HTML, IFrame
2417
+
2418
+ if os.environ.get("KAGGLE_KERNEL_RUN_TYPE") is None:
2419
+ with open(main_readme_html) as fin:
2420
+ return HTML(fin.read())
2421
+ else:
2422
+ return IFrame(main_readme_html, width=width, height=height)
2423
+
2424
+ def _report(self, width=900, height=1200):
2425
+ self._results_path = self._get_results_path()
2426
+ main_readme_html = os.path.join(self._results_path, "README.html")
2427
+
2428
+ if os.path.exists(main_readme_html):
2429
+ return self._show_report(main_readme_html, width, height)
2430
+
2431
+ body = ""
2432
+ fname = os.path.join(self._results_path, "README.md")
2433
+ body += (
2434
+ f'<div id="automl-report-main-{self._id}">\n'
2435
+ + self._md_to_html(fname, f"automl-report-main-{self._id}", self._results_path)
2436
+ + "\n\n</div>\n\n"
2437
+ )
2438
+
2439
+ for f in os.listdir(self._results_path):
2440
+ fname = os.path.join(self._results_path, f, "README.md")
2441
+ if os.path.exists(fname):
2442
+ body += (
2443
+ f'<div id="{f}-{self._id}" style="display: none">\n'
2444
+ + self._md_to_html(
2445
+ fname, "sub", os.path.join(self._results_path, f), f
2446
+ )
2447
+ + "\n\n</div>\n\n"
2448
+ )
2449
+
2450
+ body += """
2451
+ <script>
2452
+ function toggleShow(elementId) {
2453
+ var x = document.getElementById(elementId);
2454
+ if (x.style.display === "none") {
2455
+ x.style.display = "block";
2456
+ } else {
2457
+ x.style.display = "none";
2458
+ }
2459
+ }
2460
+ </script>
2461
+ """
2462
+
2463
+ report_content = f"""
2464
+ <!DOCTYPE html>
2465
+ <html>
2466
+ <head>
2467
+ <style>
2468
+ {self.report_style}
2469
+ </style>
2470
+ </head>
2471
+ <body>
2472
+ <div class="mljar-automl-report-{self._id}">
2473
+ {body}
2474
+ <div>
2475
+ </body>
2476
+ </html>
2477
+ """
2478
+ with open(main_readme_html, "w") as fout:
2479
+ fout.write(report_content)
2480
+
2481
+ return self._show_report(main_readme_html, width, height)
2482
+
2483
+ def _report_structured(self, format="markdown", model_details=True):
2484
+ self._results_path = self._get_results_path()
2485
+ if self._fit_level != "finished":
2486
+ self.load(self._results_path)
2487
+ elif self._models is None or len(self._models) == 0:
2488
+ # Handle objects where fit() returned early because results already exist.
2489
+ # In that case, fit_level can be "finished" but models might not be loaded.
2490
+ self.load(self._results_path)
2491
+
2492
+ if self._models is None or len(self._models) == 0:
2493
+ raise AutoMLException(
2494
+ "This model has not been fitted yet. Please call `fit()` first."
2495
+ )
2496
+
2497
+ if format not in ["markdown", "dict", "json"]:
2498
+ raise ValueError(
2499
+ f"Wrong format '{format}'. Allowed formats are: markdown, dict, json."
2500
+ )
2501
+
2502
+ payload = build_structured_report(self)
2503
+ save_structured_report(payload, self._results_path)
2504
+
2505
+ if format == "dict":
2506
+ return payload
2507
+ if format == "json":
2508
+ return json.dumps(payload, indent=4)
2509
+ return to_markdown(payload, model_details)
2510
+
2511
+ def _need_retrain(self, X, y, sample_weight, decrease):
2512
+ metric = self._best_model.get_metric()
2513
+
2514
+ X, y, sample_weight, _ = ExcludeRowsMissingTarget.transform(
2515
+ X, y, sample_weight, warn=True
2516
+ )
2517
+
2518
+ if self._ml_task == BINARY_CLASSIFICATION:
2519
+ prediction = self._predict_proba(X)[:, 1]
2520
+ if self._ml_task == MULTICLASS_CLASSIFICATION:
2521
+ prediction = self._predict_proba(X)
2522
+ else:
2523
+ prediction = self._predict(X)
2524
+
2525
+ sign = -1.0 if Metric.optimize_negative(metric.name) else 1.0
2526
+
2527
+ new_score = metric(y, prediction, sample_weight)
2528
+ old_score = self._best_model.get_final_loss()
2529
+
2530
+ change = np.abs((old_score - new_score) / old_score)
2531
+
2532
+ # always minimize the score
2533
+ if new_score > old_score:
2534
+ self.verbose_print(
2535
+ f"Model performance decreased by {np.round(change*100.0,2)}%"
2536
+ )
2537
+ return change > decrease
2538
+ else:
2539
+ self.verbose_print(
2540
+ f"Model performance increased by {np.round(change*100.0,2)}%"
2541
+ )
2542
+ return False