-
Notifications
You must be signed in to change notification settings - Fork 389
/
base_automl.py
2108 lines (1838 loc) · 81 KB
/
base_automl.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import os
import sys
import json
import copy
import time
import numpy as np
import pandas as pd
import logging
import traceback
import shutil
from tabulate import tabulate
from abc import ABC
from copy import deepcopy
from sklearn.base import BaseEstimator
from sklearn.utils.validation import check_array
from sklearn.metrics import r2_score, accuracy_score
from supervised.algorithms.registry import AlgorithmsRegistry
from supervised.algorithms.registry import BINARY_CLASSIFICATION
from supervised.algorithms.registry import MULTICLASS_CLASSIFICATION
from supervised.algorithms.registry import REGRESSION
from supervised.callbacks.early_stopping import EarlyStopping
from supervised.callbacks.metric_logger import MetricLogger
from supervised.callbacks.learner_time_constraint import LearnerTimeConstraint
from supervised.callbacks.total_time_constraint import TotalTimeConstraint
from supervised.ensemble import Ensemble
from supervised.exceptions import AutoMLException
from supervised.exceptions import NotTrainedException
from supervised.model_framework import ModelFramework
from supervised.preprocessing.exclude_missing_target import ExcludeRowsMissingTarget
from supervised.tuner.data_info import DataInfo
from supervised.tuner.mljar_tuner import MljarTuner
from supervised.utils.config import mem
from supervised.utils.config import LOG_LEVEL
from supervised.utils.leaderboard_plots import LeaderboardPlots
from supervised.utils.metric import Metric
from supervised.preprocessing.eda import EDA
from supervised.preprocessing.preprocessing_utils import PreprocessingUtils
from supervised.tuner.time_controller import TimeController
from supervised.utils.data_validation import (
check_positive_integer,
check_greater_than_zero_integer,
check_bool,
check_greater_than_zero_integer_or_float,
check_integer,
)
logger = logging.getLogger(__name__)
logger.setLevel(LOG_LEVEL)
class BaseAutoML(BaseEstimator, ABC):
"""
Automated Machine Learning for supervised tasks (binary classification, multiclass classification, regression).
Warning: This class should not be used directly. Use derived classes instead.
"""
def __init__(self):
logger.debug("BaseAutoML.__init__")
self._mode = None
self._ml_task = None
self._results_path = None
self._total_time_limit = None
self._model_time_limit = None
self._algorithms = []
self._train_ensemble = False
self._stack_models = False
self._eval_metric = None
self._validation_strategy = None
self._verbose = None
self._explain_level = None
self._golden_features = None
self._features_selection = None
self._start_random_models = None
self._hill_climbing_steps = None
self._top_models_to_improve = None
self._random_state = 1234
self._models = [] # instances of iterative learner framework or ensemble
self._best_model = None
self._verbose = True
self._threshold = None # used only in classification
self._metrics_details = None
self._max_metrics = None
self._confusion_matrix = None
self._X_path, self._y_path = None, None
self._data_info = None
self._model_subpaths = []
self._stacked_models = None
self._fit_level = None
self._start_time = time.time()
self._time_ctrl = None
self._all_params = {}
# https://scikit-learn.org/stable/developers/develop.html#universal-attributes
self.n_features_in_ = None # for scikit-learn api
self.tuner = None
self._boost_on_errors = None
self._kmeans_features = None
self._mix_encoding = None
self._max_single_prediction_time = None
self._optuna_time_budget = None
self._optuna_init_params = {}
self._optuna_verbose = True
self._n_jobs = -1
def _get_tuner_params(
self, start_random_models, hill_climbing_steps, top_models_to_improve
):
return {
"start_random_models": start_random_models,
"hill_climbing_steps": hill_climbing_steps,
"top_models_to_improve": top_models_to_improve,
}
def _check_can_load(self):
""" Checks if AutoML can be loaded from a folder"""
if self.results_path is not None:
# Dir exists and can be loaded
if os.path.exists(self.results_path) and os.path.exists(
os.path.join(self.results_path, "params.json")
):
self.load(self.results_path)
self._results_path = self.results_path
def load(self, path):
logger.info("Loading AutoML models ...")
try:
params = json.load(open(os.path.join(path, "params.json")))
self._model_subpaths = params["saved"]
self._mode = params.get("mode", self._mode)
self._ml_task = params.get("ml_task", self._ml_task)
self._results_path = params.get("results_path", self._results_path)
self._total_time_limit = params.get(
"total_time_limit", self._total_time_limit
)
self._model_time_limit = params.get(
"model_time_limit", self._model_time_limit
)
self._algorithms = params.get("algorithms", self._algorithms)
self._train_ensemble = params.get("train_ensemble", self._train_ensemble)
self._stack_models = params.get("stack_models", self._stack_models)
self._eval_metric = params.get("eval_metric", self._eval_metric)
self._validation_strategy = params.get(
"validation_strategy", self._validation_strategy
)
self._verbose = params.get("verbose", self._verbose)
self._explain_level = params.get("explain_level", self._explain_level)
self._golden_features = params.get("golden_features", self._golden_features)
self._features_selection = params.get(
"features_selectiom", self._features_selection
)
self._start_random_models = params.get(
"start_random_models", self._start_random_models
)
self._hill_climbing_steps = params.get(
"hill_climbing_steps", self._hill_climbing_steps
)
self._top_models_to_improve = params.get(
"top_models_to_improve", self._top_models_to_improve
)
self._boost_on_errors = params.get("boost_on_errors", self._boost_on_errors)
self._kmeans_features = params.get("kmeans_features", self._kmeans_features)
self._mix_encoding = params.get("mix_encoding", self._mix_encoding)
self._max_single_prediction_time = params.get(
"max_single_prediction_time", self._max_single_prediction_time
)
self._n_jobs = params.get("n_jobs", self._n_jobs)
self._random_state = params.get("random_state", self._random_state)
stacked_models = params.get("stacked")
load_on_predict = params.get("load_on_predict")
self._fit_level = params.get("fit_level")
lazy_load = not (
self._fit_level is not None and self._fit_level == "finished"
)
load_models = self._model_subpaths
if load_on_predict is not None and self._fit_level == "finished":
load_models = load_on_predict
models_map = {}
for model_subpath in load_models:
if model_subpath.endswith("Ensemble") or model_subpath.endswith(
"Ensemble_Stacked"
):
ens = Ensemble.load(path, model_subpath, models_map)
self._models += [ens]
models_map[ens.get_name()] = ens
else:
m = ModelFramework.load(path, model_subpath, lazy_load)
self._models += [m]
models_map[m.get_name()] = m
best_model_name = params.get("best_model")
self._best_model = None
if best_model_name is not None:
self._best_model = models_map.get(best_model_name)
if stacked_models is not None and (
self._best_model._is_stacked or self._fit_level != "finished"
):
self._stacked_models = []
for stacked_model_name in stacked_models:
self._stacked_models += [models_map[stacked_model_name]]
data_info_path = os.path.join(path, "data_info.json")
self._data_info = json.load(open(data_info_path))
self.n_features_in_ = self._data_info["n_features"]
if "n_classes" in self._data_info:
self.n_classes = self._data_info["n_classes"]
except Exception as e:
raise AutoMLException(f"Cannot load AutoML directory. {str(e)}")
def get_leaderboard(
self, filter_random_feature=False, original_metric_values=False
):
ldb = {
"name": [],
"model_type": [],
"metric_type": [],
"metric_value": [],
"train_time": [],
}
if self._max_single_prediction_time is not None:
ldb["single_prediction_time"] = []
for m in self._models:
# filter model with random feature
if filter_random_feature and "RandomFeature" in m.get_name():
continue
ldb["name"] += [m.get_name()]
ldb["model_type"] += [m.get_type()]
ldb["metric_type"] += [self._eval_metric]
ldb["metric_value"] += [m.get_final_loss()]
ldb["train_time"] += [np.round(m.get_train_time(), 2)]
if self._max_single_prediction_time is not None:
ldb["single_prediction_time"] += [
np.round(m._single_prediction_time, 4)
]
ldb = pd.DataFrame(ldb)
# need to add argument for sorting
# minimize_direction = m.get_metric().get_minimize_direction()
# ldb = ldb.sort_values("metric_value", ascending=minimize_direction)
if original_metric_values:
if Metric.optimize_negative(self._eval_metric):
ldb["metric_value"] *= -1.0
return ldb
def keep_model(self, model, model_subpath):
if model is None:
return
if self._max_single_prediction_time is not None:
# let's check the prediction time ...
# load 2x because of model reloading during the training
for _ in range(2):
start_time = time.time()
self._base_predict(self._one_sample, model)
model._single_prediction_time = (
time.time() - start_time
) # prediction time on single sample
# again release learners from models
if "Ensemble" not in model.get_type():
model.release_learners()
self._models += [model]
self._model_subpaths += [model_subpath]
self.select_and_save_best()
sign = -1.0 if Metric.optimize_negative(self._eval_metric) else 1.0
msg = "{} {} {} trained in {} seconds".format(
model.get_name(),
self._eval_metric,
np.round(sign * model.get_final_loss(), 6),
np.round(model.get_train_time(), 2),
)
if model._single_prediction_time is not None:
msg += f" (1-sample predict time {np.round(model._single_prediction_time,4)} seconds)"
self.verbose_print(msg)
self._time_ctrl.log_time(
model.get_name(), model.get_type(), self._fit_level, model.get_train_time()
)
self.tuner.add_key(model)
def create_dir(self, model_path):
if not os.path.exists(model_path):
try:
os.mkdir(model_path)
except Exception as e:
raise AutoMLException(f"Cannot create directory {model_path}. {str(e)}")
def _expected_learners_cnt(self):
try:
repeats = self._validation_strategy.get("repeats", 1)
folds = self._validation_strategy.get("k_folds", 1)
return repeats * folds
except Exception as e:
pass
return 1
def train_model(self, params):
# do we have enough time to train?
# if not, skip
if not self._time_ctrl.enough_time(
params["learner"]["model_type"], self._fit_level
):
logger.info(f"Cannot train {params['name']} because of the time constraint")
return False
# let's create directory to log all training artifacts
results_path, model_subpath = self._results_path, params["name"]
model_path = os.path.join(results_path, model_subpath)
self.create_dir(model_path)
# prepare callbacks
early_stop = EarlyStopping(
{"metric": {"name": self._eval_metric}, "log_to_dir": model_path}
)
# disable for now
max_time_for_learner = 3600
if self._total_time_limit is not None:
k_folds = self._validation_strategy.get("k_folds", 1.0)
at_least_algorithms = 10.0
max_time_for_learner = max(
self._total_time_limit / k_folds / at_least_algorithms, 60
)
params["max_time_for_learner"] = max_time_for_learner
total_time_constraint = TotalTimeConstraint(
{
"total_time_limit": self._total_time_limit
if self._model_time_limit is None
else None,
"total_time_start": self._start_time,
"expected_learners_cnt": self._expected_learners_cnt(),
}
)
# create model framework
mf = ModelFramework(
params,
callbacks=[early_stop, total_time_constraint],
)
# start training
logger.info(
f"Train model #{len(self._models)+1} / Model name: {params['name']}"
)
mf.train(results_path, model_subpath)
# save the model
mf.save(results_path, model_subpath)
# and keep info about the model
self.keep_model(mf, model_subpath)
return True
def verbose_print(self, msg):
if self._verbose > 0:
# self._progress_bar.write(msg)
print(msg)
def ensemble_step(self, is_stacked=False):
if self._train_ensemble and len(self._models) > 1:
ensemble_subpath = "Ensemble_Stacked" if is_stacked else "Ensemble"
ensemble_path = os.path.join(self._results_path, ensemble_subpath)
self.create_dir(ensemble_path)
self.ensemble = Ensemble(
self._eval_metric,
self._ml_task,
is_stacked=is_stacked,
max_single_prediction_time=self._max_single_prediction_time,
)
oofs, target, sample_weight = self.ensemble.get_oof_matrix(self._models)
self.ensemble.fit(oofs, target, sample_weight)
self.ensemble.save(self._results_path, ensemble_subpath)
self.keep_model(self.ensemble, ensemble_subpath)
return True
return False
def can_we_stack_them(self, y):
# if multiclass and too many classes then No
return True
def get_stacked_data(self, X, mode="training"):
# mode can be `training` or `predict`
if self._stacked_models is None:
return X
all_oofs = []
for m in self._stacked_models:
oof = None
if mode == "training":
oof = m.get_out_of_folds()
else:
oof = m.predict(X)
if self._ml_task == BINARY_CLASSIFICATION:
cols = [f for f in oof.columns if "prediction" in f]
if len(cols) == 2:
oof = pd.DataFrame({"prediction": oof[cols[1]]})
cols = [f for f in oof.columns if "prediction" in f]
oof = oof[cols]
oof.columns = [f"{m.get_name()}_{c}" for c in cols]
all_oofs += [oof]
org_index = X.index.copy()
X.reset_index(drop=True, inplace=True)
X_stacked = pd.concat([X] + all_oofs, axis=1)
X_stacked.index = org_index.copy()
X.index = org_index.copy()
return X_stacked
def _perform_model_stacking(self):
if self._stacked_models is not None:
return
ldb = self.get_leaderboard(filter_random_feature=True)
ldb = ldb.sort_values(by="metric_value", ascending=True)
models_map = {m.get_name(): m for m in self._models if not m._is_stacked}
self._stacked_models = []
models_limit = 10
for model_type in np.unique(ldb.model_type):
if model_type in ["Baseline"]:
continue
ds = ldb[ldb.model_type == model_type].copy()
ds.sort_values(by="metric_value", inplace=True)
for n in list(ds.name.iloc[:models_limit].values):
self._stacked_models += [models_map[n]]
scores = [m.get_final_loss() for m in self._stacked_models]
self._stacked_models = [
self._stacked_models[i] for i in np.argsort(scores).tolist()
]
def get_stacking_minimum_time_needed(self):
try:
ldb = self.get_leaderboard(filter_random_feature=True)
ldb = ldb.sort_values(by="metric_value", ascending=True)
return min(2.0 * ldb.iloc[0]["train_time"], 60)
except Exception as e:
return 60
def prepare_for_stacking(self):
# print("Stacked models ....")
# do we have enough models?
if len(self._models) < 5:
return
# do we have time?
if self._total_time_limit is not None:
time_left = self._total_time_limit - (time.time() - self._start_time)
# we need some time to start stacking
# it should be at least 60 seconds for larger data
# but for small data it can be less
if time_left < self.get_stacking_minimum_time_needed():
return
# too many classes and models
if self._ml_task == MULTICLASS_CLASSIFICATION:
if self.n_classes * len(self._models) > 1000:
return
self._perform_model_stacking()
X_stacked_path = os.path.join(self._results_path, "X_stacked.parquet")
if os.path.exists(X_stacked_path):
return
X = pd.read_parquet(self._X_path)
org_columns = X.columns.tolist()
X_stacked = self.get_stacked_data(X)
new_columns = X_stacked.columns.tolist()
added_columns = [c for c in new_columns if c not in org_columns]
# save stacked train data
X_stacked.to_parquet(X_stacked_path, index=False)
"""
# resue old params
for m in self._stacked_models:
# print(m.get_type())
# use only Xgboost, LightGBM and CatBoost as stacked models
if m.get_type() not in ["Xgboost", "LightGBM", "CatBoost"]:
continue
params = copy.deepcopy(m.params)
params["validation"]["X_train_path"] = X_train_stacked_path
params["name"] = params["name"] + "_Stacked"
params["is_stacked"] = True
# print(params)
if "model_architecture_json" in params["learner"]:
# the new model will be created with wider input size
del params["learner"]["model_architecture_json"]
if self._ml_task == REGRESSION:
# scale added predictions in regression if the target was scaled (in the case of NN)
target_preprocessing = params["preprocessing"]["target_preprocessing"]
scale = None
if "scale_log_and_normal" in target_preprocessing:
scale = "scale_log_and_normal"
elif "scale_normal" in target_preprocessing:
scale = "scale_normal"
if scale is not None:
for col in added_columns:
params["preprocessing"]["columns_preprocessing"][col] = [
scale]
self.train_model(params)
"""
def _save_data(self, X, y, sample_weight=None):
# save information about original data
self._save_data_info(X, y, sample_weight)
# handle drastic imbalance
# assure at least 20 samples of each class
# for binary and multiclass classification
self._handle_drastic_imbalance(X, y, sample_weight)
# prepare path for saving files
self._X_path = os.path.join(self._results_path, "X.parquet")
self._y_path = os.path.join(self._results_path, "y.parquet")
self._sample_weight_path = None
if sample_weight is not None:
self._sample_weight_path = os.path.join(
self._results_path, "sample_weight.parquet"
)
pd.DataFrame({"sample_weight": sample_weight}).to_parquet(
self._sample_weight_path, index=False
)
X.to_parquet(self._X_path, index=False)
if self._ml_task == MULTICLASS_CLASSIFICATION:
y = y.astype(str)
pd.DataFrame({"target": y}).to_parquet(self._y_path, index=False)
# set paths in validation parameters
self._validation_strategy["X_path"] = self._X_path
self._validation_strategy["y_path"] = self._y_path
self._validation_strategy["results_path"] = self._results_path
if sample_weight is not None:
self._validation_strategy["sample_weight_path"] = self._sample_weight_path
if self._max_single_prediction_time is not None:
self._one_sample = X.iloc[:1].copy(deep=True)
self._drop_data_variables(X)
def _handle_drastic_imbalance(self, X, y, sample_weight=None):
if self._ml_task == REGRESSION:
return
classes, cnts = np.unique(y, return_counts=True)
min_samples_per_class = 20
if self._validation_strategy is not None:
min_samples_per_class = max(
min_samples_per_class, self._validation_strategy.get("k_folds", 0)
)
for i in range(len(classes)):
if cnts[i] < min_samples_per_class:
append_samples = min_samples_per_class - cnts[i]
new_X = (
X[y == classes[i]]
.sample(n=append_samples, replace=True, random_state=1)
.reset_index(drop=True)
)
if sample_weight is not None:
new_sample_weight = (
sample_weight[y == classes[i]]
.sample(n=append_samples, replace=True, random_state=1)
.reset_index(drop=True)
)
for j in range(new_X.shape[0]):
X.loc[X.shape[0]] = new_X.loc[j]
y.loc[y.shape[0]] = classes[i]
if sample_weight is not None:
sample_weight.loc[
sample_weight.shape[0]
] = new_sample_weight.loc[j]
def _save_data_info(self, X, y, sample_weight=None):
target_is_numeric = pd.api.types.is_numeric_dtype(y)
if self._ml_task == MULTICLASS_CLASSIFICATION:
y = y.astype(str)
columns_and_target_info = DataInfo.compute(X, y, self._ml_task)
self.n_features_in_ = X.shape[1]
self.n_classes = len(np.unique(y[~pd.isnull(y)]))
self._data_info = {
"columns": X.columns.tolist(),
"rows": y.shape[0],
"cols": X.shape[1],
"target_is_numeric": target_is_numeric,
"columns_info": columns_and_target_info["columns_info"],
"target_info": columns_and_target_info["target_info"],
"n_features": self.n_features_in_,
"is_sample_weighted": sample_weight is not None,
}
# Add n_classes if not regression
if self._ml_task != REGRESSION:
self._data_info["n_classes"] = self.n_classes
if columns_and_target_info.get("num_class") is not None:
self._data_info["num_class"] = columns_and_target_info["num_class"]
data_info_path = os.path.join(self._results_path, "data_info.json")
with open(data_info_path, "w") as fout:
fout.write(json.dumps(self._data_info, indent=4))
def _drop_data_variables(self, X):
X.drop(X.columns, axis=1, inplace=True)
def _load_data_variables(self, X_train):
if X_train.shape[1] == 0:
X = pd.read_parquet(self._X_path)
for c in X.columns:
X_train.insert(loc=X_train.shape[1], column=c, value=X[c])
os.remove(self._X_path)
os.remove(self._y_path)
def save_progress(self, step=None, generated_params=None):
if step is not None and generated_params is not None:
self._all_params[step] = generated_params
state = {}
state["fit_level"] = self._fit_level
state["time_controller"] = self._time_ctrl.to_json()
state["all_params"] = self._all_params
state["adjust_validation"] = self._adjust_validation
fname = os.path.join(self._results_path, "progress.json")
with open(fname, "w") as fout:
fout.write(json.dumps(state, indent=4))
def load_progress(self):
state = {}
fname = os.path.join(self._results_path, "progress.json")
if not os.path.exists(fname):
return
state = json.load(open(fname, "r"))
self._fit_level = state.get("fit_level", self._fit_level)
self._all_params = state.get("all_params", self._all_params)
self._time_ctrl = TimeController.from_json(state.get("time_controller"))
self._adjust_validation = state.get("adjust_validation", False)
def _validate_X_predict(self, X):
"""Validate X whenever one tries to predict, apply, predict_proba"""
# X = check_array(X, ensure_2d=False)
X = np.atleast_2d(X)
n_features = X.shape[1]
if self.n_features_in_ != n_features:
raise ValueError(
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."
)
# This method builds pandas.Dataframe from input. The input can be numpy.ndarray, matrix, or pandas.Dataframe
# This method is used to build dataframes in `fit()` and in `predict`. That's the reason y can be None (`predict()` method)
def _build_dataframe(self, X, y=None, sample_weight=None):
if X is None or X.shape[0] == 0:
raise AutoMLException("Empty input dataset")
# If Inputs are not pandas dataframes use scikit-learn validation for X array
if not isinstance(X, pd.DataFrame):
# Validate X as array
X = check_array(X, ensure_2d=False, force_all_finite=False)
# Force X to be 2D
X = np.atleast_2d(X)
# Create Pandas dataframe from np.arrays, columns get names with the schema: feature_{index}
X = pd.DataFrame(
X, columns=["feature_" + str(i) for i in range(1, len(X[0]) + 1)]
)
# Enforce column names
# Enforce X_train columns to be string
X.columns = X.columns.astype(str)
X.reset_index(drop=True, inplace=True)
if y is None:
return X
# Check if y is np.ndarray, transform to pd.Series
if isinstance(y, np.ndarray):
y = check_array(
y,
ensure_2d=False,
dtype="str" if PreprocessingUtils.is_categorical(y) else "numeric",
)
y = pd.Series(np.array(y), name="target")
# if pd.DataFrame, slice first column
elif isinstance(y, pd.DataFrame):
y = np.array(y.iloc[:, 0])
y = check_array(y, ensure_2d=False)
y = pd.Series(np.array(y), name="target")
if sample_weight is not None:
if isinstance(sample_weight, np.ndarray):
sample_weight = check_array(sample_weight, ensure_2d=False)
sample_weight = pd.Series(np.array(sample_weight), name="sample_weight")
elif isinstance(sample_weight, pd.DataFrame):
sample_weight = np.array(sample_weight.iloc[:, 0])
sample_weight = check_array(sample_weight, ensure_2d=False)
sample_weight = pd.Series(np.array(sample_weight), name="sample_weight")
X, y, sample_weight = ExcludeRowsMissingTarget.transform(
X, y, sample_weight, warn=True
)
X.reset_index(drop=True, inplace=True)
y.reset_index(drop=True, inplace=True)
if sample_weight is not None:
sample_weight.reset_index(drop=True, inplace=True)
return X, y, sample_weight
def _apply_constraints(self):
if "Neural Network" in self._algorithms and self._n_jobs != -1:
self._algorithms.remove("Neural Network")
self.verbose_print(
"Neural Network algorithm was disabled because it doesn't support n_jobs parameter."
)
if "Linear" in self._algorithms and not (
self.n_rows_in_ < 10000 and self.n_features_in_ < 1000
):
self._algorithms.remove("Linear")
self.verbose_print("Linear algorithm was disabled.")
# remove algorithms in the case of multiclass
# and too many classes and columns
if self._ml_task == MULTICLASS_CLASSIFICATION:
if self.n_classes >= 10 and self.n_features_in_ * self.n_classes > 500:
if self.algorithms == "auto":
for a in ["CatBoost"]:
if a in self._algorithms:
self._algorithms.remove(a)
if self.n_features_in_ * self.n_classes > 1000:
if self.algorithms == "auto":
for a in ["Xgboost", "CatBoost"]:
if a in self._algorithms:
self._algorithms.remove(a)
if self.validation_strategy == "auto":
self._validation_strategy = {
"validation_type": "split",
"train_ratio": 0.9,
"shuffle": True,
}
if self._get_ml_task() != REGRESSION:
self._validation_strategy["stratify"] = True
if self.n_features_in_ * self.n_classes > 10000:
if self.algorithms == "auto":
for a in ["Random Forest", "Extra Trees"]:
if a in self._algorithms:
self._algorithms.remove(a)
# Adjust the validation type based on speed of Decision Tree learning
if (
self._get_mode() == "Compete"
and self._total_time_limit is not None
and self.validation_strategy == "auto"
and self._validation_strategy["validation_type"]
!= "split" # split is the fastest validation type, no need to change
):
# the validation will be adjusted after first Decision Tree learning on
# train/test split (1-fold)
self._adjust_validation = True
self._validation_strategy = self._fastest_validation()
def _fastest_validation(self):
strategy = {"validation_type": "split", "train_ratio": 0.9, "shuffle": True}
if self._get_ml_task() != REGRESSION:
strategy["stratify"] = True
return strategy
def _set_adjusted_validation(self):
if self._validation_strategy["validation_type"] != "split":
return
train_time = self._models[-1].get_train_time()
# the time of Decision Tree training multiply by 5.0
# to get the rough estimation how much time is needed for
# other algorithms
one_fold_time = train_time * 5.0
# it will be good to train at least 10 models
min_model_cnt = 10.0
# the number of folds we can afford during the training
folds_cnt = np.round(self._total_time_limit / one_fold_time / min_model_cnt)
# adjust the validation if possible
if folds_cnt >= 5.0:
self.verbose_print(f"Adjust validation. Remove: {self._model_subpaths[0]}")
k_folds = 5
if folds_cnt >= 15:
k_folds = 10
# too small dataset for stacking
if self.n_rows_in_ < 500:
self._stack_models = False
self.verbose_print(
"*** Disable stacking for small dataset (nrows < 500)"
)
self._validation_strategy["validation_type"] = "kfold"
del self._validation_strategy["train_ratio"]
self._validation_strategy["k_folds"] = k_folds
self.tuner._validation_strategy = self._validation_strategy
shutil.rmtree(self._model_subpaths[0], ignore_errors=True)
del self._models[0]
del self._model_subpaths[0]
del self.tuner._unique_params_keys[0]
self._adjust_validation = False
cv = []
if self._validation_strategy.get("shuffle", False):
cv += ["Shuffle"]
if self._validation_strategy.get("stratify", False):
cv += ["Stratify"]
self.select_and_save_best() # save validation strategy
self.verbose_print(f"Validation strategy: {k_folds}-fold CV {','.join(cv)}")
else:
# cant stack models for train/test split
self._stack_models = False
self.verbose_print("Disable stacking for split validation")
self._apply_constraints_stack_models()
def _apply_constraints_stack_models(self):
if self._validation_strategy["validation_type"] == "split":
if self._stack_models:
self.verbose_print("Disable stacking for split validation")
self._stack_models = False
self._boost_on_errors = False
if "repeats" in self._validation_strategy:
if self._stack_models:
self.verbose_print("Disable stacking for repeated validation")
self._stack_models = False
self._boost_on_errors = False
# update Tuner
if self.tuner is not None:
self.tuner._stack_models = self._stack_models
self.tuner._boost_on_errors = self._boost_on_errors
# update Time Controler
if self._time_ctrl is not None:
self._time_ctrl._is_stacking = self._stack_models
if "stack" in self._time_ctrl._steps and not self._stack_models:
self._time_ctrl._steps.remove("stack")
if (
"boost_on_errors" in self._time_ctrl._steps
and not self._boost_on_errors
):
self._time_ctrl._steps.remove("boost_on_errors")
def _fit(self, X, y, sample_weight=None):
"""Fits the AutoML model with data"""
if self._fit_level == "finished":
print(
"This model has already been fitted. You can use predict methods or select a new 'results_path' for a new a 'fit()'."
)
return
# Validate input and build dataframes
X, y, sample_weight = self._build_dataframe(X, y, sample_weight)
self.n_rows_in_ = X.shape[0]
self.n_features_in_ = X.shape[1]
self.n_classes = len(np.unique(y[~pd.isnull(y)]))
# Get attributes (__init__ params)
self._mode = self._get_mode()
self._ml_task = self._get_ml_task()
self._results_path = self._get_results_path()
self._total_time_limit = self._get_total_time_limit()
self._model_time_limit = self._get_model_time_limit()
self._algorithms = self._get_algorithms()
self._train_ensemble = self._get_train_ensemble()
self._stack_models = self._get_stack_models()
self._eval_metric = self._get_eval_metric()
self._validation_strategy = self._get_validation_strategy()
self._verbose = self._get_verbose()
self._explain_level = self._get_explain_level()
self._golden_features = self._get_golden_features()
self._features_selection = self._get_features_selection()
self._start_random_models = self._get_start_random_models()
self._hill_climbing_steps = self._get_hill_climbing_steps()
self._top_models_to_improve = self._get_top_models_to_improve()
self._boost_on_errors = self._get_boost_on_errors()
self._kmeans_features = self._get_kmeans_features()
self._mix_encoding = self._get_mix_encoding()
self._max_single_prediction_time = self._get_max_single_prediction_time()
self._optuna_time_budget = self._get_optuna_time_budget()
self._optuna_init_params = self._get_optuna_init_params()
self._optuna_verbose = self._get_optuna_verbose()
self._n_jobs = self._get_n_jobs()
self._random_state = self._get_random_state()
self._adjust_validation = False
self._apply_constraints()
if not self._adjust_validation:
# if there is no validation adjustement
# then we can apply stack_models constraints immediately
# if there is validation adjustement
# then we will apply contraints after the adjustement
self._apply_constraints_stack_models()
try:
self.load_progress()
if self._fit_level == "finished":
print(
"This model has already been fitted. You can use predict methods or select a new 'results_path' for a new 'fit()'."
)
return
self._check_can_load()
self.verbose_print(f"AutoML directory: {self._results_path}")
if self._mode == "Optuna" and self._total_time_limit is not None:
ttl = int(
self._total_time_limit
+ len(self._algorithms) * self._optuna_time_budget
)
self.verbose_print("Expected computing time:")
self.verbose_print(
f"Total training time: Optuna + ML training = {ttl} seconds"
)
self.verbose_print(
f"Total Optuna time: len(algorithms) * optuna_time_budget = {int(len(self._algorithms) * self._optuna_time_budget)} seconds"
)
self.verbose_print(
f"Total ML model training time: {int(self._total_time_limit)} seconds"
)
self.verbose_print(
f"The task is {self._ml_task} with evaluation metric {self._eval_metric}"
)
self.verbose_print(f"AutoML will use algorithms: {self._algorithms}")
if self._stack_models:
self.verbose_print("AutoML will stack models")
if self._train_ensemble:
self.verbose_print("AutoML will ensemble availabe models")
self._start_time = time.time()
if self._time_ctrl is not None:
self._start_time -= self._time_ctrl.already_spend()
# Automatic Exloratory Data Analysis
if self._explain_level == 2:
EDA.compute(X, y, os.path.join(self._results_path, "EDA"))
# Save data
self._save_data(X.copy(deep=False), y, sample_weight)
tuner = MljarTuner(
self._get_tuner_params(
self._start_random_models,
self._hill_climbing_steps,
self._top_models_to_improve,
),
self._algorithms,
self._ml_task,
self._eval_metric,
self._validation_strategy,
self._explain_level,
self._data_info,
self._golden_features,
self._features_selection,
self._train_ensemble,
self._stack_models,
self._adjust_validation,
self._boost_on_errors,
self._kmeans_features,
self._mix_encoding,
self._optuna_time_budget,
self._optuna_init_params,
self._optuna_verbose,
self._n_jobs,
self._random_state,
)
self.tuner = tuner
steps = tuner.steps()