-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
Copy pathautoml.py
2438 lines (2141 loc) · 95.3 KB
/
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
from __future__ import annotations
from typing import (
Any,
Callable,
Dict,
Iterable,
Mapping,
Optional,
Sequence,
Tuple,
Type,
)
import copy
import io
import itertools
import json
import logging.handlers
import multiprocessing
import os
import platform
import sys
import time
import types
import uuid
import warnings
import distro
import joblib
import numpy as np
import numpy.ma as ma
import pandas as pd
import pkg_resources
import scipy.stats
import sklearn.utils
from ConfigSpace.configuration_space import Configuration, ConfigurationSpace
from ConfigSpace.read_and_write import json as cs_json
from dask.distributed import Client
from scipy.sparse import spmatrix
from sklearn.base import BaseEstimator
from sklearn.dummy import DummyClassifier, DummyRegressor
from sklearn.ensemble import VotingClassifier, VotingRegressor
from sklearn.metrics._classification import type_of_target
from sklearn.model_selection._split import (
BaseCrossValidator,
BaseShuffleSplit,
_RepeatedSplits,
)
from sklearn.pipeline import Pipeline
from sklearn.utils import check_random_state
from sklearn.utils.validation import check_is_fitted
from smac.callbacks import IncorporateRunResultCallback
from smac.runhistory.runhistory import RunInfo, RunValue
from smac.stats.stats import Stats
from smac.tae import StatusType
from typing_extensions import Literal
from autosklearn.automl_common.common.utils.backend import Backend, create
from autosklearn.constants import (
BINARY_CLASSIFICATION,
CLASSIFICATION_TASKS,
MULTICLASS_CLASSIFICATION,
MULTILABEL_CLASSIFICATION,
MULTIOUTPUT_REGRESSION,
REGRESSION,
REGRESSION_TASKS,
)
from autosklearn.data.validation import (
SUPPORTED_FEAT_TYPES,
SUPPORTED_TARGET_TYPES,
InputValidator,
convert_if_sparse,
)
from autosklearn.data.xy_data_manager import XYDataManager
from autosklearn.ensemble_building import EnsembleBuilderManager
from autosklearn.ensembles.abstract_ensemble import (
AbstractEnsemble,
AbstractMultiObjectiveEnsemble,
)
from autosklearn.ensembles.ensemble_selection import EnsembleSelection
from autosklearn.ensembles.singlebest_ensemble import SingleBestFromRunhistory
from autosklearn.evaluation import ExecuteTaFuncWithQueue, get_cost_of_crash
from autosklearn.evaluation.abstract_evaluator import _fit_and_suppress_warnings
from autosklearn.evaluation.train_evaluator import TrainEvaluator, _fit_with_budget
from autosklearn.metrics import (
Scorer,
_validate_metrics,
compute_single_metric,
default_metric_for_task,
)
from autosklearn.pipeline.base import BasePipeline
from autosklearn.pipeline.components.classification import ClassifierChoice
from autosklearn.pipeline.components.data_preprocessing.categorical_encoding import (
OHEChoice,
)
from autosklearn.pipeline.components.data_preprocessing.minority_coalescense import (
CoalescenseChoice,
)
from autosklearn.pipeline.components.data_preprocessing.rescaling import RescalingChoice
from autosklearn.pipeline.components.feature_preprocessing import (
FeaturePreprocessorChoice,
)
from autosklearn.pipeline.components.regression import RegressorChoice
from autosklearn.smbo import AutoMLSMBO
from autosklearn.util import RE_PATTERN, pipeline
from autosklearn.util.dask import Dask, LocalDask, UserDask
from autosklearn.util.data import (
DatasetCompressionSpec,
default_dataset_compression_arg,
reduce_dataset_size_if_too_large,
supported_precision_reductions,
validate_dataset_compression_arg,
)
from autosklearn.util.logging_ import (
PicklableClientLogger,
get_named_client_logger,
setup_logger,
start_log_server,
warnings_to,
)
from autosklearn.util.parallel import preload_modules
from autosklearn.util.progress_bar import ProgressBar
from autosklearn.util.smac_wrap import SMACCallback, SmacRunCallback
from autosklearn.util.stopwatch import StopWatch
import unittest.mock
def _model_predict(
model: Any,
X: SUPPORTED_FEAT_TYPES,
task: int,
batch_size: Optional[int] = None,
logger: Optional[PicklableClientLogger] = None,
) -> np.ndarray:
"""Generates the predictions from a model.
This is seperated out into a seperate function to allow for multiprocessing
and perform parallel predictions.
Parameters
----------
model: Any
The model to perform predictions with
X: {array-like, sparse matrix} of shape (n_samples, n_features)
The data to perform predictions on.
task: int
The int identifier indicating the kind of task that the model was
trained on.
batchsize: Optional[int] = None
If the model supports batch_size predictions then it's possible to pass
this in as an argument.
logger: Optional[PicklableClientLogger] = None
If a logger is passed, the warnings are writte to the logger. Otherwise
the warnings propogate as they would normally.
Returns
-------
np.ndarray of shape (n_samples,) or (n_samples, n_outputs)
The predictions produced by the model
"""
# Copy the array and ensure is has the attr 'shape'
X_ = np.asarray(X) if isinstance(X, list) else X.copy()
assert X_.shape[0] >= 1, f"X must have more than 1 sample but has {X_.shape[0]}"
with warnings_to(logger=logger):
# TODO issue 1169
# VotingRegressors aren't meant to be used for multioutput but we are
# using them anyways. Hence we need to manually get their outputs and
# average the right index as it averages on wrong dimension for us.
# We should probaly move away from this in the future.
#
# def VotingRegressor.predict()
# return np.average(self._predict(X), axis=1) <- wrong axis
#
if task == MULTIOUTPUT_REGRESSION and isinstance(model, VotingRegressor):
voting_regressor = model
prediction = np.average(voting_regressor.transform(X_), axis=2).T
else:
if task in CLASSIFICATION_TASKS:
predict_func = model.predict_proba
else:
predict_func = model.predict
if batch_size is not None and hasattr(model, "batch_size"):
prediction = predict_func(X_, batch_size=batch_size)
else:
prediction = predict_func(X_)
# Check that probability values lie between 0 and 1.
if task in CLASSIFICATION_TASKS:
assert (prediction >= 0).all() and (
prediction <= 1
).all(), f"For {model}, prediction probability not within [0, 1]!"
assert (
prediction.shape[0] == X_.shape[0]
), f"Prediction shape {model} is {prediction.shape} while X_.shape is {X_.shape}"
return prediction
class AutoML(BaseEstimator):
"""Base class for handling the AutoML procedure"""
def __init__(
self,
time_left_for_this_task: int,
per_run_time_limit: int,
temporary_directory: Optional[str] = None,
delete_tmp_folder_after_terminate: bool = True,
initial_configurations_via_metalearning: int = 25,
ensemble_class: Type[AbstractEnsemble] | None = EnsembleSelection,
ensemble_kwargs: Dict[str, Any] | None = None,
ensemble_nbest: int = 1,
max_models_on_disc: int = 1,
seed: int = 1,
memory_limit: int = 3072,
metadata_directory: Optional[str] = None,
include: Optional[dict[str, list[str]]] = None,
exclude: Optional[dict[str, list[str]]] = None,
resampling_strategy: str | Any = "holdout-iterative-fit",
resampling_strategy_arguments: Mapping[str, Any] = None,
n_jobs: Optional[int] = None,
dask_client: Optional[Client] = None,
precision: Literal[16, 32, 64] = 32,
disable_evaluator_output: bool | Iterable[str] = False,
get_smac_object_callback: Optional[Callable] = None,
smac_scenario_args: Optional[Mapping] = None,
logging_config: Optional[Mapping] = None,
metrics: Sequence[Scorer] | None = None,
scoring_functions: Optional[list[Scorer]] = None,
get_trials_callback: SMACCallback | None = None,
dataset_compression: bool | Mapping[str, Any] = True,
allow_string_features: bool = True,
disable_progress_bar: bool = False,
):
super().__init__()
if isinstance(disable_evaluator_output, Iterable):
disable_evaluator_output = list(disable_evaluator_output) # Incase iterator
allowed = set(["model", "cv_model", "y_optimization", "y_test"])
unknown = allowed - set(disable_evaluator_output)
if any(unknown):
raise ValueError(
f"Unknown arg {unknown} for '_disable_evaluator_output',"
f" must be one of {allowed}"
)
# Validate dataset_compression and set its values
self._dataset_compression: Optional[DatasetCompressionSpec]
if isinstance(dataset_compression, bool):
if dataset_compression is True:
self._dataset_compression = default_dataset_compression_arg
else:
self._dataset_compression = None
else:
self._dataset_compression = validate_dataset_compression_arg(
dataset_compression,
memory_limit=memory_limit,
)
# If we got something callable for `get_trials_callback`, wrap it so SMAC
# will accept it.
if (
get_trials_callback is not None
and callable(get_trials_callback)
and not isinstance(get_trials_callback, IncorporateRunResultCallback)
):
get_trials_callback = SmacRunCallback(get_trials_callback)
self._delete_tmp_folder_after_terminate = delete_tmp_folder_after_terminate
self._time_for_task = time_left_for_this_task
self._per_run_time_limit = per_run_time_limit
self._metrics = metrics
self._ensemble_class = ensemble_class
self._ensemble_kwargs = ensemble_kwargs
self._ensemble_nbest = ensemble_nbest
self._max_models_on_disc = max_models_on_disc
self._seed = seed
self._memory_limit = memory_limit
self._metadata_directory = metadata_directory
self._include = include
self._exclude = exclude
self._resampling_strategy = resampling_strategy
self._disable_evaluator_output = disable_evaluator_output
self._get_smac_object_callback = get_smac_object_callback
self._get_trials_callback = get_trials_callback
self._smac_scenario_args = smac_scenario_args
self.logging_config = logging_config
self.precision = precision
self.allow_string_features = allow_string_features
self.disable_progress_bar = disable_progress_bar
self._initial_configurations_via_metalearning = (
initial_configurations_via_metalearning
)
self._n_jobs = n_jobs
self._scoring_functions = scoring_functions or []
self._resampling_strategy_arguments = resampling_strategy_arguments or {}
self._multiprocessing_context = "forkserver"
# Single core, local runs should use fork to prevent the __main__ requirements
# in examples. Nevertheless, multi-process runs have spawn as requirement to
# reduce the possibility of a deadlock
self._dask: Dask
if dask_client is not None:
self._dask = UserDask(client=dask_client)
else:
self._dask = LocalDask(n_jobs=n_jobs)
if n_jobs == 1:
self._multiprocessing_context = "fork"
# Create the backend
self._backend: Backend = create(
temporary_directory=temporary_directory,
output_directory=None,
prefix="auto-sklearn",
delete_output_folder_after_terminate=delete_tmp_folder_after_terminate,
)
self._data_memory_limit = None # TODO: dead variable? Always None
self._datamanager = None
self._dataset_name = None
self._feat_type = None
self._logger: Optional[PicklableClientLogger] = None
self._task = None
self._label_num = None
self._parser = None
self._can_predict = False
self._read_at_most = None
self._max_ensemble_build_iterations = None
self.models_: Optional[dict] = None
self.cv_models_: Optional[dict] = None
self.ensemble_ = None
self.InputValidator: Optional[InputValidator] = None
self.configuration_space = None
# The ensemble performance history through time
self._stopwatch = StopWatch()
self._logger_port = logging.handlers.DEFAULT_TCP_LOGGING_PORT
self.ensemble_performance_history = []
# Num_run tell us how many runs have been launched. It can be seen as an
# identifier for each configuration saved to disk
self.num_run = 0
self.fitted = False
def _get_logger(self, name: str) -> PicklableClientLogger:
logger_name = "AutoML(%d):%s" % (self._seed, name)
# Setup the configuration for the logger
# This is gonna be honored by the server
# Which is created below
setup_logger(
filename="%s.log" % str(logger_name),
logging_config=self.logging_config,
output_dir=self._backend.temporary_directory,
)
# As Auto-sklearn works with distributed process,
# we implement a logger server that can receive tcp
# pickled messages. They are unpickled and processed locally
# under the above logging configuration setting
# We need to specify the logger_name so that received records
# are treated under the logger_name ROOT logger setting
context = multiprocessing.get_context(self._multiprocessing_context)
preload_modules(context)
self.stop_logging_server = context.Event()
port = context.Value("l") # be safe by using a long
port.value = -1
self.logging_server = context.Process(
target=start_log_server,
kwargs=dict(
host="localhost",
logname=logger_name,
event=self.stop_logging_server,
port=port,
filename="%s.log" % str(logger_name),
logging_config=self.logging_config,
output_dir=self._backend.temporary_directory,
),
)
self.logging_server.start()
while True:
with port.get_lock():
if port.value == -1:
time.sleep(0.01)
else:
break
self._logger_port = int(port.value)
return get_named_client_logger(
name=logger_name,
host="localhost",
port=self._logger_port,
)
def _clean_logger(self) -> None:
if not hasattr(self, "stop_logging_server") or self.stop_logging_server is None:
return
# Clean up the logger
if self.logging_server.is_alive():
self.stop_logging_server.set()
# We try to join the process, after we sent
# the terminate event. Then we try a join to
# nicely join the event. In case something
# bad happens with nicely trying to kill the
# process, we execute a terminate to kill the
# process.
self.logging_server.join(timeout=5)
self.logging_server.terminate()
del self.stop_logging_server
def _do_dummy_prediction(self) -> None:
# When using partial-cv it makes no sense to do dummy predictions
if self._resampling_strategy in ["partial-cv", "partial-cv-iterative-fit"]:
return
if self._metrics is None:
raise ValueError("Metric/Metrics was/were not set")
# Dummy prediction always have num_run set to 1
dummy_run_num = 1
self._logger.info("Starting to create dummy predictions.")
memory_limit = self._memory_limit
if memory_limit is not None:
memory_limit = int(memory_limit)
scenario_mock = unittest.mock.Mock()
scenario_mock.wallclock_limit = self._time_for_task
# This stats object is a hack - maybe the SMAC stats object should
# already be generated here!
stats = Stats(scenario_mock)
stats.start_timing()
ta = ExecuteTaFuncWithQueue(
backend=self._backend,
autosklearn_seed=self._seed,
multi_objectives=[metric.name for metric in self._metrics],
resampling_strategy=self._resampling_strategy,
initial_num_run=dummy_run_num,
stats=stats,
metrics=self._metrics,
memory_limit=memory_limit,
disable_file_output=self._disable_evaluator_output,
abort_on_first_run_crash=False,
cost_for_crash=get_cost_of_crash(self._metrics),
port=self._logger_port,
pynisher_context=self._multiprocessing_context,
**self._resampling_strategy_arguments,
)
status, cost, runtime, additional_info = ta.run(
config=dummy_run_num,
cutoff=self._time_for_task,
)
if status == StatusType.SUCCESS:
self._logger.info("Finished creating dummy predictions.")
# Fail if dummy prediction fails.
else:
if additional_info.get("exitcode") == -6:
msg = (
f"Dummy prediction failed with run state {status}."
" The error suggests that the provided memory limits are too tight."
" Please increase the 'memory_limit' and try again. If this does"
" not solve your problem, please open an issue and paste the"
f" additional output. Additional output: {additional_info}"
)
else:
msg = (
f" Dummy prediction failed with run state {status} and"
f" additional output: {additional_info}.",
)
self._logger.error(msg)
raise ValueError(msg)
return
@classmethod
def _task_type_id(cls, task_type: str) -> int:
raise NotImplementedError
@classmethod
def _supports_task_type(cls, task_type: str) -> bool:
raise NotImplementedError
def fit(
self,
X: SUPPORTED_FEAT_TYPES,
y: SUPPORTED_TARGET_TYPES,
task: Optional[int] = None,
X_test: Optional[SUPPORTED_FEAT_TYPES] = None,
y_test: Optional[SUPPORTED_TARGET_TYPES] = None,
feat_type: Optional[list[str]] = None,
dataset_name: Optional[str] = None,
only_return_configuration_space: bool = False,
load_models: bool = True,
is_classification: bool = False,
):
"""Fit AutoML to given training set (X, y).
Fit both optimizes the machine learning models and builds an ensemble
out of them.
# TODO PR1213
#
# `task: Optional[int]` and `is_classification`
#
# `AutoML` tries to identify the task itself with `sklearn.type_of_target`,
# leaving little for the subclasses to do.
# Except this failes when type_of_target(y) == "multiclass".
#
# "multiclass" be mean either REGRESSION or MULTICLASS_CLASSIFICATION,
# and so this is where the subclasses are used to determine which.
# However, this could also be deduced from the `is_classification`
# parameter.
#
# In the future, there is little need for the subclasses of `AutoML`
# and no need for the `task` parameter. The extra functionality
# provided by `AutoMLClassifier` in predict could be moved to
# `AutoSklearnClassifier`, leaving `AutoML` to just produce raw
# outputs and simplifying the heirarchy.
#
# `load_models`
#
# This parameter is likely not needed as they are loaded upon demand
# throughout `AutoML`.
# Creating a @property models that loads models into self.models_ is
# not loaded would remove the need for this parameter and simplyify
# the verification of `load if self.models_ is None` to one place.
#
# `only_return_configuration_space`
#
# This parameter is indicative of a need to create a seperate method
# for this as the functionality of `fit` and what it returns can vary.
Parameters
----------
X : {array-like, sparse matrix}, shape (n_samples, n_features)
The training input samples.
y : array-like, shape (n_samples) or (n_samples, n_outputs)
The target classes.
task : Optional[int]
The identifier for the task AutoML is to perform.
X_test : Optional[{array-like, sparse matrix}, shape (n_samples, n_features)]
Test data input samples. Will be used to save test predictions for
all models. This allows to evaluate the performance of Auto-sklearn
over time.
y_test : Optional[array-like, shape (n_samples) or (n_samples, n_outputs)]
Test data target classes. Will be used to calculate the test error
of all models. This allows to evaluate the performance of
Auto-sklearn over time.
feat_type : Optional[list],
List of str of `len(X.shape[1])` describing the attribute type.
Possible types are `Categorical` and `Numerical`. `Categorical`
attributes will be automatically One-Hot encoded. The values
used for a categorical attribute must be integers, obtained for
example by `sklearn.preprocessing.LabelEncoder
<https://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.LabelEncoder.html>`_.
dataset_name : Optional[str]
Create nicer output. If None, a string will be determined by the
md5 hash of the dataset.
only_return_configuration_space: bool = False
If set to true, fit will only return the configuration space that will
be used for model search. Otherwise fitting will be performed and an
ensemble created.
load_models: bool = True
If true, this will load the models into memory once complete.
is_classification: bool = False
Indicates whether this is a classification task if True or a
regression task if False.
Returns
-------
self
"""
if (X_test is not None) ^ (y_test is not None):
raise ValueError("Must provide both X_test and y_test together")
# AutoSklearn does not handle sparse y for now
y = convert_if_sparse(y)
y_test = convert_if_sparse(y_test) if y_test is not None else None
# Get the task if it doesn't exist
if task is None:
y_task = type_of_target(y)
if not self._supports_task_type(y_task):
raise ValueError(
f"{self.__class__.__name__} does not support" f" task {y_task}"
)
self._task = self._task_type_id(y_task)
else:
self._task = task
# Assign a metric if it doesnt exist
if self._metrics is None:
self._metrics = [default_metric_for_task[self._task]]
_validate_metrics(self._metrics, self._scoring_functions)
if dataset_name is None:
dataset_name = str(uuid.uuid1(clock_seq=os.getpid()))
# By default try to use the TCP logging port or get a new port
self._logger_port = logging.handlers.DEFAULT_TCP_LOGGING_PORT
progress_bar = ProgressBar(
total=self._time_for_task,
disable=self.disable_progress_bar,
desc="Fitting to the training data",
colour="green",
)
# Once we start the logging server, it starts in a new process
# If an error occurs then we want to make sure that we exit cleanly
# and shut it down, else it might hang
# https://github.com/automl/auto-sklearn/issues/1480
try:
self._logger = self._get_logger(dataset_name)
# The first thing we have to do is create the logger to update the backend
self._backend.setup_logger(self._logger_port)
if not only_return_configuration_space:
# If only querying the configuration space, we do not save the start
# time The start time internally checks for the fit() method to execute
# only once but this does not apply when only querying the configuration
# space
self._backend.save_start_time(self._seed)
progress_bar.start()
self._stopwatch = StopWatch()
# Make sure that input is valid
# Performs Ordinal one hot encoding to the target
# both for train and test data
self.InputValidator = InputValidator(
is_classification=is_classification,
feat_type=feat_type,
logger_port=self._logger_port,
allow_string_features=self.allow_string_features,
)
self.InputValidator.fit(X_train=X, y_train=y, X_test=X_test, y_test=y_test)
X, y = self.InputValidator.transform(X, y)
if X_test is not None and y_test is not None:
X_test, y_test = self.InputValidator.transform(X_test, y_test)
# We don't support size reduction on pandas type object yet
if (
self._dataset_compression is not None
and not isinstance(X, pd.DataFrame)
and not (isinstance(y, pd.Series) or isinstance(y, pd.DataFrame))
):
methods = self._dataset_compression["methods"]
memory_allocation = self._dataset_compression["memory_allocation"]
# Remove precision reduction if we can't perform it
if (
"precision" in methods
and X.dtype not in supported_precision_reductions
):
methods = [method for method in methods if method != "precision"]
with warnings_to(self._logger):
X, y = reduce_dataset_size_if_too_large(
X=X,
y=y,
memory_limit=self._memory_limit,
is_classification=is_classification,
random_state=self._seed,
operations=methods,
memory_allocation=memory_allocation,
)
# Check the re-sampling strategy
self._check_resampling_strategy(
X=X,
y=y,
task=self._task,
)
# Reset learnt stuff
self.models_ = None
self.cv_models_ = None
self.ensemble_ = None
# The metric must exist as of this point
# It can be provided in the constructor, or automatically
# defined in the estimator fit call
if isinstance(self._metrics, Sequence):
for entry in self._metrics:
if not isinstance(entry, Scorer):
raise ValueError(
f"Metric {entry} must be instance of"
" autosklearn.metrics.Scorer."
)
else:
raise ValueError(
"Metric must be a sequence of instances of "
"autosklearn.metrics.Scorer."
)
self._dataset_name = dataset_name
self._stopwatch.start(self._dataset_name)
# Take the feature types from the validator
self._feat_type = self.InputValidator.feature_validator.feat_type
self._log_fit_setup()
# == Pickle the data manager to speed up loading
with self._stopwatch.time("Save Datamanager"):
datamanager = XYDataManager(
X,
y,
X_test=X_test,
y_test=y_test,
task=self._task,
feat_type=self._feat_type,
dataset_name=dataset_name,
)
self._backend._make_internals_directory()
self._label_num = datamanager.info["label_num"]
self._backend.save_datamanager(datamanager)
# = Create a searchspace
# Do this before One Hot Encoding to make sure that it creates a
# search space for a dense classifier even if one hot encoding would
# make it sparse (tradeoff; if one hot encoding would make it sparse,
# densifier and truncatedSVD would probably lead to a MemoryError,
# like this we can't use some of the preprocessing methods in case
# the data became sparse)
with self._stopwatch.time("Create Search space"):
self.configuration_space, configspace_path = self._create_search_space(
self._backend.temporary_directory,
self._backend,
datamanager,
include=self._include,
exclude=self._exclude,
)
if only_return_configuration_space:
return self.configuration_space
# == Perform dummy predictions
with self._stopwatch.time("Dummy predictions"):
self.num_run += 1
self._do_dummy_prediction()
# == RUN ensemble builder
# Do this before calculating the meta-features to make sure that the
# dummy predictions are actually included in the ensemble even if
# calculating the meta-features takes very long
with self._stopwatch.time("Run Ensemble Builder"):
elapsed_time = self._stopwatch.time_since(self._dataset_name, "start")
time_left_for_ensembles = max(0, self._time_for_task - elapsed_time)
proc_ensemble = None
if time_left_for_ensembles <= 0:
# Fit only raises error when an ensemble class is given but
# time_left_for_ensembles is zero.
if self._ensemble_class is not None:
raise ValueError(
"Not starting ensemble builder because there "
"is no time left. Try increasing the value "
"of time_left_for_this_task."
)
elif self._ensemble_class is None:
self._logger.info(
"No ensemble buildin because no ensemble class was given."
)
else:
self._logger.info(
"Start Ensemble with %5.2fsec time left"
% time_left_for_ensembles
)
proc_ensemble = EnsembleBuilderManager(
start_time=time.time(),
time_left_for_ensembles=time_left_for_ensembles,
backend=copy.deepcopy(self._backend),
dataset_name=dataset_name,
task=self._task,
metrics=self._metrics,
ensemble_class=self._ensemble_class,
ensemble_kwargs=self._ensemble_kwargs,
ensemble_nbest=self._ensemble_nbest,
max_models_on_disc=self._max_models_on_disc,
seed=self._seed,
precision=self.precision,
max_iterations=self._max_ensemble_build_iterations,
read_at_most=self._read_at_most,
memory_limit=self._memory_limit,
random_state=self._seed,
logger_port=self._logger_port,
pynisher_context=self._multiprocessing_context,
)
# kill the datamanager as it will be re-loaded anyways from sub processes
try:
del self._datamanager
except Exception:
pass
# => RUN SMAC
with self._stopwatch.time("Run SMAC"):
elapsed_time = self._stopwatch.time_since(self._dataset_name, "start")
time_left = self._time_for_task - elapsed_time
if self._logger:
self._logger.info("Start SMAC with %5.2fsec time left" % time_left)
if time_left <= 0:
self._logger.warning(
"Not starting SMAC because there is no time left."
)
_proc_smac = None
self._budget_type = None
else:
if (
self._per_run_time_limit is None
or self._per_run_time_limit > time_left
):
self._logger.warning(
"Time limit for a single run is higher than total time "
"limit. Capping the limit for a single run to the total "
"time given to SMAC (%f)" % time_left
)
per_run_time_limit = time_left
else:
per_run_time_limit = self._per_run_time_limit
# At least 2 models are created for the ensemble process
num_models = time_left // per_run_time_limit
if num_models < 2:
per_run_time_limit = time_left // 2
self._logger.warning(
"Capping the per_run_time_limit to {} to have "
"time for a least 2 models in each process.".format(
per_run_time_limit
)
)
n_meta_configs = self._initial_configurations_via_metalearning
with self._dask as dask_client:
resamp_args = self._resampling_strategy_arguments
_proc_smac = AutoMLSMBO(
config_space=self.configuration_space,
dataset_name=self._dataset_name,
backend=self._backend,
total_walltime_limit=time_left,
func_eval_time_limit=per_run_time_limit,
memory_limit=self._memory_limit,
data_memory_limit=self._data_memory_limit,
stopwatch=self._stopwatch,
n_jobs=self._n_jobs,
dask_client=dask_client,
start_num_run=self.num_run,
num_metalearning_cfgs=n_meta_configs,
config_file=configspace_path,
seed=self._seed,
metadata_directory=self._metadata_directory,
metrics=self._metrics,
resampling_strategy=self._resampling_strategy,
resampling_strategy_args=resamp_args,
include=self._include,
exclude=self._exclude,
disable_file_output=self._disable_evaluator_output,
get_smac_object_callback=self._get_smac_object_callback,
smac_scenario_args=self._smac_scenario_args,
scoring_functions=self._scoring_functions,
port=self._logger_port,
pynisher_context=self._multiprocessing_context,
ensemble_callback=proc_ensemble,
trials_callback=self._get_trials_callback,
)
(
self.runhistory_,
self.trajectory_,
self._budget_type,
) = _proc_smac.run_smbo()
trajectory_filename = os.path.join(
self._backend.get_smac_output_directory_for_run(self._seed),
"trajectory.json",
)
saveable_trajectory = [
list(entry[:2])
+ [entry[2].get_dictionary()]
+ list(entry[3:])
for entry in self.trajectory_
]
with open(trajectory_filename, "w") as fh:
json.dump(saveable_trajectory, fh)
self._logger.info("Starting shutdown...")
# Wait until the ensemble process is finished to avoid shutting
# down while the ensemble builder tries to access the data
if proc_ensemble is not None:
self.ensemble_performance_history = list(
proc_ensemble.history
)
if len(proc_ensemble.futures) > 0:
# Now we wait for the future to return as it cannot be
# cancelled while it is running
# * https://stackoverflow.com/a/49203129
self._logger.info(
"Ensemble script still running,"
" waiting for it to finish."
)
result = proc_ensemble.futures.pop().result()
if result:
ensemble_history, _ = result
self.ensemble_performance_history.extend(
ensemble_history
)
self._logger.info(
"Ensemble script finished, continue shutdown."
)
# save the ensemble performance history file
if len(self.ensemble_performance_history) > 0:
pd.DataFrame(self.ensemble_performance_history).to_json(
os.path.join(
self._backend.internals_directory, "ensemble_history.json"
)
)
if load_models:
self._logger.info("Loading models...")
self._load_models()
self._logger.info("Finished loading models...")
# The whole logic above from where we begin the logging server is capture
# in a try: finally: so that if something goes wrong, we at least close
# down the logging server, preventing it from hanging and not closing
# until ctrl+c is pressed
except Exception as e:
# This will be called before the _fit_cleanup
self._logger.exception(e)
raise e
finally:
progress_bar.join()
self._fit_cleanup()
self.fitted = True
return self
def _log_fit_setup(self) -> None:
# Produce debug information to the logfile
self._logger.debug("Starting to print environment information")
self._logger.debug(" Python version: %s", sys.version.split("\n"))
try:
self._logger.debug(
f"\tDistribution: {distro.id()}-{distro.version()}-{distro.name()}"
)
except AttributeError:
pass
self._logger.debug(" System: %s", platform.system())
self._logger.debug(" Machine: %s", platform.machine())
self._logger.debug(" Platform: %s", platform.platform())
# UNAME appears to leak sensible information
# self._logger.debug(' uname: %s', platform.uname())
self._logger.debug(" Version: %s", platform.version())
self._logger.debug(" Mac version: %s", platform.mac_ver())
requirements = pkg_resources.resource_string("autosklearn", "requirements.txt")
requirements = requirements.decode("utf-8")