forked from automl/auto-sklearn
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathensemble_builder.py
1506 lines (1352 loc) · 60.2 KB
/
ensemble_builder.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
# -*- encoding: utf-8 -*-
import glob
import gzip
import math
import numbers
import logging.handlers
import multiprocessing
import os
import pickle
import re
import shutil
import time
import traceback
from typing import List, Optional, Tuple, Union
import zlib
import dask.distributed
import numpy as np
import pandas as pd
import pynisher
from sklearn.utils.validation import check_random_state
from smac.callbacks import IncorporateRunResultCallback
from smac.optimizer.smbo import SMBO
from smac.runhistory.runhistory import RunInfo, RunValue
from smac.tae.base import StatusType
from autosklearn.util.backend import Backend
from autosklearn.constants import BINARY_CLASSIFICATION
from autosklearn.metrics import calculate_score, calculate_loss, Scorer
from autosklearn.ensembles.ensemble_selection import EnsembleSelection
from autosklearn.ensembles.abstract_ensemble import AbstractEnsemble
from autosklearn.util.logging_ import get_named_client_logger
from autosklearn.util.parallel import preload_modules
Y_ENSEMBLE = 0
Y_VALID = 1
Y_TEST = 2
MODEL_FN_RE = r'_([0-9]*)_([0-9]*)_([0-9]{1,3}\.[0-9]*)\.npy'
class EnsembleBuilderManager(IncorporateRunResultCallback):
def __init__(
self,
start_time: float,
time_left_for_ensembles: float,
backend: Backend,
dataset_name: str,
task: int,
metric: Scorer,
ensemble_size: int,
ensemble_nbest: int,
max_models_on_disc: Union[float, int],
seed: int,
precision: int,
max_iterations: Optional[int],
read_at_most: int,
ensemble_memory_limit: Optional[int],
random_state: int,
logger_port: int = logging.handlers.DEFAULT_TCP_LOGGING_PORT,
pynisher_context: str = 'fork',
):
""" SMAC callback to handle ensemble building
Parameters
----------
start_time: int
the time when this job was started, to account for any latency in job allocation
time_left_for_ensemble: int
How much time is left for the task. Job should finish within this allocated time
backend: util.backend.Backend
backend to write and read files
dataset_name: str
name of dataset
task_type: int
type of ML task
metric: str
name of metric to compute the loss of the given predictions
ensemble_size: int
maximal size of ensemble (passed to autosklearn.ensemble.ensemble_selection)
ensemble_nbest: int/float
if int: consider only the n best prediction
if float: consider only this fraction of the best models
Both wrt to validation predictions
If performance_range_threshold > 0, might return less models
max_models_on_disc: int
Defines the maximum number of models that are kept in the disc.
If int, it must be greater or equal than 1, and dictates the max number of
models to keep.
If float, it will be interpreted as the max megabytes allowed of disc space. That
is, if the number of ensemble candidates require more disc space than this float
value, the worst models will be deleted to keep within this budget.
Models and predictions of the worst-performing models will be deleted then.
If None, the feature is disabled.
It defines an upper bound on the models that can be used in the ensemble.
seed: int
random seed
max_iterations: int
maximal number of iterations to run this script
(default None --> deactivated)
precision: [16,32,64,128]
precision of floats to read the predictions
memory_limit: Optional[int]
memory limit in mb. If ``None``, no memory limit is enforced.
read_at_most: int
read at most n new prediction files in each iteration
logger_port: int
port that receives logging records
pynisher_context: str
The multiprocessing context for pynisher. One of spawn/fork/forkserver.
Returns
-------
List[Tuple[int, float, float, float]]:
A list with the performance history of this ensemble, of the form
[[pandas_timestamp, train_performance, val_performance, test_performance], ...]
"""
self.start_time = start_time
self.time_left_for_ensembles = time_left_for_ensembles
self.backend = backend
self.dataset_name = dataset_name
self.task = task
self.metric = metric
self.ensemble_size = ensemble_size
self.ensemble_nbest = ensemble_nbest
self.max_models_on_disc = max_models_on_disc
self.seed = seed
self.precision = precision
self.max_iterations = max_iterations
self.read_at_most = read_at_most
self.ensemble_memory_limit = ensemble_memory_limit
self.random_state = random_state
self.logger_port = logger_port
self.pynisher_context = pynisher_context
# Store something similar to SMAC's runhistory
self.history = []
# We only submit new ensembles when there is not an active ensemble job
self.futures = []
# The last criteria is the number of iterations
self.iteration = 0
# Keep track of when we started to know when we need to finish!
self.start_time = time.time()
def __call__(
self,
smbo: 'SMBO',
run_info: RunInfo,
result: RunValue,
time_left: float,
):
if result.status in (StatusType.STOP, StatusType.ABORT) or smbo._stop:
return
self.build_ensemble(smbo.tae_runner.client)
def build_ensemble(
self,
dask_client: dask.distributed.Client,
unit_test: bool = False
) -> None:
# The second criteria is elapsed time
elapsed_time = time.time() - self.start_time
logger = get_named_client_logger(
name='EnsembleBuilder',
port=self.logger_port,
)
# First test for termination conditions
if self.time_left_for_ensembles < elapsed_time:
logger.info(
"Terminate ensemble building as not time is left (run for {}s)".format(
elapsed_time
),
)
return
if self.max_iterations is not None and self.max_iterations <= self.iteration:
logger.info(
"Terminate ensemble building because of max iterations: {} of {}".format(
self.max_iterations,
self.iteration
)
)
return
if len(self.futures) != 0:
if self.futures[0].done():
result = self.futures.pop().result()
if result:
ensemble_history, self.ensemble_nbest, _, _, _ = result
logger.debug("iteration={} @ elapsed_time={} has history={}".format(
self.iteration,
elapsed_time,
ensemble_history,
))
self.history.extend(ensemble_history)
# Only submit new jobs if the previous ensemble job finished
if len(self.futures) == 0:
# Add the result of the run
# On the next while iteration, no references to
# ensemble builder object, so it should be garbage collected to
# save memory while waiting for resources
# Also, notice how ensemble nbest is returned, so we don't waste
# iterations testing if the deterministic predictions size can
# be fitted in memory
try:
# Submit a Dask job from this job, to properly
# see it in the dask diagnostic dashboard
# Notice that the forked ensemble_builder_process will
# wait for the below function to be done
self.futures.append(dask_client.submit(
fit_and_return_ensemble,
backend=self.backend,
dataset_name=self.dataset_name,
task_type=self.task,
metric=self.metric,
ensemble_size=self.ensemble_size,
ensemble_nbest=self.ensemble_nbest,
max_models_on_disc=self.max_models_on_disc,
seed=self.seed,
precision=self.precision,
memory_limit=self.ensemble_memory_limit,
read_at_most=self.read_at_most,
random_state=self.seed,
end_at=self.start_time + self.time_left_for_ensembles,
iteration=self.iteration,
return_predictions=False,
priority=100,
pynisher_context=self.pynisher_context,
logger_port=self.logger_port,
unit_test=unit_test,
))
logger.info(
"{}/{} Started Ensemble builder job at {} for iteration {}.".format(
# Log the client to make sure we
# remain connected to the scheduler
self.futures[0],
dask_client,
time.strftime("%Y.%m.%d-%H.%M.%S"),
self.iteration,
),
)
self.iteration += 1
except Exception as e:
exception_traceback = traceback.format_exc()
error_message = repr(e)
logger.critical(exception_traceback)
logger.critical(error_message)
def fit_and_return_ensemble(
backend: Backend,
dataset_name: str,
task_type: str,
metric: Scorer,
ensemble_size: int,
ensemble_nbest: int,
max_models_on_disc: Union[float, int],
seed: int,
precision: int,
memory_limit: Optional[int],
read_at_most: int,
random_state: int,
end_at: float,
iteration: int,
return_predictions: bool,
pynisher_context: str,
logger_port: int = logging.handlers.DEFAULT_TCP_LOGGING_PORT,
unit_test: bool = False,
) -> Tuple[
List[Tuple[int, float, float, float]],
int,
Optional[np.ndarray],
Optional[np.ndarray],
Optional[np.ndarray],
]:
"""
A short function to fit and create an ensemble. It is just a wrapper to easily send
a request to dask to create an ensemble and clean the memory when finished
Parameters
----------
backend: util.backend.Backend
backend to write and read files
dataset_name: str
name of dataset
metric: str
name of metric to compute the loss of the given predictions
task_type: int
type of ML task
ensemble_size: int
maximal size of ensemble (passed to autosklearn.ensemble.ensemble_selection)
ensemble_nbest: int/float
if int: consider only the n best prediction
if float: consider only this fraction of the best models
Both wrt to validation predictions
If performance_range_threshold > 0, might return less models
max_models_on_disc: int
Defines the maximum number of models that are kept in the disc.
If int, it must be greater or equal than 1, and dictates the max number of
models to keep.
If float, it will be interpreted as the max megabytes allowed of disc space. That
is, if the number of ensemble candidates require more disc space than this float
value, the worst models will be deleted to keep within this budget.
Models and predictions of the worst-performing models will be deleted then.
If None, the feature is disabled.
It defines an upper bound on the models that can be used in the ensemble.
seed: int
random seed
precision: [16,32,64,128]
precision of floats to read the predictions
memory_limit: Optional[int]
memory limit in mb. If ``None``, no memory limit is enforced.
read_at_most: int
read at most n new prediction files in each iteration
end_at: float
At what time the job must finish. Needs to be the endtime and not the time left
because we do not know when dask schedules the job.
iteration: int
The current iteration
pynisher_context: str
Context to use for multiprocessing, can be either fork, spawn or forkserver.
logger_port: int
The port where the logging server is listening to.
unit_test: bool
Turn on unit testing mode. This currently makes fit_ensemble raise a MemoryError.
Having this is very bad coding style, but I did not find a way to make
unittest.mock work through the pynisher with all spawn contexts. If you know a
better solution, please let us know by opening an issue.
Returns
-------
List[Tuple[int, float, float, float]]
A list with the performance history of this ensemble, of the form
[[pandas_timestamp, train_performance, val_performance, test_performance], ...]
"""
result = EnsembleBuilder(
backend=backend,
dataset_name=dataset_name,
task_type=task_type,
metric=metric,
ensemble_size=ensemble_size,
ensemble_nbest=ensemble_nbest,
max_models_on_disc=max_models_on_disc,
seed=seed,
precision=precision,
memory_limit=memory_limit,
read_at_most=read_at_most,
random_state=random_state,
logger_port=logger_port,
unit_test=unit_test,
).run(
end_at=end_at,
iteration=iteration,
return_predictions=return_predictions,
pynisher_context=pynisher_context,
)
return result
class EnsembleBuilder(object):
def __init__(
self,
backend: Backend,
dataset_name: str,
task_type: int,
metric: Scorer,
ensemble_size: int = 10,
ensemble_nbest: int = 100,
max_models_on_disc: int = 100,
performance_range_threshold: float = 0,
seed: int = 1,
precision: int = 32,
memory_limit: Optional[int] = 1024,
read_at_most: int = 5,
random_state: Optional[Union[int, np.random.RandomState]] = None,
logger_port: int = logging.handlers.DEFAULT_TCP_LOGGING_PORT,
unit_test: bool = False,
):
"""
Constructor
Parameters
----------
backend: util.backend.Backend
backend to write and read files
dataset_name: str
name of dataset
task_type: int
type of ML task
metric: str
name of metric to compute the loss of the given predictions
ensemble_size: int
maximal size of ensemble (passed to autosklearn.ensemble.ensemble_selection)
ensemble_nbest: int/float
if int: consider only the n best prediction
if float: consider only this fraction of the best models
Both wrt to validation predictions
If performance_range_threshold > 0, might return less models
max_models_on_disc: int
Defines the maximum number of models that are kept in the disc.
If int, it must be greater or equal than 1, and dictates the max number of
models to keep.
If float, it will be interpreted as the max megabytes allowed of disc space. That
is, if the number of ensemble candidates require more disc space than this float
value, the worst models will be deleted to keep within this budget.
Models and predictions of the worst-performing models will be deleted then.
If None, the feature is disabled.
It defines an upper bound on the models that can be used in the ensemble.
performance_range_threshold: float
Keep only models that are better than:
dummy + (best - dummy)*performance_range_threshold
E.g dummy=2, best=4, thresh=0.5 --> only consider models with loss > 3
Will at most return the minimum between ensemble_nbest models,
and max_models_on_disc. Might return less
seed: int
random seed
precision: [16,32,64,128]
precision of floats to read the predictions
memory_limit: Optional[int]
memory limit in mb. If ``None``, no memory limit is enforced.
read_at_most: int
read at most n new prediction files in each iteration
logger_port: int
port that receives logging records
unit_test: bool
Turn on unit testing mode. This currently makes fit_ensemble raise a MemoryError.
Having this is very bad coding style, but I did not find a way to make
unittest.mock work through the pynisher with all spawn contexts. If you know a
better solution, please let us know by opening an issue.
"""
super(EnsembleBuilder, self).__init__()
self.backend = backend # communication with filesystem
self.dataset_name = dataset_name
self.task_type = task_type
self.metric = metric
self.ensemble_size = ensemble_size
self.performance_range_threshold = performance_range_threshold
if isinstance(ensemble_nbest, numbers.Integral) and ensemble_nbest < 1:
raise ValueError("Integer ensemble_nbest has to be larger 1: %s" %
ensemble_nbest)
elif not isinstance(ensemble_nbest, numbers.Integral):
if ensemble_nbest < 0 or ensemble_nbest > 1:
raise ValueError(
"Float ensemble_nbest best has to be >= 0 and <= 1: %s" %
ensemble_nbest)
self.ensemble_nbest = ensemble_nbest
# max_models_on_disc can be a float, in such case we need to
# remember the user specified Megabytes and translate this to
# max number of ensemble models. max_resident_models keeps the
# maximum number of models in disc
if max_models_on_disc is not None and max_models_on_disc < 0:
raise ValueError(
"max_models_on_disc has to be a positive number or None"
)
self.max_models_on_disc = max_models_on_disc
self.max_resident_models = None
self.seed = seed
self.precision = precision
self.memory_limit = memory_limit
self.read_at_most = read_at_most
self.random_state = check_random_state(random_state)
self.unit_test = unit_test
# Setup the logger
self.logger_port = logger_port
self.logger = get_named_client_logger(
name='EnsembleBuilder',
port=self.logger_port,
)
if ensemble_nbest == 1:
self.logger.debug("Behaviour depends on int/float: %s, %s (ensemble_nbest, type)" %
(ensemble_nbest, type(ensemble_nbest)))
self.start_time = 0
self.model_fn_re = re.compile(MODEL_FN_RE)
self.last_hash = None # hash of ensemble training data
self.y_true_ensemble = None
self.SAVE2DISC = True
# already read prediction files
# {"file name": {
# "ens_loss": float
# "mtime_ens": str,
# "mtime_valid": str,
# "mtime_test": str,
# "seed": int,
# "num_run": int,
# }}
self.read_losses = {}
# {"file_name": {
# Y_ENSEMBLE: np.ndarray
# Y_VALID: np.ndarray
# Y_TEST: np.ndarray
# }
# }
self.read_preds = {}
# Depending on the dataset dimensions,
# regenerating every iteration, the predictions
# losses for self.read_preds
# is too computationally expensive
# As the ensemble builder is stateless
# (every time the ensemble builder gets resources
# from dask, it builds this object from scratch)
# we save the state of this dictionary to memory
# and read it if available
self.ensemble_memory_file = os.path.join(
self.backend.internals_directory,
'ensemble_read_preds.pkl'
)
if os.path.exists(self.ensemble_memory_file):
try:
with (open(self.ensemble_memory_file, "rb")) as memory:
self.read_preds, self.last_hash = pickle.load(memory)
except Exception as e:
self.logger.warning(
"Could not load the previous iterations of ensemble_builder predictions."
"This might impact the quality of the run. Exception={} {}".format(
e,
traceback.format_exc(),
)
)
self.ensemble_loss_file = os.path.join(
self.backend.internals_directory,
'ensemble_read_losses.pkl'
)
if os.path.exists(self.ensemble_loss_file):
try:
with (open(self.ensemble_loss_file, "rb")) as memory:
self.read_losses = pickle.load(memory)
except Exception as e:
self.logger.warning(
"Could not load the previous iterations of ensemble_builder losses."
"This might impact the quality of the run. Exception={} {}".format(
e,
traceback.format_exc(),
)
)
# hidden feature which can be activated via an environment variable. This keeps all
# models and predictions which have ever been a candidate. This is necessary to post-hoc
# compute the whole ensemble building trajectory.
self._has_been_candidate = set()
self.validation_performance_ = np.inf
# Track the ensemble performance
datamanager = self.backend.load_datamanager()
self.y_valid = datamanager.data.get('Y_valid')
self.y_test = datamanager.data.get('Y_test')
del datamanager
self.ensemble_history = []
def run(
self,
iteration: int,
pynisher_context: str,
time_left: Optional[float] = None,
end_at: Optional[float] = None,
time_buffer=5,
return_predictions: bool = False,
):
if time_left is None and end_at is None:
raise ValueError('Must provide either time_left or end_at.')
elif time_left is not None and end_at is not None:
raise ValueError('Cannot provide both time_left and end_at.')
self.logger = get_named_client_logger(
name='EnsembleBuilder',
port=self.logger_port,
)
process_start_time = time.time()
while True:
if time_left is not None:
time_elapsed = time.time() - process_start_time
time_left -= time_elapsed
else:
current_time = time.time()
if current_time > end_at:
break
else:
time_left = end_at - current_time
wall_time_in_s = int(time_left - time_buffer)
if wall_time_in_s < 1:
break
context = multiprocessing.get_context(pynisher_context)
preload_modules(context)
safe_ensemble_script = pynisher.enforce_limits(
wall_time_in_s=wall_time_in_s,
mem_in_mb=self.memory_limit,
logger=self.logger,
context=context,
)(self.main)
safe_ensemble_script(time_left, iteration, return_predictions)
if safe_ensemble_script.exit_status is pynisher.MemorylimitException:
# if ensemble script died because of memory error,
# reduce nbest to reduce memory consumption and try it again
# ATTENTION: main will start from scratch; # all data structures are empty again
try:
os.remove(self.ensemble_memory_file)
except: # noqa E722
pass
if isinstance(self.ensemble_nbest, numbers.Integral) and self.ensemble_nbest <= 1:
if self.read_at_most == 1:
self.logger.error(
"Memory Exception -- Unable to further reduce the number of ensemble "
"members and can no further limit the number of ensemble members "
"loaded per iteration -- please restart Auto-sklearn with a higher "
"value for the argument `memory_limit` (current limit is %s MB). "
"The ensemble builder will keep running to delete files from disk in "
"case this was enabled.", self.memory_limit
)
self.ensemble_nbest = 0
else:
self.read_at_most = 1
self.logger.warning(
"Memory Exception -- Unable to further reduce the number of ensemble "
"members -- Now reducing the number of predictions per call to read "
"at most to 1."
)
else:
if isinstance(self.ensemble_nbest, numbers.Integral):
self.ensemble_nbest = max(1, int(self.ensemble_nbest / 2))
else:
self.ensemble_nbest = self.ensemble_nbest / 2
self.logger.warning("Memory Exception -- restart with "
"less ensemble_nbest: %d" % self.ensemble_nbest)
return [], self.ensemble_nbest, None, None, None
else:
return safe_ensemble_script.result
return [], self.ensemble_nbest, None, None, None
def main(self, time_left, iteration, return_predictions):
# Pynisher jobs inside dask 'forget'
# the logger configuration. So we have to set it up
# accordingly
self.logger = get_named_client_logger(
name='EnsembleBuilder',
port=self.logger_port,
)
self.start_time = time.time()
train_pred, valid_pred, test_pred = None, None, None
used_time = time.time() - self.start_time
self.logger.debug(
'Starting iteration %d, time left: %f',
iteration,
time_left - used_time,
)
# populates self.read_preds and self.read_losses
if not self.compute_loss_per_model():
if return_predictions:
return self.ensemble_history, self.ensemble_nbest, train_pred, valid_pred, test_pred
else:
return self.ensemble_history, self.ensemble_nbest, None, None, None
# Only the models with the n_best predictions are candidates
# to be in the ensemble
candidate_models = self.get_n_best_preds()
if not candidate_models: # no candidates yet
if return_predictions:
return self.ensemble_history, self.ensemble_nbest, train_pred, valid_pred, test_pred
else:
return self.ensemble_history, self.ensemble_nbest, None, None, None
# populates predictions in self.read_preds
# reduces selected models if file reading failed
n_sel_valid, n_sel_test = self. \
get_valid_test_preds(selected_keys=candidate_models)
# If valid/test predictions loaded, then reduce candidate models to this set
if len(n_sel_test) != 0 and len(n_sel_valid) != 0 \
and len(set(n_sel_valid).intersection(set(n_sel_test))) == 0:
# Both n_sel_* have entries, but there is no overlap, this is critical
self.logger.error("n_sel_valid and n_sel_test are not empty, but do not overlap")
if return_predictions:
return self.ensemble_history, self.ensemble_nbest, train_pred, valid_pred, test_pred
else:
return self.ensemble_history, self.ensemble_nbest, None, None, None
# If any of n_sel_* is not empty and overlaps with candidate_models,
# then ensure candidate_models AND n_sel_test are sorted the same
candidate_models_set = set(candidate_models)
if candidate_models_set.intersection(n_sel_valid).intersection(n_sel_test):
candidate_models = sorted(list(candidate_models_set.intersection(
n_sel_valid).intersection(n_sel_test)))
n_sel_test = candidate_models
n_sel_valid = candidate_models
elif candidate_models_set.intersection(n_sel_valid):
candidate_models = sorted(list(candidate_models_set.intersection(
n_sel_valid)))
n_sel_valid = candidate_models
elif candidate_models_set.intersection(n_sel_test):
candidate_models = sorted(list(candidate_models_set.intersection(
n_sel_test)))
n_sel_test = candidate_models
else:
# This has to be the case
n_sel_test = []
n_sel_valid = []
if os.environ.get('ENSEMBLE_KEEP_ALL_CANDIDATES'):
for candidate in candidate_models:
self._has_been_candidate.add(candidate)
# train ensemble
ensemble = self.fit_ensemble(selected_keys=candidate_models)
# Save the ensemble for later use in the main auto-sklearn module!
if ensemble is not None and self.SAVE2DISC:
self.backend.save_ensemble(ensemble, iteration, self.seed)
# Delete files of non-candidate models - can only be done after fitting the ensemble and
# saving it to disc so we do not accidentally delete models in the previous ensemble
if self.max_resident_models is not None:
self._delete_excess_models(selected_keys=candidate_models)
# Save the read losses status for the next iteration
with open(self.ensemble_loss_file, "wb") as memory:
pickle.dump(self.read_losses, memory)
if ensemble is not None:
train_pred = self.predict(set_="train",
ensemble=ensemble,
selected_keys=candidate_models,
n_preds=len(candidate_models),
index_run=iteration)
# We can't use candidate_models here, as n_sel_* might be empty
valid_pred = self.predict(set_="valid",
ensemble=ensemble,
selected_keys=n_sel_valid,
n_preds=len(candidate_models),
index_run=iteration)
# TODO if predictions fails, build the model again during the
# next iteration!
test_pred = self.predict(set_="test",
ensemble=ensemble,
selected_keys=n_sel_test,
n_preds=len(candidate_models),
index_run=iteration)
# Add a score to run history to see ensemble progress
self._add_ensemble_trajectory(
train_pred,
valid_pred,
test_pred
)
# The loaded predictions and the hash can only be saved after the ensemble has been
# built, because the hash is computed during the construction of the ensemble
with open(self.ensemble_memory_file, "wb") as memory:
pickle.dump((self.read_preds, self.last_hash), memory)
if return_predictions:
return self.ensemble_history, self.ensemble_nbest, train_pred, valid_pred, test_pred
else:
return self.ensemble_history, self.ensemble_nbest, None, None, None
def get_disk_consumption(self, pred_path):
"""
gets the cost of a model being on disc
"""
match = self.model_fn_re.search(pred_path)
if not match:
raise ValueError("Invalid path format %s" % pred_path)
_seed = int(match.group(1))
_num_run = int(match.group(2))
_budget = float(match.group(3))
stored_files_for_run = os.listdir(
self.backend.get_numrun_directory(_seed, _num_run, _budget))
stored_files_for_run = [
os.path.join(self.backend.get_numrun_directory(_seed, _num_run, _budget), file_name)
for file_name in stored_files_for_run]
this_model_cost = sum([os.path.getsize(path) for path in stored_files_for_run])
# get the megabytes
return round(this_model_cost / math.pow(1024, 2), 2)
def compute_loss_per_model(self):
"""
Compute the loss of the predictions on ensemble building data set;
populates self.read_preds and self.read_losses
"""
self.logger.debug("Read ensemble data set predictions")
if self.y_true_ensemble is None:
try:
self.y_true_ensemble = self.backend.load_targets_ensemble()
except FileNotFoundError:
self.logger.debug(
"Could not find true targets on ensemble data set: %s",
traceback.format_exc(),
)
return False
pred_path = os.path.join(
glob.escape(self.backend.get_runs_directory()),
'%d_*_*' % self.seed,
'predictions_ensemble_%s_*_*.npy*' % self.seed,
)
y_ens_files = glob.glob(pred_path)
y_ens_files = [y_ens_file for y_ens_file in y_ens_files
if y_ens_file.endswith('.npy') or y_ens_file.endswith('.npy.gz')]
self.y_ens_files = y_ens_files
# no validation predictions so far -- no files
if len(self.y_ens_files) == 0:
self.logger.debug("Found no prediction files on ensemble data set:"
" %s" % pred_path)
return False
# First sort files chronologically
to_read = []
for y_ens_fn in self.y_ens_files:
match = self.model_fn_re.search(y_ens_fn)
_seed = int(match.group(1))
_num_run = int(match.group(2))
_budget = float(match.group(3))
mtime = os.path.getmtime(y_ens_fn)
to_read.append([y_ens_fn, match, _seed, _num_run, _budget, mtime])
n_read_files = 0
# Now read file wrt to num_run
for y_ens_fn, match, _seed, _num_run, _budget, mtime in \
sorted(to_read, key=lambda x: x[5]):
if self.read_at_most and n_read_files >= self.read_at_most:
# limit the number of files that will be read
# to limit memory consumption
break
if not y_ens_fn.endswith(".npy") and not y_ens_fn.endswith(".npy.gz"):
self.logger.info('Error loading file (not .npy or .npy.gz): %s', y_ens_fn)
continue
if not self.read_losses.get(y_ens_fn):
self.read_losses[y_ens_fn] = {
"ens_loss": np.inf,
"mtime_ens": 0,
"mtime_valid": 0,
"mtime_test": 0,
"seed": _seed,
"num_run": _num_run,
"budget": _budget,
"disc_space_cost_mb": None,
# Lazy keys so far:
# 0 - not loaded
# 1 - loaded and in memory
# 2 - loaded but dropped again
# 3 - deleted from disk due to space constraints
"loaded": 0
}
if not self.read_preds.get(y_ens_fn):
self.read_preds[y_ens_fn] = {
Y_ENSEMBLE: None,
Y_VALID: None,
Y_TEST: None,
}
if self.read_losses[y_ens_fn]["mtime_ens"] == mtime:
# same time stamp; nothing changed;
continue
# actually read the predictions and compute their respective loss
try:
y_ensemble = self._read_np_fn(y_ens_fn)
loss = calculate_loss(solution=self.y_true_ensemble,
prediction=y_ensemble,
task_type=self.task_type,
metric=self.metric,
scoring_functions=None)
if np.isfinite(self.read_losses[y_ens_fn]["ens_loss"]):
self.logger.debug(
'Changing ensemble loss for file %s from %f to %f '
'because file modification time changed? %f - %f',
y_ens_fn,
self.read_losses[y_ens_fn]["ens_loss"],
loss,
self.read_losses[y_ens_fn]["mtime_ens"],
os.path.getmtime(y_ens_fn),
)
self.read_losses[y_ens_fn]["ens_loss"] = loss
# It is not needed to create the object here
# To save memory, we just compute the loss.
self.read_losses[y_ens_fn]["mtime_ens"] = os.path.getmtime(y_ens_fn)
self.read_losses[y_ens_fn]["loaded"] = 2
self.read_losses[y_ens_fn]["disc_space_cost_mb"] = self.get_disk_consumption(
y_ens_fn
)
n_read_files += 1
except Exception:
self.logger.warning(
'Error loading %s: %s',
y_ens_fn,
traceback.format_exc(),
)
self.read_losses[y_ens_fn]["ens_loss"] = np.inf
self.logger.debug(
'Done reading %d new prediction files. Loaded %d predictions in '
'total.',
n_read_files,
np.sum([pred["loaded"] > 0 for pred in self.read_losses.values()])
)
return True
def get_n_best_preds(self):
"""
get best n predictions (i.e., keys of self.read_losses)
according to the loss on the "ensemble set"
n: self.ensemble_nbest
Side effects:
->Define the n-best models to use in ensemble
->Only the best models are loaded
->Any model that is not best is candidate to deletion
if max models in disc is exceeded.
"""
sorted_keys = self._get_list_of_sorted_preds()
# number of models available
num_keys = len(sorted_keys)
# remove all that are at most as good as random
# note: dummy model must have run_id=1 (there is no run_id=0)
dummy_losses = list(filter(lambda x: x[2] == 1, sorted_keys))
# number of dummy models
num_dummy = len(dummy_losses)
dummy_loss = dummy_losses[0]
self.logger.debug("Use %f as dummy loss" % dummy_loss[1])
# sorted_keys looks like: (k, v["ens_loss"], v["num_run"])
# On position 1 we have the loss of a minimization problem.
# keep only the predictions with a loss smaller than the dummy
# prediction
sorted_keys = filter(lambda x: x[1] < dummy_loss[1], sorted_keys)
# remove Dummy Classifier
sorted_keys = list(filter(lambda x: x[2] > 1, sorted_keys))
if not sorted_keys:
# no model left; try to use dummy loss (num_run==0)
# log warning when there are other models but not better than dummy model
if num_keys > num_dummy:
self.logger.warning("No models better than random - using Dummy loss!"
"Number of models besides current dummy model: %d. "
"Number of dummy models: %d",
num_keys - 1,
num_dummy)
sorted_keys = [
(k, v["ens_loss"], v["num_run"]) for k, v in self.read_losses.items()
if v["seed"] == self.seed and v["num_run"] == 1
]
# reload predictions if losses changed over time and a model is
# considered to be in the top models again!
if not isinstance(self.ensemble_nbest, numbers.Integral):
# Transform to number of models to keep. Keep at least one
keep_nbest = max(1, min(len(sorted_keys),
int(len(sorted_keys) * self.ensemble_nbest)))
self.logger.debug(
"Library pruning: using only top %f percent of the models for ensemble "
"(%d out of %d)",
self.ensemble_nbest * 100, keep_nbest, len(sorted_keys)
)