GASearchCV
Genetic algorithm hyperparameter search for scikit-learn estimators.
GASearchCV implements the scikit-learn estimator interface and follows the same patterns as GridSearchCV and RandomizedSearchCV. After a successful search, inspect best_params_ and cv_results_. With refitting enabled, use score and the prediction methods supported by the wrapped estimator.
An unfitted clone can be used as a fresh pipeline step. The search creates its fitness cache and constant probability schedules when fitting or when you first access the corresponding runtime attributes.
Common constructor arguments
import numpy as np
from sklearn_genetic import GASearchCV
GASearchCV(
estimator,
cv=3,
param_grid=param_grid,
scoring=None,
refit=True,
verbose=True,
error_score=np.nan,
return_train_score=False,
random_state=None,
evolution_config=None,
population_config=None,
runtime_config=None,
optimization_config=None,
optimizer_backend="deap",
objective_metric=None,
ensemble_sample_weight=False,
)Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
optimizer_backend | str or callable, keyword-only | "deap" | Select "deap", "scipy", "nevergrad", "cmaes", "pymoo" or a plugin. See backend settings and limits and the tutorial. |
estimator | estimator | — | A scikit-learn estimator with a fit method |
param_grid | dict | — | Mapping from parameter name to Integer, Continuous, or Categorical |
scoring | str, callable, list, tuple or dict | None | Metric(s) to evaluate. None uses default scoring. A standalone callable returns one numeric score per fold. Use named scorers for multiple metrics. |
cv | int, CV splitter, iterable or None | 3 | Cross-validation strategy, including for outlier detection. See explicit fold validation. |
refit | bool, str or callable | True | Refit the selected candidate. With multiple metrics, pass a metric name or a refit function and objective_metric. |
objective_metric | str or None, keyword-only | None | Search objective for multiple metrics with refit=False or callable refit |
ensemble_sample_weight | bool, keyword-only | False | Advertise weighted fitting to ensembles when the template accepts the sample_weight keyword. Exclude zero-weight observations from candidate and finalist folds. |
verbose | bool | True | Print the generation log |
error_score | float or "raise" | np.nan | Replacement score for failed CV folds. With a numeric setting, candidates that fail to fit every fold receive NaN and rank last. |
return_train_score | bool | False | Include training scores in cv_results_ |
random_state | int, RandomState or None | None | Seeds the whole search (population init, mutation, crossover, immigrants) at fit time for reproducible runs. None is non-deterministic |
evolution_config | EvolutionConfig | None | Controls population size, generations, crossover/mutation rates, elitism |
population_config | PopulationConfig | None | Controls initialization strategy, warm starts, diversity |
runtime_config | RuntimeConfig | None | Controls parallelism, caching, verbosity |
optimization_config | OptimizationConfig | None | Finalist selection; DEAP-specific local search and fitness sharing |
Under the default DEAP engine, standard mutation excludes numeric dimensions with equal bounds and single-choice categorical dimensions. GASearchCV chooses uniformly among the remaining dimensions and draws from the chosen distribution. A discrete draw may still repeat the parent value. With caching enabled, fewer repeated proposals can increase the number of distinct models fitted in a generation.
Set OptimizationConfig(offspring_diversity_retries=2) to let a mutation try up to two other variable parameters if the first draw copies the parent or produces a cached configuration. Each attempt samples a different parameter from its declared distribution, starting from the same parent. The child changes at most one parameter. If all attempts repeat, a previously evaluated change can still be returned. Repeated values remain possible in a single-parameter search. With caching disabled, the operator can detect a copy of the parent but has no score history to consult. DEAP separately checks the resulting offspring against parents and siblings before evaluation.
With positive retries and caching, DEAP's eaMuPlusLambda and eaMuCommaLambda also reuse the two children of a multi-parameter uniform crossover. These algorithms retain one child per mating. If the first child's configuration already has a cached score and the second child's configuration is new, the search retains the second child. This takes no extra random draws. The usual duplicate checks still apply within the generation.
Local refinement (local_search=True) uses the same variable dimensions when choosing a neighbor of an elite candidate. Each step proposes one neighbor per selected elite. Clipping and previously visited configurations can reduce the number of distinct evaluations.
With algorithm="eaDifferentialEvolution", binomial crossover always takes one coordinate from the donor trial, even when crossover_probability=0. If the grid has any variable dimensions, the algorithm chooses this coordinate among them. A trial can still match its parent after rounding, clipping, or drawing the same categorical value.
Search correctness
Each fresh fit recomputes candidate scores for the supplied data and scoring settings. Caching avoids repeated evaluations within that fit; explicit checkpoint resumes retain saved evaluations. With DEAP, both elitist and non-elitist tournament selection support signed scores, so negative scores and criteria="min" remain meaningful. Scikit-learn's negative loss scorers normally use the default criteria="max".
Final selection's top_k counts distinct parameter configurations, even when the candidate log contains repeated cache hits. Among candidates with the same search rank, the shortlist promotes distinct configurations in evaluation order.
You can pass a search to scikit-learn's RFE or SelectFromModel. For a decision tree, set importance_getter="best_estimator_.feature_importances_". These selectors accept missing values when the search wraps a compatible tree or tunes a pipeline that imputes its inputs. Pipeline importances must correspond to the original columns used by the outer selector.
Scikit-learn can inspect the target requirements of your estimator before fitting the search. For example, a pipeline ending in MultiOutputRegressor expects a two-dimensional target even for one output. A pipeline ending in GammaRegressor requires positive targets.
Attributes After fit
| Attribute | Description |
|---|---|
best_index_ | Row in cv_results_ for the selected candidate, including with refit=False |
best_params_ | Parameters from the selected candidate row |
best_score_ | Mean CV objective score for the selected candidate. Uses the finalist score when finalist validation runs and retains extended NumPy precision when available. Not set with callable refit; use the objective column of the row at best_index_. |
best_estimator_ | Estimator fitted with best_params_ on the full training data after a successful refit |
feature_names_in_ | Input column names in training order, available when the refitted estimator records them. For a pipeline, these are the names before preprocessing. |
search_time_ | Elapsed search seconds until the optimizer returned or raised |
search_interrupted_ | Whether the optimizer raised and its recorded search work is a lower bound |
refit_time_ | Elapsed seconds of the successful full-data refit |
refit_failure_time_ | Elapsed seconds of the full-data refit phase when it raises |
cv_results_ | Dict with per-candidate results, compatible with pd.DataFrame |
history_, history | Dictionary of lists aligned by generation. Pair cross_validate_calls with fitness_best_observed for the best finite score evaluated so far (including discarded candidates), or fitness_best for the best archived score. |
logbook_, logbook | Compatibility view of per-candidate records, materialized on access for shared-runtime engines, in logbook.chapters["parameters"] |
hof_, hof | Hall of fame containing the retained candidates from this fit. |
metrics_list_ | Names of the scoring metrics evaluated during the search. |
refit_metric_ | Metric used to rank candidates for the configured objective. |
fit_stats_ | Dict with evaluation counters (cache hits, skipped candidates, etc.) |
fit_counts_ | Fresh fits and reused finalist folds by phase in the most recent call to fit |
search_space_exhausted_ | Whether the engine detected full coverage of a finite space with caching enabled. See backend stopping rules. |
See plotting score against evaluation cost to compare runs with different cache-hit rates.
Methods
| Method | Description |
|---|---|
fit(X, y=None, callbacks=None, groups=None, **fit_params) | Run the genetic search |
set_callbacks(*callbacks) | Register native scikit-learn fit observers on scikit-learn 1.9 or later. |
cv_results_dataframe(*, preserve_index=False, columns=None, top_k=None) | Return ranked candidates as a pandas DataFrame |
predict(X, **params) | Predict using best_estimator_. For example, mean, std = search.predict(X, return_std=True) with BayesianRidge. With metadata routing enabled, request the parameter on the regressor using set_predict_request(return_std=True). |
fit_predict(X, y=None, **params) | Return training labels from the winner's single full-data refit. Available with refitting enabled when the estimator implements fit_predict. |
fit_transform(X, y=None, **params) | Run the search and obtain the training representation from the winner in one refit. Available when the search supports transform. |
transform(X, **params) | Transform new rows with the refitted winner. With metadata routing enabled, a containing pipeline can pass parameters requested by the winning transformer. |
inverse_transform(X, **params) | Reconstruct inputs with the refitted transformer when it supports that operation. For example, use search.inverse_transform(values, copy=False) with a searched StandardScaler. In a metadata-routed pipeline, configure this option with set_inverse_transform_request(copy=True) on the scaler. |
set_output(*, transform=None) | Configure a wrapped estimator that supports set_output with refitting enabled. Pass "pandas", "polars" or "default". Omitting the argument keeps its current setting. |
get_feature_names_out(input_features=None) | Return output column names from the refitted estimator if it implements this method. ColumnTransformer uses these names when combining branches. |
predict_proba(X, **params) / predict_log_proba(X, **params) | Return probabilities or log-probabilities in the refitted classifier's class order. With metadata routing enabled, a classifier pipeline can receive metadata requested by its preprocessing steps for the new rows. |
decision_function(X, **params) | Return decision scores when the refitted estimator supports them. This method forwards inference parameters in the same way as predict_proba. |
score(X, y=None, **params) | Evaluate the refitted estimator using the configured scorer, or the search objective with multiple scorers. Scorer metadata requires metadata routing. |
get_params() / set_params() | Standard sklearn estimator interface |
With multiple scorers and metadata routing enabled, fit accepts metadata for all candidate scores. On held-out rows, score accepts the requests of the named refit metric or, with callable refit, the metric named by objective_metric. For example, if that scorer uses set_score_request(sample_weight="importance"), call search.score(X_test, y_test, importance=test_weights). Changing scoring with set_params takes effect on the next fit. Until then, the fitted scorers keep their metadata requests.
Pass y if the estimator or a step in a scikit-learn Pipeline requires a target. If the search space replaces pipeline steps, the configured candidates determine whether labels are required. For example, a grid that replaces model=Ridge() with PCA(n_components=2) allows fit(X). CV, refit and score(X) then omit the target. If every candidate requires labels, the search raises a ValueError before evaluating candidates. In a mixed search, a supervised candidate that fails without labels follows the usual error_score setting. See custom scoring without labels.
After set_params(estimator=...) or a change to an estimator__... parameter, the configured estimator determines whether fit_predict and fit_transform are available on the search and which training metadata they accept. Prediction on new rows uses the most recent fitted winner until the next fit. When switching from a transformer to a classifier, call pipeline.fit(X, y) to train the classifier.
For clustering, call pipeline.fit_predict(X_train) when the final step is a GASearchCV wrapping an estimator such as KMeans or DBSCAN. Each candidate still trains on its training fold and is scored on the validation fold. For estimators such as DBSCAN that lack a default score, supply a scorer that can evaluate held-out rows. The winning estimator assigns labels to the full training set during refit.
Use fit_transform(X_train, y_train) to train downstream steps on the cross-fitted encodings produced by TargetEncoder. A scikit-learn Pipeline or ColumnTransformer calls this method for its training rows. Use transform(X_test) on new samples to apply the encoder fitted on the full training set. The search forwards metadata requested for the training transformation to the winner and evaluates candidates on their validation folds.
To get a DataFrame from a ColumnTransformer with a searched transformer branch, call column_transformer.set_output(transform="pandas"). The search configures each candidate after applying its parameters, so replacement preprocessing steps also produce DataFrames before downstream steps fit. For a searched classification or regression pipeline, call search.set_output(transform="pandas") to give its final estimator named columns. The original estimator and objects supplied through the parameter grid can be reused independently. Calling set_output after fitting updates the winner immediately.
For transformation metadata in a ColumnTransformer branch, configure the same alias on the original transformer and its possible replacements. Scikit-learn 1.5.0 and 1.9.1 inspect the original branch to decide which keywords to forward. For example, configure the scalers with set_transform_request(copy="copy_input") before calling columns.transform(X_new, copy_input=True) with routing enabled.
Use a dense transformer for pandas or Polars output. Polars 1.44.2 works with scikit-learn 1.5.0. That version of ColumnTransformer rejects Polars 2.2.0 frames even for native transformers. Polars 2.2.0 works with scikit-learn 1.9.1. Resume a search checkpoint with the same explicit output setting used when it was saved.
For multilabel classification with OneVsRestClassifier, you can pass a SciPy sparse indicator matrix as y. As in GridSearchCV, the search uses CSR rows for splitters, fold fitting, scoring and refitting. Use a metric that supports multilabel targets, such as scoring="accuracy" for exact label-set accuracy.
For an estimator that declares a precomputed kernel or distance input, pass the square matrix over training samples to fit. For predictions, pass the matrix whose rows are new samples and whose columns are the training samples in their original order. See the precomputed SVC example.
With metadata routing enabled, fit can receive separate weights for estimator fitting and scoring. For a weighted ensemble, set ensemble_sample_weight=True and wrap an estimator whose fit declares sample_weight, such as DecisionTreeClassifier. For example, AdaBoostClassifier(estimator=search).fit(X, y, sample_weight=weights) passes each round's weights into the search. CV splitters see the positive-weight rows once each. Precomputed folds keep their original row indices, with zero-weight rows removed. Each fit receives its training weights. Validation weighting follows the scorer's metadata requests, and the final refit receives the full weight vector. With metadata routing enabled and scoring=None, configure the tree with set_fit_request(sample_weight=True).set_score_request(sample_weight=False) for weighted fits and unweighted validation, or request weights in both methods. See the AdaBoost example and out-of-bag scoring considerations. After refitting with scoring=None, pipeline.score uses the winning estimator's metadata requests. For example, if the search replaces a pipeline regressor with one configured using set_score_request(sample_weight=True), pass the evaluation weights with pipeline.score(X_test, y_test, sample_weight=test_weights). For unlabeled detectors with scoring=None, a pipeline can route training weights to the detector. For example, configure OneClassSVM().set_fit_request(sample_weight="training_weight") and call pipeline.fit(X_train, training_weight=weights). Each fold fits the detector with its training weights and evaluates the default anomaly score on its validation rows. After refit, call pipeline.score(X_test) for the mean score or pipeline.score(X_test, sample_weight=test_weights) for a weighted mean over the held-out samples.
Pass groups through a pipeline or outer cross-validation when the wrapped estimator, scorer, search splitter or active finalist splitter requests group labels. For example, cv=3, final_selection=True, final_selection_cv=GroupKFold(4) uses ordinary search folds and keeps groups together during finalist validation. Use set_fit_request(groups="inner_groups") to supply labels to the inner splitters while the outer splitter receives its own labels through groups. Set groups aliases on the individual splitters when candidates and finalists need different group labels. See group labels in nested validation. A custom split(X, y) method can supply folds for one stage when the other active splitter accepts groups. With metadata routing enabled, both stages can also use ungrouped splitters while a nested estimator or scorer receives the group labels.
After set_params(param_grid=new_space), the next fit validates and uses new_space, including changed parameter names. An explicit checkpoint resume restores the saved search space.
Each evaluation configures a cloned estimator. Immutable scalar parameters can be passed directly. Mutable choices, including dictionaries and estimator-valued pipeline steps, follow scikit-learn's cloning rules before configuration. A grid can contain one parameter, including a pipeline step with preconfigured estimator choices.
cv_results_["params"] and the param_* columns retain the values passed to the estimator, including names shared with diagnostics. Parameter columns and each params dictionary follow the order of param_grid. Each completed proposal has its own dictionary, including proposals with cached scores. For an estimator parameter named fit_time, read param_fit_time for the parameter and mean_fit_time for the measured fold time. See the example with overlapping names.
cv_results_dataframe() uses the selected refit or objective_metric for multi-metric searches and keeps evaluation order for tied ranks. It leaves cv_results_ unchanged and also works after a fit with refit=False. The Boolean column all_fits_failed identifies candidates whose estimator failed to fit every search fold. See the CV troubleshooting guide. With numeric error_score, the table and history remain available when every candidate fails, even though fit raises. Pass columns as a name or a list of names to build only those columns, in the requested order. The table stays sorted by the same test rank even when the rank column is omitted. Unknown column names raise KeyError.
Pass a positive integer as top_k to return up to that many rows. Tied candidates retain their evaluation order at the cutoff. For a short list from a long history, the exporter can select a rank cutoff and sort only the leading rows.
With preserve_index=True, the sorted table uses positions in cv_results_ as labels in the candidate_index index. Retrieve the selected row with search.cv_results_dataframe(preserve_index=True).loc[search.best_index_].
To inspect a search without refitting, set refit=False. Read the selected row, parameters and CV objective score through best_index_, best_params_ and best_score_. For multiple scorers, set objective_metric to the one you want to optimize.
Example
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier
from sklearn_genetic import EvolutionConfig, GASearchCV
from sklearn_genetic.space import Categorical, Integer
X, y = load_breast_cancer(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.25, stratify=y, random_state=42
)
search = GASearchCV(
estimator=DecisionTreeClassifier(random_state=42),
param_grid={
"max_depth": Integer(2, 12),
"criterion": Categorical(["gini", "entropy"]),
},
cv=3,
scoring="roc_auc",
evolution_config=EvolutionConfig(population_size=6, generations=2),
random_state=42,
)
search.fit(X_train, y_train)
print("Selected parameters", search.best_params_)
print("Search CV evaluations", search.history["cross_validate_calls"])
print("Held-out ROC AUC", search.score(X_test, y_test))
print(search.cv_results_dataframe(columns=["params", "mean_test_score"], top_k=5))Tune a preprocessing step
A search around PCA can act as a transformer in a regression pipeline. The inner search compares component counts using PCA's held-out log likelihood. The outer cross-validation measures the regression pipeline on separate rows.
from sklearn.datasets import load_diabetes
from sklearn.decomposition import PCA
from sklearn.linear_model import Ridge
from sklearn.model_selection import cross_val_score
from sklearn.pipeline import make_pipeline
from sklearn_genetic import GASearchCV
from sklearn_genetic.space import Integer
X, y = load_diabetes(return_X_y=True)
reduce = GASearchCV(
PCA(), param_grid={"n_components": Integer(2, 6)}, cv=3,
population_size=4, generations=1, random_state=17, n_jobs=1, verbose=False,
)
pipeline = make_pipeline(reduce, Ridge())
scores = cross_val_score(pipeline, X, y, cv=3, scoring="r2")For a transformer without a score method, pass a scoring callable that evaluates the fitted transformer on validation data. An unlabeled search calls the scorer with (estimator, X). A search with targets passes (estimator, X, y). To choose preprocessing parameters by the final regressor's score, wrap the whole regression pipeline in GASearchCV and use step-prefixed parameter names.
See Also
- Basic Usage — step-by-step tutorial
- Config Objects —
EvolutionConfig,PopulationConfig,RuntimeConfig,OptimizationConfig - Search Space —
Integer,Continuous,Categorical - GAFeatureSelectionCV — feature selection variant