-
Notifications
You must be signed in to change notification settings - Fork 1.5k
/
base.py
1531 lines (1310 loc) · 68.1 KB
/
base.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
# -*- coding: utf-8 -*-
"""This file is part of the TPOT library.
TPOT was primarily developed at the University of Pennsylvania by:
- Randal S. Olson (rso@randalolson.com)
- Weixuan Fu (weixuanf@upenn.edu)
- Daniel Angell (dpa34@drexel.edu)
- and many more generous open source contributors
TPOT is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as
published by the Free Software Foundation, either version 3 of
the License, or (at your option) any later version.
TPOT is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with TPOT. If not, see <http://www.gnu.org/licenses/>.
"""
from __future__ import print_function
import random
import inspect
import warnings
import sys
import imp
from functools import partial
from datetime import datetime
from multiprocessing import cpu_count
import os
import re
import errno
from tempfile import mkdtemp
from shutil import rmtree
import numpy as np
from scipy import sparse
import deap
from deap import base, creator, tools, gp
from tqdm import tqdm
from copy import copy, deepcopy
from sklearn.base import BaseEstimator
from sklearn.utils import check_X_y
from sklearn.externals.joblib import Parallel, delayed, Memory
from sklearn.pipeline import make_pipeline, make_union
from sklearn.preprocessing import FunctionTransformer, Imputer
from sklearn.model_selection import train_test_split
from sklearn.metrics.scorer import make_scorer, _BaseScorer
from update_checker import update_check
from ._version import __version__
from .operator_utils import TPOTOperatorClassFactory, Operator, ARGType
from .export_utils import export_pipeline, expr_to_tree, generate_pipeline_code
from .decorators import _pre_test
from .builtins import CombineDFs, StackingEstimator
from .config.classifier_light import classifier_config_dict_light
from .config.regressor_light import regressor_config_dict_light
from .config.classifier_mdr import tpot_mdr_classifier_config_dict
from .config.regressor_mdr import tpot_mdr_regressor_config_dict
from .config.regressor_sparse import regressor_config_sparse
from .config.classifier_sparse import classifier_config_sparse
from .metrics import SCORERS
from .gp_types import Output_Array
from .gp_deap import eaMuPlusLambda, mutNodeReplacement, _wrapped_cross_val_score, cxOnePoint
# hot patch for Windows: solve the problem of crashing python after Ctrl + C in Windows OS
# https://github.com/ContinuumIO/anaconda-issues/issues/905
if sys.platform.startswith('win'):
import win32api
try:
import _thread
except ImportError:
import thread as _thread
def handler(dwCtrlType, hook_sigint=_thread.interrupt_main):
"""SIGINT handler function."""
if dwCtrlType == 0: # CTRL_C_EVENT
hook_sigint()
return 1 # don't chain to the next handler
return 0
win32api.SetConsoleCtrlHandler(handler, 1)
class TPOTBase(BaseEstimator):
"""Automatically creates and optimizes machine learning pipelines using GP."""
def __init__(self, generations=100, population_size=100, offspring_size=None,
mutation_rate=0.9, crossover_rate=0.1,
scoring=None, cv=5, subsample=1.0, n_jobs=1,
max_time_mins=None, max_eval_time_mins=5,
random_state=None, config_dict=None,
warm_start=False, memory=None,
periodic_checkpoint_folder=None, early_stop=None,
verbosity=0, disable_update_check=False):
"""Set up the genetic programming algorithm for pipeline optimization.
Parameters
----------
generations: int, optional (default: 100)
Number of iterations to the run pipeline optimization process.
Generally, TPOT will work better when you give it more generations (and
therefore time) to optimize the pipeline. TPOT will evaluate
POPULATION_SIZE + GENERATIONS x OFFSPRING_SIZE pipelines in total.
population_size: int, optional (default: 100)
Number of individuals to retain in the GP population every generation.
Generally, TPOT will work better when you give it more individuals
(and therefore time) to optimize the pipeline. TPOT will evaluate
POPULATION_SIZE + GENERATIONS x OFFSPRING_SIZE pipelines in total.
offspring_size: int, optional (default: None)
Number of offspring to produce in each GP generation.
By default, offspring_size = population_size.
mutation_rate: float, optional (default: 0.9)
Mutation rate for the genetic programming algorithm in the range [0.0, 1.0].
This parameter tells the GP algorithm how many pipelines to apply random
changes to every generation. We recommend using the default parameter unless
you understand how the mutation rate affects GP algorithms.
crossover_rate: float, optional (default: 0.1)
Crossover rate for the genetic programming algorithm in the range [0.0, 1.0].
This parameter tells the genetic programming algorithm how many pipelines to
"breed" every generation. We recommend using the default parameter unless you
understand how the mutation rate affects GP algorithms.
scoring: string or callable, optional
Function used to evaluate the quality of a given pipeline for the
problem. By default, accuracy is used for classification problems and
mean squared error (MSE) for regression problems.
Offers the same options as sklearn.model_selection.cross_val_score as well as
a built-in score 'balanced_accuracy'. Classification metrics:
['accuracy', 'adjusted_rand_score', 'average_precision', 'balanced_accuracy',
'f1', 'f1_macro', 'f1_micro', 'f1_samples', 'f1_weighted',
'precision', 'precision_macro', 'precision_micro', 'precision_samples',
'precision_weighted', 'recall', 'recall_macro', 'recall_micro',
'recall_samples', 'recall_weighted', 'roc_auc']
Regression metrics:
['neg_median_absolute_error', 'neg_mean_absolute_error',
'neg_mean_squared_error', 'r2']
If you would like to use a custom scoring function, you can pass a callable
function to this parameter with the signature scorer(y_true, y_pred).
See the section on scoring functions in the documentation for more details.
TPOT assumes that any custom scoring function with "error" or "loss" in the
name is meant to be minimized, whereas any other functions will be maximized.
cv: int or cross-validation generator, optional (default: 5)
If CV is a number, then it is the number of folds to evaluate each
pipeline over in k-fold cross-validation during the TPOT optimization
process. If it is an object then it is an object to be used as a
cross-validation generator.
subsample: float, optional (default: 1.0)
Subsample ratio of the training instance. Setting it to 0.5 means that TPOT
randomly collects half of training samples for pipeline optimization process.
n_jobs: int, optional (default: 1)
Number of CPUs for evaluating pipelines in parallel during the TPOT
optimization process. Assigning this to -1 will use as many cores as available
on the computer.
max_time_mins: int, optional (default: None)
How many minutes TPOT has to optimize the pipeline.
If provided, this setting will override the "generations" parameter and allow
TPOT to run until it runs out of time.
max_eval_time_mins: int, optional (default: 5)
How many minutes TPOT has to optimize a single pipeline.
Setting this parameter to higher values will allow TPOT to explore more
complex pipelines, but will also allow TPOT to run longer.
random_state: int, optional (default: None)
Random number generator seed for TPOT. Use this parameter to make sure
that TPOT will give you the same results each time you run it against the
same data set with that seed.
config_dict: a Python dictionary or string, optional (default: None)
Python dictionary:
A dictionary customizing the operators and parameters that
TPOT uses in the optimization process.
For examples, see config_regressor.py and config_classifier.py
Path for configuration file:
A path to a configuration file for customizing the operators and parameters that
TPOT uses in the optimization process.
For examples, see config_regressor.py and config_classifier.py
String 'TPOT light':
TPOT uses a light version of operator configuration dictionary instead of
the default one.
String 'TPOT MDR':
TPOT uses a list of TPOT-MDR operator configuration dictionary instead of
the default one.
String 'TPOT sparse':
TPOT uses a configuration dictionary with a one-hot-encoder and the
operators normally included in TPOT that also support sparse matrices.
warm_start: bool, optional (default: False)
Flag indicating whether the TPOT instance will reuse the population from
previous calls to fit().
memory: a Memory object or string, optional (default: None)
If supplied, pipeline will cache each transformer after calling fit. This feature
is used to avoid computing the fit transformers within a pipeline if the parameters
and input data are identical with another fitted pipeline during optimization process.
String 'auto':
TPOT uses memory caching with a temporary directory and cleans it up upon shutdown.
String path of a caching directory
TPOT uses memory caching with the provided directory and TPOT does NOT clean
the caching directory up upon shutdown.
Memory object:
TPOT uses the instance of sklearn.external.joblib.Memory for memory caching,
and TPOT does NOT clean the caching directory up upon shutdown.
None:
TPOT does not use memory caching.
periodic_checkpoint_folder: path string, optional (default: None)
If supplied, a folder in which tpot will periodically save the best pipeline so far while optimizing.
Currently once per generation but not more often than once per 30 seconds.
Useful in multiple cases:
Sudden death before tpot could save optimized pipeline
Track its progress
Grab pipelines while it's still optimizing
early_stop: int or None (default: None)
How many generations TPOT checks whether there is no improvement in optimization process.
End optimization process if there is no improvement in the set number of generations.
verbosity: int, optional (default: 0)
How much information TPOT communicates while it's running.
0 = none, 1 = minimal, 2 = high, 3 = all.
A setting of 2 or higher will add a progress bar during the optimization procedure.
disable_update_check: bool, optional (default: False)
Flag indicating whether the TPOT version checker should be disabled.
Returns
-------
None
"""
if self.__class__.__name__ == 'TPOTBase':
raise RuntimeError('Do not instantiate the TPOTBase class directly; use TPOTRegressor or TPOTClassifier instead.')
# Prompt the user if their version is out of date
self.disable_update_check = disable_update_check
if not self.disable_update_check:
update_check('tpot', __version__)
self._pareto_front = None
self._optimized_pipeline = None
self._optimized_pipeline_score = None
self._exported_pipeline_text = ""
self.fitted_pipeline_ = None
self._fitted_imputer = None
self._imputed = False
self._pop = []
self.warm_start = warm_start
self.population_size = population_size
self.generations = generations
self.max_time_mins = max_time_mins
self.max_eval_time_mins = max_eval_time_mins
self.max_eval_time_seconds = max(int(self.max_eval_time_mins * 60), 1)
self.periodic_checkpoint_folder = periodic_checkpoint_folder
self.early_stop = early_stop
self._last_optimized_pareto_front = None
self._last_optimized_pareto_front_n_gens = 0
self.memory = memory
self._memory = None # initial Memory setting for sklearn pipeline
# dont save periodic pipelines more often than this
self._output_best_pipeline_period_seconds = 30
# Try crossover and mutation at most this many times for
# any one given individual (or pair of individuals)
self._max_mut_loops = 50
# Set offspring_size equal to population_size by default
if offspring_size:
self.offspring_size = offspring_size
else:
self.offspring_size = population_size
self.config_dict_params = config_dict
self._setup_config(self.config_dict_params)
self.operators = []
self.arguments = []
for key in sorted(self.config_dict.keys()):
op_class, arg_types = TPOTOperatorClassFactory(
key,
self.config_dict[key],
BaseClass=Operator,
ArgBaseClass=ARGType
)
if op_class:
self.operators.append(op_class)
self.arguments += arg_types
# Schedule TPOT to run for many generations if the user specifies a
# run-time limit TPOT will automatically interrupt itself when the timer
# runs out
if max_time_mins is not None:
self.generations = 1000000
self.mutation_rate = mutation_rate
self.crossover_rate = crossover_rate
if self.mutation_rate + self.crossover_rate > 1:
raise ValueError(
'The sum of the crossover and mutation probabilities must be <= 1.0.'
)
self.verbosity = verbosity
self.operators_context = {
'make_pipeline': make_pipeline,
'make_union': make_union,
'StackingEstimator': StackingEstimator,
'FunctionTransformer': FunctionTransformer,
'copy': copy
}
self._pbar = None
# Specifies where to output the progress messages (default: sys.stdout).
# Maybe open this API in future version of TPOT.(io.TextIOWrapper or io.StringIO)
self._file = sys.stdout
# Dictionary of individuals that have already been evaluated in previous
# generations
self.evaluated_individuals_ = {}
self.random_state = random_state
self._setup_scoring_function(scoring)
self.cv = cv
self.subsample = subsample
if self.subsample <= 0.0 or self.subsample > 1.0:
raise ValueError(
'The subsample ratio of the training instance must be in the range (0.0, 1.0].'
)
if n_jobs == -1:
self.n_jobs = cpu_count()
else:
self.n_jobs = n_jobs
self._setup_pset()
self._setup_toolbox()
def _setup_scoring_function(self, scoring):
if scoring:
if isinstance(scoring, str):
if scoring not in SCORERS:
raise ValueError(
'The scoring function {} is not available. Please '
'choose a valid scoring function from the TPOT '
'documentation.'.format(scoring)
)
elif callable(scoring):
# Heuristic to ensure user has not passed a metric
module = getattr(scoring, '__module__', None)
if sys.version_info[0] < 3:
if inspect.isfunction(scoring):
args_list = inspect.getargspec(scoring)[0]
else:
args_list = inspect.getargspec(scoring.__call__)[0]
else:
args_list = inspect.getfullargspec(scoring)[0]
if args_list == ["y_true", "y_pred"] or (hasattr(module, 'startswith') and \
(module.startswith('sklearn.metrics.') or module.startswith('tpot.metrics')) and \
not module.startswith('sklearn.metrics.scorer') and \
not module.startswith('sklearn.metrics.tests.')):
scoring_name = scoring.__name__
greater_is_better = 'loss' not in scoring_name and 'error' not in scoring_name
SCORERS[scoring_name] = make_scorer(scoring, greater_is_better=greater_is_better)
warnings.simplefilter('always', DeprecationWarning)
warnings.warn('Scoring function {} looks like it is a metric function '
'rather than a scikit-learn scorer. This scoring type was deprecated '
'in version TPOT 0.9.1 and will be removed in version 0.11. '
'Please update your custom scoring function.'.format(scoring), DeprecationWarning)
else:
if isinstance(scoring, _BaseScorer):
scoring_name = scoring._score_func.__name__
else:
scoring_name = scoring.__name__
SCORERS[scoring_name] = scoring
scoring = scoring_name
self.scoring_function = scoring
def _setup_config(self, config_dict):
if config_dict:
if isinstance(config_dict, dict):
self.config_dict = config_dict
elif config_dict == 'TPOT light':
if self.classification:
self.config_dict = classifier_config_dict_light
else:
self.config_dict = regressor_config_dict_light
elif config_dict == 'TPOT MDR':
if self.classification:
self.config_dict = tpot_mdr_classifier_config_dict
else:
self.config_dict = tpot_mdr_regressor_config_dict
elif config_dict == 'TPOT sparse':
if self.classification:
self.config_dict = classifier_config_sparse
else:
self.config_dict = regressor_config_sparse
else:
config = self._read_config_file(config_dict)
if hasattr(config, 'tpot_config'):
self.config_dict = config.tpot_config
else:
raise ValueError(
'Could not find "tpot_config" in configuration file {}. '
'When using a custom config file for customizing operators '
'dictionary, the file must have a python dictionary with '
'the standardized name of "tpot_config"'.format(config_dict)
)
else:
self.config_dict = self.default_config_dict
def _read_config_file(self, config_path):
if os.path.isfile(config_path):
try:
custom_config = imp.new_module('custom_config')
with open(config_path, 'r') as config_file:
file_string = config_file.read()
exec(file_string, custom_config.__dict__)
return custom_config
except Exception as e:
raise ValueError(
'An error occured while attempting to read the specified '
'custom TPOT operator configuration file: {}'.format(e)
)
else:
raise ValueError(
'Could not open specified TPOT operator config file: '
'{}'.format(config_path)
)
def _setup_pset(self):
if self.random_state is not None:
random.seed(self.random_state)
np.random.seed(self.random_state)
self._pset = gp.PrimitiveSetTyped('MAIN', [np.ndarray], Output_Array)
self._pset.renameArguments(ARG0='input_matrix')
self._add_operators()
self._add_terminals()
if self.verbosity > 2:
print('{} operators have been imported by TPOT.'.format(len(self.operators)))
def _add_operators(self):
for operator in self.operators:
if operator.root:
# We need to add rooted primitives twice so that they can
# return both an Output_Array (and thus be the root of the tree),
# and return a np.ndarray so they can exist elsewhere in the tree.
p_types = (operator.parameter_types()[0], Output_Array)
self._pset.addPrimitive(operator, *p_types)
self._pset.addPrimitive(operator, *operator.parameter_types())
# Import required modules into local namespace so that pipelines
# may be evaluated directly
for key in sorted(operator.import_hash.keys()):
module_list = ', '.join(sorted(operator.import_hash[key]))
if key.startswith('tpot.'):
exec('from {} import {}'.format(key[4:], module_list))
else:
exec('from {} import {}'.format(key, module_list))
for var in operator.import_hash[key]:
self.operators_context[var] = eval(var)
self._pset.addPrimitive(CombineDFs(), [np.ndarray, np.ndarray], np.ndarray)
def _add_terminals(self):
for _type in self.arguments:
type_values = list(_type.values)
for val in type_values:
terminal_name = _type.__name__ + "=" + str(val)
self._pset.addTerminal(val, _type, name=terminal_name)
def _setup_toolbox(self):
with warnings.catch_warnings():
warnings.simplefilter('ignore')
creator.create('FitnessMulti', base.Fitness, weights=(-1.0, 1.0))
creator.create('Individual', gp.PrimitiveTree, fitness=creator.FitnessMulti, statistics=dict)
self._toolbox = base.Toolbox()
self._toolbox.register('expr', self._gen_grow_safe, pset=self._pset, min_=1, max_=3)
self._toolbox.register('individual', tools.initIterate, creator.Individual, self._toolbox.expr)
self._toolbox.register('population', tools.initRepeat, list, self._toolbox.individual)
self._toolbox.register('compile', self._compile_to_sklearn)
self._toolbox.register('select', tools.selNSGA2)
self._toolbox.register('mate', self._mate_operator)
self._toolbox.register('expr_mut', self._gen_grow_safe, min_=1, max_=4)
self._toolbox.register('mutate', self._random_mutation_operator)
def fit(self, features, target, sample_weight=None, groups=None):
"""Fit an optimized machine learning pipeline.
Uses genetic programming to optimize a machine learning pipeline that
maximizes score on the provided features and target. Performs internal
k-fold cross-validaton to avoid overfitting on the provided data. The
best pipeline is then trained on the entire set of provided samples.
Parameters
----------
features: array-like {n_samples, n_features}
Feature matrix
TPOT and all scikit-learn algorithms assume that the features will be numerical
and there will be no missing values. As such, when a feature matrix is provided
to TPOT, all missing values will automatically be replaced (i.e., imputed) using
median value imputation.
If you wish to use a different imputation strategy than median imputation, please
make sure to apply imputation to your feature set prior to passing it to TPOT.
target: array-like {n_samples}
List of class labels for prediction
sample_weight: array-like {n_samples}, optional
Per-sample weights. Higher weights indicate more importance. If specified,
sample_weight will be passed to any pipeline element whose fit() function accepts
a sample_weight argument. By default, using sample_weight does not affect tpot's
scoring functions, which determine preferences between pipelines.
groups: array-like, with shape {n_samples, }, optional
Group labels for the samples used when performing cross-validation.
This parameter should only be used in conjunction with sklearn's Group cross-validation
functions, such as sklearn.model_selection.GroupKFold
Returns
-------
self: object
Returns a copy of the fitted TPOT object
"""
features, target = self._check_dataset(features, target)
# Randomly collect a subsample of training samples for pipeline optimization process.
if self.subsample < 1.0:
features, _, target, _ = train_test_split(features, target, train_size=self.subsample, random_state=self.random_state)
# Raise a warning message if the training size is less than 1500 when subsample is not default value
if features.shape[0] < 1500:
print(
'Warning: Although subsample can accelerate pipeline optimization process, '
'too small training sample size may cause unpredictable effect on maximizing '
'score in pipeline optimization process. Increasing subsample ratio may get '
'a more reasonable outcome from optimization process in TPOT.'
)
# Set the seed for the GP run
if self.random_state is not None:
random.seed(self.random_state) # deap uses random
np.random.seed(self.random_state)
self._start_datetime = datetime.now()
self._last_pipeline_write = self._start_datetime
self._toolbox.register('evaluate', self._evaluate_individuals, features=features, target=target, sample_weight=sample_weight, groups=groups)
# assign population, self._pop can only be not None if warm_start is enabled
if self._pop:
pop = self._pop
else:
pop = self._toolbox.population(n=self.population_size)
def pareto_eq(ind1, ind2):
"""Determine whether two individuals are equal on the Pareto front.
Parameters
----------
ind1: DEAP individual from the GP population
First individual to compare
ind2: DEAP individual from the GP population
Second individual to compare
Returns
----------
individuals_equal: bool
Boolean indicating whether the two individuals are equal on
the Pareto front
"""
return np.allclose(ind1.fitness.values, ind2.fitness.values)
# Generate new pareto front if it doesn't already exist for warm start
if not self.warm_start or not self._pareto_front:
self._pareto_front = tools.ParetoFront(similar=pareto_eq)
# Start the progress bar
if self.max_time_mins:
total_evals = self.population_size
else:
total_evals = self.offspring_size * self.generations + self.population_size
self._pbar = tqdm(total=total_evals, unit='pipeline', leave=False,
disable=not (self.verbosity >= 2), desc='Optimization Progress')
try:
with warnings.catch_warnings():
self._setup_memory()
warnings.simplefilter('ignore')
pop, _ = eaMuPlusLambda(
population=pop,
toolbox=self._toolbox,
mu=self.population_size,
lambda_=self.offspring_size,
cxpb=self.crossover_rate,
mutpb=self.mutation_rate,
ngen=self.generations,
pbar=self._pbar,
halloffame=self._pareto_front,
verbose=self.verbosity,
per_generation_function=self._check_periodic_pipeline
)
# store population for the next call
if self.warm_start:
self._pop = pop
# Allow for certain exceptions to signal a premature fit() cancellation
except (KeyboardInterrupt, SystemExit, StopIteration) as e:
if self.verbosity > 0:
self._pbar.write('', file=self._file)
self._pbar.write('{}\nTPOT closed prematurely. Will use the current best pipeline.'.format(e),
file=self._file)
finally:
# keep trying 10 times in case weird things happened like multiple CTRL+C or exceptions
attempts = 10
for attempt in range(attempts):
try:
# Close the progress bar
# Standard truthiness checks won't work for tqdm
if not isinstance(self._pbar, type(None)):
self._pbar.close()
self._update_top_pipeline()
self._summary_of_best_pipeline(features, target)
# Delete the temporary cache before exiting
self._cleanup_memory()
break
except (KeyboardInterrupt, SystemExit, Exception) as e:
# raise the exception if it's our last attempt
if attempt == (attempts - 1):
raise e
return self
def _setup_memory(self):
"""Setup Memory object for memory caching.
"""
if self.memory:
if isinstance(self.memory, str):
if self.memory == "auto":
# Create a temporary folder to store the transformers of the pipeline
self._cachedir = mkdtemp()
elif os.path.isdir(self.memory):
self._cachedir = self.memory
else:
raise ValueError(
'Could not find directory for memory caching: {}'.format(self.memory)
)
self._memory = Memory(cachedir=self._cachedir, verbose=0)
elif isinstance(self.memory, Memory):
self._memory = self.memory
else:
raise ValueError(
'Could not recognize Memory object for pipeline caching. '
'Please provide an instance of sklearn.external.joblib.Memory,'
' a path to a directory on your system, or \"auto\".'
)
def _cleanup_memory(self):
"""Clean up caching directory at the end of optimization process only when memory='auto'"""
if self.memory == "auto":
rmtree(self._cachedir)
self._memory = None
def _update_top_pipeline(self):
"""Helper function to update the _optimized_pipeline field."""
# Store the pipeline with the highest internal testing score
if self._pareto_front:
self._optimized_pipeline_score = -float('inf')
for pipeline, pipeline_scores in zip(self._pareto_front.items, reversed(self._pareto_front.keys)):
if pipeline_scores.wvalues[1] > self._optimized_pipeline_score:
self._optimized_pipeline = pipeline
self._optimized_pipeline_score = pipeline_scores.wvalues[1]
if not self._optimized_pipeline:
raise RuntimeError('There was an error in the TPOT optimization '
'process. This could be because the data was '
'not formatted properly, or because data for '
'a regression problem was provided to the '
'TPOTClassifier object. Please make sure you '
'passed the data to TPOT correctly.')
else:
pareto_front_wvalues = [pipeline_scores.wvalues[1] for pipeline_scores in self._pareto_front.keys]
if not self._last_optimized_pareto_front:
self._last_optimized_pareto_front = pareto_front_wvalues
elif self._last_optimized_pareto_front == pareto_front_wvalues:
self._last_optimized_pareto_front_n_gens += 1
else:
self._last_optimized_pareto_front = pareto_front_wvalues
self._last_optimized_pareto_front_n_gens = 0
else:
# If user passes CTRL+C in initial generation, self._pareto_front (halloffame) shoule be not updated yet.
# need raise RuntimeError because no pipeline has been optimized
raise RuntimeError('A pipeline has not yet been optimized. Please call fit() first.')
def _summary_of_best_pipeline(self, features, target):
"""Print out best pipeline at the end of optimization process.
Parameters
----------
features: array-like {n_samples, n_features}
Feature matrix
target: array-like {n_samples}
List of class labels for prediction
Returns
-------
self: object
Returns a copy of the fitted TPOT object
"""
if not self._optimized_pipeline:
raise RuntimeError('There was an error in the TPOT optimization '
'process. This could be because the data was '
'not formatted properly, or because data for '
'a regression problem was provided to the '
'TPOTClassifier object. Please make sure you '
'passed the data to TPOT correctly.')
else:
self.fitted_pipeline_ = self._toolbox.compile(expr=self._optimized_pipeline)
with warnings.catch_warnings():
warnings.simplefilter('ignore')
self.fitted_pipeline_.fit(features, target)
if self.verbosity in [1, 2]:
# Add an extra line of spacing if the progress bar was used
if self.verbosity >= 2:
print('')
optimized_pipeline_str = self.clean_pipeline_string(self._optimized_pipeline)
print('Best pipeline:', optimized_pipeline_str)
# Store and fit the entire Pareto front as fitted models for convenience
self.pareto_front_fitted_pipelines_ = {}
for pipeline in self._pareto_front.items:
self.pareto_front_fitted_pipelines_[str(pipeline)] = self._toolbox.compile(expr=pipeline)
with warnings.catch_warnings():
warnings.simplefilter('ignore')
self.pareto_front_fitted_pipelines_[str(pipeline)].fit(features, target)
def predict(self, features):
"""Use the optimized pipeline to predict the target for a feature set.
Parameters
----------
features: array-like {n_samples, n_features}
Feature matrix
Returns
----------
array-like: {n_samples}
Predicted target for the samples in the feature matrix
"""
if not self.fitted_pipeline_:
raise RuntimeError('A pipeline has not yet been optimized. Please call fit() first.')
features = features.astype(np.float64)
if np.any(np.isnan(features)):
features = self._impute_values(features)
return self.fitted_pipeline_.predict(features)
def fit_predict(self, features, target, sample_weight=None, groups=None):
"""Call fit and predict in sequence.
Parameters
----------
features: array-like {n_samples, n_features}
Feature matrix
target: array-like {n_samples}
List of class labels for prediction
sample_weight: array-like {n_samples}, optional
Per-sample weights. Higher weights force TPOT to put more emphasis on those points
groups: array-like, with shape {n_samples, }, optional
Group labels for the samples used when performing cross-validation.
This parameter should only be used in conjunction with sklearn's Group cross-validation
functions, such as sklearn.model_selection.GroupKFold
Returns
----------
array-like: {n_samples}
Predicted target for the provided features
"""
self.fit(features, target, sample_weight=sample_weight, groups=groups)
return self.predict(features)
def score(self, testing_features, testing_target):
"""Return the score on the given testing data using the user-specified scoring function.
Parameters
----------
testing_features: array-like {n_samples, n_features}
Feature matrix of the testing set
testing_target: array-like {n_samples}
List of class labels for prediction in the testing set
Returns
-------
accuracy_score: float
The estimated test set accuracy
"""
if self.fitted_pipeline_ is None:
raise RuntimeError('A pipeline has not yet been optimized. Please call fit() first.')
if np.any(np.isnan(testing_features)):
testing_features = self._impute_values(testing_features)
# If the scoring function is a string, we must adjust to use the sklearn
# scoring interface
score = SCORERS[self.scoring_function](
self.fitted_pipeline_,
testing_features.astype(np.float64),
testing_target.astype(np.float64)
)
return score
def predict_proba(self, features):
"""Use the optimized pipeline to estimate the class probabilities for a feature set.
Parameters
----------
features: array-like {n_samples, n_features}
Feature matrix of the testing set
Returns
-------
array-like: {n_samples, n_target}
The class probabilities of the input samples
"""
if not self.fitted_pipeline_:
raise RuntimeError('A pipeline has not yet been optimized. Please call fit() first.')
else:
if not (hasattr(self.fitted_pipeline_, 'predict_proba')):
raise RuntimeError('The fitted pipeline does not have the predict_proba() function.')
return self.fitted_pipeline_.predict_proba(features.astype(np.float64))
def set_params(self, **params):
"""Set the parameters of TPOT.
Returns
-------
self
"""
self.__init__(**params)
return self
def clean_pipeline_string(self, individual):
"""Provide a string of the individual without the parameter prefixes.
Parameters
----------
individual: individual
Individual which should be represented by a pretty string
Returns
-------
A string like str(individual), but with parameter prefixes removed.
"""
dirty_string = str(individual)
# There are many parameter prefixes in the pipeline strings, used solely for
# making the terminal name unique, eg. LinearSVC__.
parameter_prefixes = [(m.start(), m.end()) for m in re.finditer(', [\w]+__', dirty_string)]
# We handle them in reverse so we do not mess up indices
pretty = dirty_string
for (start, end) in reversed(parameter_prefixes):
pretty = pretty[:start + 2] + pretty[end:]
return pretty
def _check_periodic_pipeline(self):
"""If enough time has passed, save a new optimized pipeline.
Currently used in the per generation hook in the optimization loop.
"""
self._update_top_pipeline()
if self.periodic_checkpoint_folder is not None:
total_since_last_pipeline_save = (datetime.now() - self._last_pipeline_write).total_seconds()
if total_since_last_pipeline_save > self._output_best_pipeline_period_seconds:
self._last_pipeline_write = datetime.now()
self._save_periodic_pipeline()
if self.early_stop is not None:
if self._last_optimized_pareto_front_n_gens >= self.early_stop:
raise StopIteration("The optimized pipeline was not improved after evaluating {} more generations. "
"Will end the optimization process.\n".format(self.early_stop))
def _save_periodic_pipeline(self):
try:
self._create_periodic_checkpoint_folder()
filename = os.path.join(self.periodic_checkpoint_folder, 'pipeline_{}.py'.format(datetime.now().strftime('%Y.%m.%d_%H-%M-%S')))
did_export = self.export(filename, skip_if_repeated=True)
if not did_export:
self._update_pbar(pbar_num=0, pbar_msg='Periodic pipeline was not saved, probably saved before...')
else:
self._update_pbar(pbar_num=0, pbar_msg='Saving best periodic pipeline to {}'.format(filename))
except Exception as e:
self._update_pbar(pbar_num=0, pbar_msg='Failed saving periodic pipeline, exception:\n{}'.format(str(e)[:250]))
def _create_periodic_checkpoint_folder(self):
try:
os.makedirs(self.periodic_checkpoint_folder)
self._update_pbar(pbar_msg='Created new folder to save periodic pipeline: {}'.format(self.periodic_checkpoint_folder))
except OSError as e:
if e.errno == errno.EEXIST and os.path.isdir(self.periodic_checkpoint_folder):
pass # Folder already exists. User probably created it.
else:
raise ValueError('Failed creating the periodic_checkpoint_folder:\n{}'.format(e))
def export(self, output_file_name, skip_if_repeated=False):
"""Export the optimized pipeline as Python code.
Parameters
----------
output_file_name: string
String containing the path and file name of the desired output file
skip_if_repeated: boolean
If True, skip the actual writing if a pipeline
code would be identical to the last pipeline exported
Returns
-------
False if it skipped writing the pipeline to file
True if the pipeline was actually written
"""
if self._optimized_pipeline is None:
raise RuntimeError('A pipeline has not yet been optimized. Please call fit() first.')
to_write = export_pipeline(self._optimized_pipeline, self.operators, self._pset, self._imputed, self._optimized_pipeline_score)
# dont export a pipeline you just had
if skip_if_repeated and (self._exported_pipeline_text == to_write):
return False
with open(output_file_name, 'w') as output_file:
output_file.write(to_write)
self._exported_pipeline_text = to_write
return True
def _impute_values(self, features):
"""Impute missing values in a feature set.
Parameters
----------
features: array-like {n_samples, n_features}
A feature matrix
Returns
-------
array-like {n_samples, n_features}
"""
if self.verbosity > 1:
print('Imputing missing values in feature set')
if self._fitted_imputer is None:
self._fitted_imputer = Imputer(strategy="median")
self._fitted_imputer.fit(features)
return self._fitted_imputer.transform(features)
def _check_dataset(self, features, target):
"""Check if a dataset has a valid feature set and labels.
Parameters
----------
features: array-like {n_samples, n_features}