'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 training data.
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 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
self: object
Returns a copy of the fitted TPOT object'

def fit(self, features, target, sample_weight=None, groups=None):

    features = features.astype(np.float64)
    self._fitted_imputer = None
    if np.any(np.isnan(features)):
        features = self._impute_values(features)
    self._check_dataset(features, target)
    if (self.subsample < 1.0):
        (features, _, target, _) = train_test_split(features, target, train_size=self.subsample, random_state=self.random_state)
        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.')
    if (self.random_state is not None):
        random.seed(self.random_state)
        np.random.seed(self.random_state)
    self._start_datetime = datetime.now()
    self._toolbox.register('evaluate', self._evaluate_individuals, features=features, target=target, sample_weight=sample_weight, groups=groups)
    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.\n\n                                                Parameters\n                                                ----------\n                                                ind1:    DEAP    individual    from    the    GP    population\n                                                                First    individual    to    compare\n                                                ind2:    DEAP    individual    from    the    GP    population\n                                                                Second    individual    to    compare\n\n                                                Returns\n                                                ----------\n                                                individuals_equal:    bool\n                                                                Boolean    indicating    whether    the    two    individuals    are    equal    on\n                                                                the    Pareto    front\n\n                                                '
        return np.allclose(ind1.fitness.values, ind2.fitness.values)
    if ((not self.warm_start) or (not self._pareto_front)):
        self._pareto_front = tools.ParetoFront(similar=pareto_eq)
    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():
            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, max_time_mins=self.max_time_mins)
        if self.warm_start:
            self._pop = pop
    except (KeyboardInterrupt, SystemExit):
        if (self.verbosity > 0):
            self._pbar.write('')
            self._pbar.write('TPOT    closed    prematurely.    Will    use    the    current    best    pipeline.')
    finally:
        attempts = 10
        for attempt in range(attempts):
            try:
                if (not isinstance(self._pbar, type(None))):
                    self._pbar.close()
                if self._pareto_front:
                    self._update_top_pipeline()
                    if (not self._optimized_pipeline):
                        print('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]):
                            if (self.verbosity >= 2):
                                print('')
                            print('Best    pipeline:    {}'.format(self._optimized_pipeline))
                        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)
                break
            except (KeyboardInterrupt, SystemExit, Exception) as e:
                if (attempt == (attempts - 1)):
                    raise
        return self
