-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
Copy pathbase.py
2045 lines (1808 loc) · 84.2 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 ([email protected])
- Weixuan Fu ([email protected])
- Daniel Angell ([email protected])
- 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
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 types
import numpy as np
from pandas import DataFrame
from scipy import sparse
import deap
from deap import base, creator, tools, gp
from copy import copy, deepcopy
from sklearn.base import BaseEstimator
from sklearn.utils import check_X_y, check_consistent_length, check_array
from sklearn.pipeline import make_union, make_pipeline
from sklearn.preprocessing import FunctionTransformer
from sklearn.impute import SimpleImputer
from sklearn.model_selection import train_test_split
from sklearn.model_selection._split import check_cv
from sklearn.utils.metaestimators import available_if
from joblib import Parallel, delayed, Memory
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,
set_param_recursive,
)
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 .config.classifier_nn import classifier_config_nn
from .config.classifier_cuml import classifier_config_cuml
from .config.regressor_cuml import regressor_config_cuml
from .metrics import SCORERS
from .gp_types import Output_Array
from .gp_deap import (
eaMuPlusLambda,
mutNodeReplacement,
_wrapped_cross_val_score,
cxOnePoint,
)
try:
from imblearn.pipeline import make_pipeline as make_imblearn_pipeline
except:
make_imblearn_pipeline = None
with warnings.catch_warnings():
warnings.simplefilter("ignore")
from tqdm.autonotebook import tqdm
class TPOTBase(BaseEstimator):
"""Automatically creates and optimizes machine learning pipelines using GP."""
classification = None # set by child classes
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,
template=None,
warm_start=False,
memory=None,
use_dask=False,
periodic_checkpoint_folder=None,
early_stop=None,
verbosity=0,
disable_update_check=False,
log_file=None,
):
"""Set up the genetic programming algorithm for pipeline optimization.
Parameters
----------
generations: int or None, optional (default: 100)
Number of iterations to the run pipeline optimization process.
It must be a positive number or None. If None, the parameter
max_time_mins must be defined as the runtime limit.
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']
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. For n_jobs below -1, (n_cpus + 1 + n_jobs) are used.
Thus for n_jobs = -2, all CPUs but one are used.
max_time_mins: int, optional (default: None)
How many minutes TPOT has to optimize the pipeline.
If not None, this setting will allow TPOT to run until max_time_mins minutes
elapsed and then stop. TPOT will stop earlier if generationsis set and all
generations are already evaluated.
max_eval_time_mins: float, 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.
String 'TPOT NN':
TPOT uses a configuration dictionary for PyTorch neural network classifiers
included in `tpot.nn`.
template: string (default: None)
Template of predefined pipeline structure. The option is for specifying a desired structure
for the machine learning pipeline evaluated in TPOT. So far this option only supports
linear pipeline structure. Each step in the pipeline should be a main class of operators
(Selector, Transformer, Classifier or Regressor) or a specific operator
(e.g. SelectPercentile) defined in TPOT operator configuration. If one step is a main class,
TPOT will randomly assign all subclass operators (subclasses of SelectorMixin,
TransformerMixin, ClassifierMixin or RegressorMixin in scikit-learn) to that step.
Steps in the template are delimited by "-", e.g. "SelectPercentile-Transformer-Classifier".
By default value of template is None, TPOT generates tree-based pipeline randomly.
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. If the directory does not exist, TPOT will
create it.
Memory object:
TPOT uses the instance of joblib.Memory for memory caching,
and TPOT does NOT clean the caching directory up upon shutdown.
None:
TPOT does not use memory caching.
use_dask: boolean, default False
Whether to use Dask-ML's pipeline optimizations. This avoid re-fitting
the same estimator on the same split of data multiple times. It
will also provide more detailed diagnostics when using Dask's
distributed scheduler.
See `avoid repeated work <https://dask-ml.readthedocs.io/en/latest/hyper-parameter-search.html#avoid-repeated-work>`__
for more details.
periodic_checkpoint_folder: path string, optional (default: None)
If supplied, a folder in which tpot will periodically save pipelines in pareto front 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.
log_file: string, io.TextIOWrapper or io.StringIO, optional (defaul: sys.stdout)
Save progress content to a file.
Returns
-------
None
"""
if self.__class__.__name__ == "TPOTBase":
raise RuntimeError(
"Do not instantiate the TPOTBase class directly; use TPOTRegressor or TPOTClassifier instead."
)
self.population_size = population_size
self.offspring_size = offspring_size
self.generations = generations
self.mutation_rate = mutation_rate
self.crossover_rate = crossover_rate
self.scoring = scoring
self.cv = cv
self.subsample = subsample
self.n_jobs = n_jobs
self.max_time_mins = max_time_mins
self.max_eval_time_mins = max_eval_time_mins
self.periodic_checkpoint_folder = periodic_checkpoint_folder
self.early_stop = early_stop
self.config_dict = config_dict
self.template = template
self.warm_start = warm_start
self.memory = memory
self.use_dask = use_dask
self.verbosity = verbosity
self.disable_update_check = disable_update_check
self.random_state = random_state
self.log_file = log_file
def _setup_template(self, template):
self.template = template
if self.template is None:
self._min = 1
self._max = 3
else:
self._template_comp = template.split("-")
self._min = 0
self._max = 1
for comp in self._template_comp:
if comp == "CombineDFs":
self._max += 2
self._min += 1
else:
self._max += 1
self._min += 1
if self._max - self._min == 1:
self.tree_structure = False
else:
self.tree_structure = True
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)
)
self.scoring_function = scoring
elif callable(scoring):
# Heuristic to ensure user has not passed a metric
module = getattr(scoring, "__module__", None)
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.")
):
raise ValueError(
"Scoring function {} looks like it is a metric function "
"rather than a scikit-learn scorer. This scoring type was removed in version 0.11. "
"Please update your custom scoring function.".format(scoring)
)
else:
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
elif config_dict == "TPOT NN":
self._config_dict = classifier_config_nn
elif config_dict == "TPOT cuML":
if not _has_cuml():
raise ValueError(
"The GPU machine learning library cuML is not "
"available. To use cuML, please install cuML via conda."
)
elif self.classification:
self._config_dict = classifier_config_cuml
else:
self._config_dict = regressor_config_cuml
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 = types.ModuleType("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()
if self.verbosity > 2:
print(
"{} operators have been imported by TPOT.".format(len(self.operators))
)
def _add_operators(self):
main_type = ["Classifier", "Regressor", "Selector", "Transformer"]
ret_types = []
self.op_list = []
if self.template == None: # default pipeline structure
step_in_type = np.ndarray
step_ret_type = Output_Array
for operator in self.operators:
arg_types = operator.parameter_types()[0][1:]
p_types = ([step_in_type] + arg_types, step_ret_type)
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.
self._pset.addPrimitive(operator, *p_types)
tree_p_types = ([step_in_type] + arg_types, step_in_type)
self._pset.addPrimitive(operator, *tree_p_types)
self._import_hash_and_add_terminals(operator, arg_types)
self._pset.addPrimitive(
CombineDFs(), [step_in_type, step_in_type], step_in_type
)
else:
gp_types = {}
for idx, step in enumerate(self._template_comp):
# input class in each step
if idx:
step_in_type = ret_types[-1]
else:
step_in_type = np.ndarray
if step != "CombineDFs":
if idx < len(self._template_comp) - 1:
# create an empty for returning class for strongly-type GP
step_ret_type_name = "Ret_{}".format(idx)
step_ret_type = type(step_ret_type_name, (object,), {})
ret_types.append(step_ret_type)
else:
step_ret_type = Output_Array
check_template = True
if step == "CombineDFs":
self._pset.addPrimitive(
CombineDFs(), [step_in_type, step_in_type], step_in_type
)
elif main_type.count(step): # if the step is a main type
ops = [op for op in self.operators if op.type() == step]
for operator in ops:
arg_types = operator.parameter_types()[0][1:]
p_types = ([step_in_type] + arg_types, step_ret_type)
self._pset.addPrimitive(operator, *p_types)
self._import_hash_and_add_terminals(operator, arg_types)
else: # is the step is a specific operator or a wrong input
try:
operator = next(
op for op in self.operators if op.__name__ == step
)
except:
raise ValueError(
"An error occured while attempting to read the specified "
"template. Please check a step named {}".format(step)
)
arg_types = operator.parameter_types()[0][1:]
p_types = ([step_in_type] + arg_types, step_ret_type)
self._pset.addPrimitive(operator, *p_types)
self._import_hash_and_add_terminals(operator, arg_types)
self.ret_types = [np.ndarray, Output_Array] + ret_types
def _import_hash_and_add_terminals(self, operator, arg_types):
if not self.op_list.count(operator.__name__):
self._import_hash(operator)
self._add_terminals(arg_types)
self.op_list.append(operator.__name__)
def _import_hash(self, operator):
# 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)
def _add_terminals(self, arg_types):
for _type in arg_types:
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_=self._min, max_=self._max
)
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)
if self.tree_structure:
self._toolbox.register(
"expr_mut", self._gen_grow_safe, min_=self._min, max_=self._max + 1
)
else:
self._toolbox.register(
"expr_mut", self._gen_grow_safe, min_=self._min, max_=self._max
)
self._toolbox.register("mutate", self._random_mutation_operator)
def _get_make_pipeline_func(self):
imblearn_used = np.any([k.count("imblearn") for k in self._config_dict.keys()])
if imblearn_used == True:
assert make_imblearn_pipeline is not None, "You must install `imblearn`"
make_pipeline_func = make_imblearn_pipeline
else:
make_pipeline_func = make_pipeline
return make_pipeline_func
def _fit_init(self):
# initialization for fit function
if not self.warm_start or not hasattr(self, "_pareto_front"):
self._pop = []
self._pareto_front = None
self._last_optimized_pareto_front = None
self._last_optimized_pareto_front_n_gens = 0
self._setup_config(self.config_dict)
self._setup_template(self.template)
self.operators = []
self.arguments = []
make_pipeline_func = self._get_make_pipeline_func()
for key in sorted(self._config_dict.keys()):
op_class, arg_types = TPOTOperatorClassFactory(
key,
self._config_dict[key],
BaseClass=Operator,
ArgBaseClass=ARGType,
verbose=self.verbosity,
)
if op_class:
self.operators.append(op_class)
self.arguments += arg_types
self.operators_context = {
"make_pipeline": make_pipeline_func,
"make_union": make_union,
"StackingEstimator": StackingEstimator,
"FunctionTransformer": FunctionTransformer,
"copy": copy,
}
self._setup_pset()
self._setup_toolbox()
# Dictionary of individuals that have already been evaluated in previous
# generations or previous runs
self.evaluated_individuals_ = {}
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._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
if self.max_time_mins is None and self.generations is None:
raise ValueError(
"Either the parameter generations should bet set or a maximum evaluation time should be defined via max_time_mins"
)
# 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 self.max_time_mins is not None and self.generations is None:
self.generations = 1000000
# Prompt the user if their version is out of date
if not self.disable_update_check:
update_check("tpot", __version__)
if self.mutation_rate + self.crossover_rate > 1:
raise ValueError(
"The sum of the crossover and mutation probabilities must be <= 1.0."
)
self._pbar = None
if not self.log_file:
self.log_file_ = sys.stdout
elif isinstance(self.log_file, str):
self.log_file_ = open(self.log_file, "w")
else:
self.log_file_ = self.log_file
self._setup_scoring_function(self.scoring)
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 self.n_jobs == 0:
raise ValueError("The value 0 of n_jobs is invalid.")
elif self.n_jobs < 0:
self._n_jobs = cpu_count() + 1 + self.n_jobs
else:
self._n_jobs = self.n_jobs
def _init_pretest(self, features, target):
"""Set the sample of data used to verify pipelines work with the passed data set.
"""
raise ValueError("Use TPOTClassifier or TPOTRegressor")
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
"""
self._fit_init()
features, target = self._check_dataset(features, target, sample_weight)
self._init_pretest(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,
test_size=None,
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 not self._pop:
self._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)
# Set lambda_ (offspring size in GP) equal to population_size by default
if not self.offspring_size:
self._lambda = self.population_size
else:
self._lambda = self.offspring_size
# Start the progress bar
if self.max_time_mins:
total_evals = self.population_size
else:
total_evals = self._lambda * self.generations + self.population_size
self._pbar = tqdm(
total=total_evals,
unit="pipeline",
leave=False,
file=self.log_file_,
disable=not (self.verbosity >= 2),
desc="Optimization Progress",
)
try:
with warnings.catch_warnings():
self._setup_memory()
warnings.simplefilter("ignore")
self._pop, _ = eaMuPlusLambda(
population=self._pop,
toolbox=self._toolbox,
mu=self.population_size,
lambda_=self._lambda,
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,
log_file=self.log_file_,
)
# 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.log_file_)
self._pbar.write(
"{}\nTPOT closed prematurely. Will use the current best pipeline.".format(
e
),
file=self.log_file_,
)
finally:
# clean population for the next call if warm_start=False
if not self.warm_start:
self._pop = []
# 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()
else:
if not os.path.isdir(self.memory):
try:
os.makedirs(self.memory)
except:
raise ValueError(
"Could not create directory for memory caching: {}".format(
self.memory
)
)
self._cachedir = self.memory
self._memory = Memory(location=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 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:
# pick one individual from evaluated pipeline for a error message
eval_ind_list = list(self.evaluated_individuals_.keys())
for pipeline, pipeline_scores in zip(
self._pareto_front.items, reversed(self._pareto_front.keys)
):
if np.isinf(pipeline_scores.wvalues[1]):
sklearn_pipeline = self._toolbox.compile(expr=pipeline)
from sklearn.model_selection import cross_val_score
cv_scores = cross_val_score(
sklearn_pipeline,
self.pretest_X,
self.pretest_y,
cv=self.cv,
scoring=self.scoring_function,
verbose=0,
error_score="raise",
)
break
raise RuntimeError(
"There was an error in the TPOT optimization "
"process. This could be because the data was "
"not formatted properly, because a timeout "
"was reached or because data for "
"a regression problem was provided to the "
"TPOTClassifier object. Please make sure you "
"passed the data to TPOT correctly. If you "
"enabled PyTorch estimators, please check "
"the data requirements in the online "
"documentation: "
"https://epistasislab.github.io/tpot/using/"
)
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 (e.g. nan values became a third class), 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