Skip to content

GAFeatureSelectionCV ​

Genetic algorithm wrapper-based feature selection with cross-validation.

GAFeatureSelectionCV selects a subset of columns from the input data using the cross-validation score of the given estimator. The default objective is maximization; set criteria="min" for a loss you supply as a positive value. After fitting, it exposes support_ (a boolean mask of selected features) and behaves as a fitted scikit-learn estimator for prediction.

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 ​

python
import numpy as np
from sklearn_genetic import GAFeatureSelectionCV

GAFeatureSelectionCV(
    estimator,
    cv=3,
    scoring=None,
    max_features=None,
    refit=True,
    verbose=True,
    keep_top_k=1,
    elitism=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,
    preserve_dataframe=False,
    ensemble_sample_weight=False,
)

Parameters ​

ParameterTypeDefaultDescription
optimizer_backendstr or callable, keyword-only"deap"Select "deap", "scipy", "nevergrad", "cmaes", "pymoo" or a plugin. See backend settings and limits and the tutorial.
estimatorestimator—A cloneable estimator with fit, including classifiers, regressors, clusterers and transformers. Supply scoring when it has no default score.
cvint, CV splitter, iterable or None3Cross-validation strategy, including for outlier detection. See explicit fold validation.
scoringstr, callable, list, tuple or dictNoneMetric(s) to evaluate. None uses default scoring. A standalone callable returns one numeric score per fold. Use named scorers for multiple metrics.
refitbool, str or callableTrueRefit the selected mask. With multiple metrics, pass a metric name or a refit function and objective_metric.
objective_metricstr or None, keyword-onlyNoneSearch objective for multiple metrics with refit=False or callable refit
max_featuresint or NoneNoneMaximum number of selected columns per mask. By default all input columns are eligible; a nonempty subset is still required.
return_train_scoreboolFalseInclude training-fold scores in cv_results_.
preserve_dataframebool or "align_named_columns", keyword-onlyFalsePass selected pandas columns with their names and dtypes to the wrapped estimator during search, finalist validation, refit and prediction.
ensemble_sample_weightbool, keyword-onlyFalseAdvertise weighted fitting to ensembles when the template accepts the sample_weight keyword. Exclude zero-weight observations from candidate and finalist folds.
verboseboolTruePrint the generation log
keep_top_kint1Number of hall-of-fame individuals to keep across generations
elitismboolTrueDEAP control for carrying an elite into the next generation
error_scorefloat or "raise"np.nanReplacement score for failed CV folds. With a numeric setting, masks that fail to fit every fold receive NaN and rank last.
random_stateint, RandomState or NoneNoneSeeds the whole search at fit time for reproducible runs. None is non-deterministic
population_initializer"smart", "random" or "spread""smart"Strategy for initial feature masks
evolution_configEvolutionConfigNonePopulation size and generations; variation settings depend on the backend
population_configPopulationConfigNoneInitialization strategy and optional warm-start feature masks
runtime_configRuntimeConfigNoneParallelism, caching, verbosity
optimization_configOptimizationConfigNoneFinalist selection; DEAP-specific local search and fitness sharing

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".

Smart initialization spreads target mask sizes across the allowed range. It samples column indices without replacement, drawing the omitted columns for dense masks. This reduces initialization cost on wide data. Within the same version, set random_state to reproduce the initial masks. If caching is enabled and the population exceeds the number of possible masks, smart initialization reuses duplicate draws to fill the remaining slots with independent individuals.

max_features must be None or an integer from 1 through the number of input columns. Initialisation, crossover and mutation repair masks to keep at least one feature and respect that upper bound.

The built-in initializers prepare masks within these bounds during setup. Random sampling repairs each mask as it is drawn. Smart, spread and warm starts build valid masks directly. DEAP sends those masks directly to the first evaluation batch when the search has no callbacks or uses only the built-in CVBudgetStopping. Custom startup callbacks can change the population before evaluation, so their initial masks go through the usual repair.

Initial mask order under a CV budget ​

GAFeatureSelectionCV accepts population_initializer="spread" or PopulationConfig(initializer="spread"). This uses the same masks drawn by "smart". It evaluates a mask near the middle of the sampled size range first, then takes the remaining mask whose size is farthest from the nearest size already in the order.

Use this option with CVBudgetStopping when the search may stop before evaluating the initial population. Early candidates cover a wider range of subset sizes. The selected mask can have more features, and fitting larger masks can take longer at the same evaluation budget. Compare validation scores, held-out scores and fit time for your estimator and data. See the paired initialization example.

Start from known feature subsets ​

Supply PopulationConfig(warm_start_masks=[previous.get_support()]) to give a new search the Boolean mask from a fitted selector. Keep the same input columns in the same order. Each mask must select at least one column, respect max_features and have one entry per input column.

All five built-in engines evaluate distinct seeds in input order, up to population_size. Entries after the population fills are ignored. Invalid entries encountered during initialization raise ValueError. The initializer fills the remaining slots, and "spread" orders those generated masks by size. A fresh fit scores the seeds on its current CV splits. Use masks chosen independently of the rows used to validate the search. See the warm-start example.

Attributes After fit ​

AttributeDescription
support_Boolean mask — True for selected features
best_index_Row in cv_results_ for the selected mask, including with refit=False when that row is available
best_score_Mean CV objective score of the selected mask. 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 the selected features on the full training data when refitting is enabled
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 refit on the selected columns
refit_failure_time_Elapsed seconds of the full-data refit phase when it raises
classes_Class labels when the selected estimator is a refitted classifier
cv_results_Dict with per-candidate results
history_, historyDictionary of lists aligned by generation. Pair cross_validate_calls with fitness_best_observed for the best finite score from any evaluated mask, or fitness_best for the best archived score.
logbook_, logbookCompatibility view of per-candidate records, materialized on access for shared-runtime engines, in logbook.chapters["parameters"]
hof_, hofHall 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_Evaluation counters
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.
n_features_Number of selected features in support_, available after a search with or without refit
n_features_in_Number of input features before selection
feature_names_in_Feature names seen during fit when X has string column names

See plotting score against evaluation cost to compare runs with different cache-hit rates.

Methods ​

MethodDescription
fit(X, y=None, callbacks=None, groups=None, **fit_params)Run the genetic feature selection
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 feature masks as a pandas DataFrame
fit_predict(X, y=None, **params)Select columns and return training labels in one final refit when the wrapped estimator supports fit_predict.
transform(X)Return X with only the selected features
inverse_transform(X)Restore the original feature count by inserting zeros in removed columns
get_support(indices=False)Return the mask or indices of selected features
get_feature_names_out(input_features=None)Return the selected feature names
predict(X, **params)Predict on selected features with the refitted estimator. For example, mean, std = selector.predict(X, return_std=True) with BayesianRidge. With metadata routing enabled, request return_std on the regressor.
predict_proba(X, **params) / predict_log_proba(X, **params)Return probabilities or log-probabilities from the refitted classifier on the selected columns. With metadata routing enabled, a classifier pipeline can receive preprocessing metadata for the new rows.
decision_function(X, **params)Return decision scores on the selected columns when the refitted estimator supports them. This method forwards inference parameters in the same way as predict_proba.
score_samples(X)Return per-sample scores when the refitted estimator exposes that method
score(X, y=None, *, sample_weight=None, **params)Score the selected features with the configured scorer, the default anomaly scorer, or the search objective for multi-metric scoring. With metadata routing enabled, pass additional parameters requested by that scorer. Requires refitting.

For multilabel classification, a SciPy sparse indicator matrix can supply y to a compatible estimator such as OneVsRestClassifier. Feature selection changes columns of X. All label columns remain available in CSR format during fold fitting, scoring and refit.

Pass y if the estimator or a step in a scikit-learn Pipeline requires a target. The selector raises a ValueError before evaluating masks when a required target is missing. When the estimator accepts an omitted target, call fit(X). Lists, NumPy arrays and pandas DataFrames can supply the feature columns in this mode. CV, refit and score(X) omit the target. See custom scoring without labels.

For multi-output regression or multilabel classification, pass y with shape (n_samples, n_outputs) and choose an estimator that supports that target. The selector applies one feature mask to X and evaluates it against all outputs using a scorer that returns one value per fold. With cv=None or an integer, multi-output regression and multilabel classification use KFold. See the multi-output regression example.

Replacing the estimator or one of its pipeline steps with set_params updates the availability and metadata requests of fit_predict. Until the next fit, best_estimator_ and get_support() describe the previous fit. For example, after replacing a fitted imputation pipeline, you can still pass rows containing missing values to predict and transform using the fitted mask. The next fit establishes the new estimator's input requirements.

For clustering, use labels = selector.fit_predict(X_train) to obtain the labels assigned with the winning feature mask. For a clusterer such as DBSCAN, supply a scorer that evaluates held-out rows. To retrieve the selected input columns, call selector.transform(X_train).

With BaggingClassifier or BaggingRegressor, put the encoder or imputer in the bagging estimator's base pipeline. Each learner fits its preprocessing on its own training samples. Bagging draws its features from the selected columns, preserving their category values and missing entries. For multiple regression targets, use a base regressor that accepts the target matrix, such as a decision tree, with the default oob_score=False. The selector passes all target columns to each training fold and to the final refit.

With AdaBoostRegressor, a base pipeline can encode categorical columns on each round's training rows. For example, OneHotEncoder can distinguish the codes "01" and "1". AdaBoost requires finite input before it fits its base pipeline. To impute missing values, put the imputer before AdaBoost.

A StackingClassifier can receive a dense binary target matrix with one column per label. Choose base classifiers and a final classifier that accept multilabel targets, such as decision trees. The selector preserves the label columns for each training fold and for the final refit. With refit=False, the same target matrix can guide feature selection for a downstream classifier.

TransformedTargetRegressor fits its target transformation on each training fold. The selector preserves the original shape of y, including (n_samples, 1). A target transformer such as PCA(n_components=1) can reduce several outputs for a single-output regressor and restore them at prediction time.

For raw categorical columns, use an estimator that accepts two-dimensional categorical input or a pipeline that starts with a compatible encoder. By default, the search passes each candidate subset to the pipeline as an array of selected columns. See feature selection with OneHotEncoder.

The same input policy applies when the preprocessing pipeline is the base estimator of TransformedTargetRegressor, MultiOutputRegressor, MultiOutputClassifier, OneVsRestClassifier or OutputCodeClassifier. For example, MultiOutputRegressor(make_pipeline(SimpleImputer(), Ridge())) fits its imputers on the selected training columns. A base pipeline starting with OneHotEncoder can receive string categories directly.

Use GridSearchCV, RandomizedSearchCV or GASearchCV as the selector's estimator to tune preprocessing on each candidate feature subset. For example, GridSearchCV(pipe, {"prep": [SimpleImputer()], "model__C": [0.1, 1]}, cv=3) replaces a "passthrough" step named prep and tunes the logistic regression step named model. Each imputer learns from its inner training fold. For named columns, use preserve_dataframe=True with selectors that adapt to each feature subset, or preserve_dataframe="align_named_columns" with fixed names. Inner searches also receive the original number of target columns, including a single column shaped (n_samples, 1). This lets a target transformer or multi-output scorer use the same shape in every fold. The selector also exposes the target requirements of its estimator to scikit-learn. For example, a pipeline ending in GammaRegressor requires positive targets.

For successive halving, import enable_halving_search_cv from sklearn.experimental and use HalvingGridSearchCV or HalvingRandomSearchCV as the selector's estimator. Their candidate pipelines can encode categorical columns or impute missing values on the training rows allocated to each round.

A custom numeric transformer can be the first step in a cached pipeline. It needs the usual cloning, fit and transform methods. When the transformer provides no input tags, the selector accepts finite numeric feature matrices. The pipeline fits its own copy of the transformer on each training fold.

Encoders can distinguish category codes such as "01" and "1". In a fixed numeric pipeline, fitting on an object array of integer IDs preserves values that float64 would round. Object arrays mixing integers and floats use the usual float64 conversion. A pipeline fitted on floating-point data keeps its floating-point dtype when predicting on numeric object arrays. Inspecting a randomized search leaves its custom sampling distributions untouched.

With VotingClassifier and VotingRegressor, each active learner receives the same selected columns. A pipeline with an encoder can distinguish category codes such as "01" and "1" even when another learner converts them to numbers. For missing values, use a compatible estimator or imputation pipeline in every active branch. Learners set to "drop" do not participate.

StackingClassifier and StackingRegressor also pass the selected columns to their base learners. For example, a stack with cv=3 fits its base pipelines inside three training folds and trains the final estimator on their out-of-fold predictions. With passthrough=True, the final estimator also receives the selected columns, preserving category codes for a final encoder. When scikit-learn concatenates numeric predictions with an all-string array, the prediction columns also become strings. Passing the same text rows as a Python list preserves those categories at training and prediction time. An imputer in a base pipeline processes its own input. If the final estimator receives missing values through passthrough, its pipeline must handle them too.

CalibratedClassifierCV, FixedThresholdClassifier and TunedThresholdClassifierCV can also wrap the preprocessing pipeline. For example, CalibratedClassifierCV(make_pipeline(OneHotEncoder(handle_unknown="ignore"), LogisticRegression()), cv=3) fits the encoder inside calibration folds. After refitting, call selector.predict_proba(X_test) with the original columns.

Feature selection requires the original input columns. If the estimator declares a precomputed kernel or distance input, fit raises a ValueError before evaluating masks. See precomputed kernels and distances.

With a sparse-compatible estimator, you can pass a SciPy sparse matrix directly to fit. The selector keeps CSR and CSC training matrices in their original formats and converts other sparse formats, including COO, to CSC before selecting columns. Prediction and scoring keep CSR and CSC inputs in their original formats. They convert other sparse inputs to CSR before selecting columns. Choose the format your wrapped estimator accepts for inference. See the sparse feature selection tutorial. The selector reports the wrapped estimator's sparse input support through scikit-learn's estimator tags, including when it is a step in a pipeline. transform returns CSR for sparse inputs. For large CSC inputs that retain at most half the columns, it validates the entire input and converts only the selected columns to CSR. See the sparse pipeline example. With caching enabled, standard evaluation on sparse inputs with at least 4,096 columns can build an independently writable Boolean mask from the tuple already prepared for the cache lookup. For wide sparse training matrices, see how to compare CSR and CSC at the same CV budget.

With refitting enabled, scikit-learn recognizes the selector as the type of estimator it wraps. For a classifier, an integer cv in external validation uses stratified folds and scorers such as "roc_auc" use the refitted class labels. With refit=False, the selector can be used as a transformer in a pipeline whose final step makes predictions.

For an estimator that advertises allow_nan through scikit-learn's tags, the selector preserves NaN in feature values during fit, transformation, prediction and scoring. The estimator still validates the selected data. For a scikit-learn Pipeline, the selector checks the step that first consumes the raw features, including inside nested pipelines. For example, in make_pipeline(FunctionTransformer(), SimpleImputer(), LogisticRegression()), the imputer receives missing values and learns its statistics in each training fold. A leading FunctionTransformer() likewise passes string categories to a subsequent encoder. Setting validate=True on the transformer applies its own input checks. If the first preprocessing step is a scikit-learn ColumnTransformer, its branches handle missing values in the columns selected for each fold. For example, one branch can use SimpleImputer on nullable numeric columns while another applies PCA to complete measurements. If a branch receives values it cannot handle, candidate evaluation follows error_score. With a FeatureUnion, all active branches receive the same selected columns. For example, make_union(SimpleImputer(), MissingIndicator(features="all")) supplies imputed values and missingness indicators to the estimator. The selector accepts missing values when each branch can receive them. See the sparse example with imputation. Supervised targets must contain valid values. inverse_transform preserves these values in the selected columns and inserts zeros for the removed columns. Sparse inputs produce a CSC result. For CSR and CSC inputs, the selector reconstructs the sparse column index directly. The result follows scikit-learn's configured sparse interface when that setting is available.

set_output(transform="pandas") controls the output of transform. By default, prediction and scoring pass selected columns as an array or sparse matrix. The selector checks string column names and their order before predicting or scoring.

Set preserve_dataframe=True when the wrapped estimator needs pandas column names, dtypes or row indices. Supply a pandas DataFrame at fit and prediction time. The selector validates its shape and column names, and the wrapped estimator validates the selected values. Use a callable column selector when preprocessing must adapt to the columns in each mask. A fixed list of required names can fail in this mode if a candidate drops one of them. See the dtype-based preprocessing example.

Set preserve_dataframe="align_named_columns" to reuse a ColumnTransformer that assigns specific input names to each branch. For every mask, a branch receives its surviving columns in the declared order. A surviving scalar name still gives a one-dimensional input to a text vectorizer. A branch with no surviving columns is skipped. With unique input names, a slice such as slice("age", "income") includes the selected columns from that interval in the original frame, even if the mask drops either endpoint. This applies to closed and open-ended ranges with the default step or a step of one. Misspelled names still raise scikit-learn's column-selection error. This applies to a ColumnTransformer used directly or after pipeline steps that pass the original columns through. For example, a FunctionTransformer(func=None, validate=False) with default or "one-to-one" feature names preserves the input names, including inside a nested pipeline. If an inner search enables a transforming function or a callable that renames the output, downstream selectors use those output names. With a FeatureUnion at the input, each parallel branch can use its own named ColumnTransformer. Later pipeline steps consume the columns produced by the preceding transformations. Callable and positional selectors keep their usual scikit-learn behavior.

An inner GridSearchCV, RandomizedSearchCV, successive halving search or GASearchCV can also tune the preprocessing step. Each inner candidate uses its configured pipeline and the outer feature mask. For example, a search over {"prep": [numeric_preprocessor, mixed_preprocessor]} can use different fixed column lists for the two preprocessors. The inner search keeps the original parameter values in best_params_ and fits its winning best_estimator_ on the selected columns. With a TransformedTargetRegressor, the feature mask applies to its regressor, including replacements such as regressor__prep in a grid. Its target transformer receives every column of y in the training fold. For a complete regression workflow, see select DataFrame columns and tune a pipeline together.

python
from sklearn.compose import make_column_transformer
from sklearn.datasets import load_iris
from sklearn.linear_model import LogisticRegression
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import PolynomialFeatures

from sklearn_genetic import GAFeatureSelectionCV

X, y = load_iris(return_X_y=True, as_frame=True)
prep = make_column_transformer(
    (PolynomialFeatures(include_bias=False), ["petal length (cm)", "petal width (cm)"]),
    remainder="passthrough",
)
search = GAFeatureSelectionCV(
    make_pipeline(prep, LogisticRegression(max_iter=500)),
    preserve_dataframe="align_named_columns",
    population_size=6,
    generations=2,
    random_state=42,
    cv=3,
)
search.fit(X, y)

For positional preprocessing, ColumnTransformer and FeatureUnion can also receive an array of selected values. A categorical code such as "01" reaches an encoder as a string, so a parallel numeric conversion cannot merge it with "1" before the encoder fits. When a list or DataFrame converts to a dense array, the selector keeps integer IDs exact alongside floating-point measurements. This includes DataFrames with a mixture of dense and pandas sparse columns. For example, 2**53 and 2**53 + 1 remain separate categories for OneHotEncoder during cross-validation and prediction. Supply the original integers when constructing the input. Fully sparse numeric DataFrames keep scikit-learn's sparse representation and common numeric dtype.

With preserve_dataframe=True, a pipeline such as make_pipeline(selector, OneHotEncoder()) can consume mixed categorical and nullable pandas columns with the default NumPy output. When a dtype uses pd.NA and the frame includes nonnumeric columns, the selector returns an object array. It also uses object output for dense numeric columns when a floating-point array would round an integer ID. Missing values in nullable columns become np.nan. Choose selector.set_output(transform="pandas") to keep the pandas dtypes and row index.

score(X, y) evaluates the refitted estimator on new data. Read cv_results_["features"][best_index_] to find the selected mask in the search results. Without finalist validation, standard refit and refit=False follow the archived mask and score, including when several rows tie or repeat that mask. When several rows match a finite archived score for the same mask, best_index_ identifies the first matching row. With a custom scorer that includes a feature-count penalty, score(X, y) includes it. Calculate an unpenalized test metric separately when needed.

With a callable refit, final_selection_results_["original_best_index"] identifies the row the standard refit would select when the archived mask is available in the search results. selected_index identifies the callable's choice and changed compares those row indices. See the example that refits the best observed mask.

To use the selector as the base classifier in AdaBoostClassifier, set ensemble_sample_weight=True and wrap a classifier whose fit declares sample_weight, such as DecisionTreeClassifier. Each boosting round passes its weights into feature selection and refit. Candidate and finalist validation use the positive-weight rows. The final refit receives all rows and weights. For metadata-routed bagging with scoring=None, use set_fit_request(sample_weight=True).set_score_request(sample_weight=False) on the tree for weighted fits and unweighted validation, or request weights in both methods. See the AdaBoost example and out-of-bag scoring considerations.

Pass sample_weight to score to weight the evaluation rows when the selected scorer accepts it. With metadata routing enabled, request an alias such as selector.set_score_request(sample_weight="outer_weight"). Then cross_val_score(selector, X, y, scoring=None, params={"outer_weight": weights}) passes the weights for each outer validation fold. When sharing a metadata name across fit and score, set each estimator and scorer request explicitly. For a metric that accepts a per-row penalty, configure the scorer with set_score_request(penalty="cost") and evaluate held-out rows with selector.score(X_test, y_test, cost=test_costs). In a multi-metric search the held-out evaluation uses the selected objective's requests. A separate weight alias configured on the scorer still applies to the inner folds. For the search itself, fit can receive separate weights for estimator fitting and scoring. Pipelines also forward those requests to the selector when they call fit or fit_transform.

With metadata routing enabled, a wrapped estimator or scorer can request the groups for the rows it fits or scores, including when both selection stages use an explicit KFold or a custom split(X, y). Groups also reach the selector when its search splitter or active finalist splitter requests them. For example, an outer GroupKFold can consume params={"groups": groups} while a pipeline's GAFeatureSelectionCV(cv=3) uses ordinary inner folds. An explicit set_fit_request(groups=None) makes the selector reject routed group labels. Use GroupKFold.set_split_request on each splitter to supply different group labels for search and finalist folds. Finalist validation runs when refitting and final_selection are enabled. See grouped finalist validation for an example.

cv_results_dataframe() uses the selected refit or objective_metric for multi-metric searches and keeps evaluation order for tied ranks. Its params column contains each candidate's feature mask. It leaves cv_results_ unchanged and also works after a fit with refit=False. In long histories with frequent cache reuse, the exporter can convert a shared Boolean mask once. Each params row still has its own editable list. The Boolean column all_fits_failed identifies masks 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 mask fails, even though fit raises. If evaluation skips an empty mask or one outside max_features, cv_results_["skipped_invalid_mask"] identifies the skipped rows. Their CV scores are NaN and they are ineligible for finalist selection and refit. The search raises with the diagnostics available when every mask is skipped. When at least one mask was evaluated, the search raises if every evaluated mask failed to fit every fold. The two Boolean columns distinguish skipped masks from failed evaluations. Use cv_results_["n_features"] for the size of each evaluated mask. rank_n_features is one plus the number of candidate rows with fewer selected features. Rows with the same size share the same rank. For long histories with a bounded range of sizes, the selector computes these ranks by counting rows at each size. When cached rows share a Boolean mask, the selector can count its selected features once. Every completed proposal has its own row and contributes to the ranks.

Pass columns as a name or a list of names to build only those columns, in the requested order. Sorting still uses the selected test rank, and unknown column names raise KeyError. For wide data, request columns such as n_features and mean_test_score to inspect subset sizes and scores without converting each mask into a list for params.

Pass a positive integer as top_k for a ranked shortlist. Tied rows retain their evaluation order at the cutoff. For a short list from a long history, the exporter can sort only the leading rows. If you request params, the selector converts only the masks in the returned rows.

With preserve_index=True, the sorted table uses positions in cv_results_ as labels in the candidate_index index. When best_index_ is available, retrieve the selected row with selector.cv_results_dataframe(preserve_index=True).loc[selector.best_index_].

To inspect a search without refitting, set refit=False. Read support_ for the mask and best_score_ for its CV objective score. For multiple scorers, set objective_metric to the one you want to optimize.

get_support(), transform(), inverse_transform() and get_feature_names_out() work after any successful fit. The selector's prediction and scoring methods require its refitted estimator.

Example ​

python
import numpy as np
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.svm import SVC

from sklearn_genetic import EvolutionConfig, GAFeatureSelectionCV

X, y = load_iris(return_X_y=True)
rng = np.random.default_rng(42)
noise = rng.uniform(0, 10, size=(X.shape[0], 10))
X = np.hstack((X, noise))

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.33, random_state=0)

selector = GAFeatureSelectionCV(
    estimator=SVC(gamma="auto"),
    cv=3,
    scoring="accuracy",
    evolution_config=EvolutionConfig(population_size=6, generations=2),
    random_state=42,
)

selector.fit(X_train, y_train)

print("Selected features:", selector.support_)
print("Number of selected features:", selector.n_features_)
print("Search CV evaluations:", selector.history["cross_validate_calls"])
print("Selected mask's search row:", selector.best_index_)
print("Selected mask's CV accuracy:", round(selector.best_score_, 4))
print("Test accuracy:", round(selector.score(X_test, y_test), 4))
print(selector.cv_results_dataframe(columns=["n_features", "mean_test_score"], top_k=5))

Use external validation data for early stopping ​

With scikit-learn 1.7 or later, a histogram gradient boosting model can use a separate validation set for early stopping. Enable metadata routing and list X_val in the wrapped pipeline's transform_input. Pass all original columns to the selector. Each candidate and finalist uses its own feature mask on the validation matrix, then transforms it with preprocessing fitted on that fold's training rows. The final refit uses the winning mask. The same rule applies when GridSearchCV, RandomizedSearchCV or GASearchCV fits the pipeline. The search can also set transform_input in its parameter space. If a scorer uses the same external alias, it receives its original matrix while the pipeline receives the columns declared for transformation.

python
from sklearn import config_context
from sklearn.datasets import load_iris
from sklearn.ensemble import HistGradientBoostingClassifier
from sklearn.model_selection import train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn_genetic import GAFeatureSelectionCV

X, y = load_iris(return_X_y=True)
train, test, target, test_y = train_test_split(X, y, stratify=y, random_state=11)
train, validation, target, validation_y = train_test_split(
    train, target, test_size=0.2, stratify=target, random_state=12
)
with config_context(enable_metadata_routing=True):
    model = HistGradientBoostingClassifier(
        early_stopping=True, max_iter=30, random_state=11
    ).set_fit_request(X_val=True, y_val=True)
    pipeline = make_pipeline(StandardScaler(), model, transform_input=["X_val"])
    selector = GAFeatureSelectionCV(
        pipeline, cv=2, population_size=4, generations=0, max_features=2,
        n_jobs=1, random_state=11, verbose=False,
    ).fit(train, target, X_val=validation, y_val=validation_y)

print(selector.score(test, test_y))

The same feature selection applies to other two-dimensional inputs named in Pipeline.transform_input starting with scikit-learn 1.6. If a step requests a validation matrix under an alias, put the step's parameter name in transform_input and pass the alias to fit. Other recipients of the alias keep their original metadata. Scikit-learn applies its usual fold row slicing to fit parameters whose length matches the training set.

Select columns for clustering ​

Use a metric that compares feature subsets on held-out rows. This example scores the separation of three clusters using the labels predicted by a KMeans fitted on each training fold. Each validation fold must have at least two predicted clusters and more observations than predicted clusters.

python
from sklearn.cluster import KMeans
from sklearn.datasets import make_blobs
from sklearn.metrics import silhouette_score
from sklearn.model_selection import train_test_split
from sklearn_genetic import GAFeatureSelectionCV

X, _ = make_blobs(
    n_samples=150,
    centers=[[-4, -4, -4], [0, 0, 0], [4, 4, 4]],
    cluster_std=0.5,
    random_state=17,
)
train, test = train_test_split(X, random_state=17)


def cluster_separation(estimator, X, y=None):
    return silhouette_score(X, estimator.predict(X))


selector = GAFeatureSelectionCV(
    KMeans(n_clusters=3, n_init=5, random_state=17),
    scoring=cluster_separation,
    cv=3,
    population_size=6,
    generations=1,
    random_state=17,
    n_jobs=1,
    verbose=False,
).fit(train)

print(selector.get_support(indices=True))
print(selector.score(test))

With scoring=None, KMeans.score returns the negative sum of squared distances to the fitted cluster centers. Its magnitude depends on the feature scales and the number of selected columns. A transformer can use a callable scorer in the same way. When the scorer needs targets, pass y to fit and score. The selector slices sample-aligned targets by fold and preserves the output columns of a matrix target.

selector.transform(test) returns the selected input columns. To obtain distances to the cluster centers, call selector.best_estimator_.transform(selector.transform(test)).

Use the selector in a pipeline without refitting ​

Set refit=False when the next pipeline step trains the final predictor. The selector uses cross-validation to choose the columns. The final step fits on those columns from the full training set. With the selector as its last step, the pipeline exposes transform. You can also call get_feature_names_out when the preceding steps supply feature names. Add a classifier or regressor after the selector to call predict and score on that pipeline.

For repeated observations, use a splitter such as GroupKFold to keep each group together during feature selection. With metadata routing enabled, pass groups to pipeline.fit when the selector's cv requests them. See the nested grouped pipeline example. A custom split(X, y) method can supply folds for one stage when the other active splitter accepts groups. See the custom finalist splitter example.

python
from sklearn.datasets import load_iris
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.tree import DecisionTreeClassifier

from sklearn_genetic import GAFeatureSelectionCV

X, y = load_iris(return_X_y=True, as_frame=True)
X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.25, stratify=y, random_state=42
)
selector = GAFeatureSelectionCV(
    DecisionTreeClassifier(random_state=42),
    scoring="accuracy",
    cv=3,
    population_size=6,
    generations=2,
    refit=False,
    n_jobs=1,
    random_state=42,
    verbose=False,
).set_output(transform="pandas")
pipeline = make_pipeline(selector, LogisticRegression(max_iter=500)).fit(X_train, y_train)
print(selector.get_feature_names_out())
print(selector.fit_counts_["refit_fits"])  # 0
print(pipeline.score(X_test, y_test))

See Also ​

Released under the MIT License.