Tune Pipelines on Selected DataFrame Columns
Use this recipe when the best hyperparameters may depend on which columns survive. The outer search proposes feature subsets. For each subset, an inner grid search chooses a scaler and a ridge penalty. Keep pandas installed and use the development version that provides preserve_dataframe="align_named_columns".
Reserve an evaluation set
The scikit-learn diabetes dataset includes a coded categorical column, sex. Load the unscaled measurements so that each scaler learns its parameters inside the pipeline. Keep the holdout rows out of both searches.
from sklearn.compose import ColumnTransformer
from sklearn.datasets import load_diabetes
from sklearn.linear_model import Ridge
from sklearn.metrics import mean_absolute_error
from sklearn.model_selection import GridSearchCV, KFold, train_test_split
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import OneHotEncoder, RobustScaler, StandardScaler
from sklearn_genetic import GAFeatureSelectionCV
X, y = load_diabetes(return_X_y=True, as_frame=True, scaled=False)
numeric = ["age", "bmi", "bp", "s5"]
X = X[numeric + ["sex"]].astype({"sex": "category"})
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=11)Tune preprocessing for each feature subset
Each scaler gets the surviving numeric columns. If the mask keeps sex, the encoder learns its categories from the inner training fold. If the mask drops it, the categorical branch is skipped. The three outer folds evaluate the fitted inner search on rows it did not use to choose its hyperparameters.
def preprocessing(scaler):
return ColumnTransformer([
("numeric", scaler, numeric),
("category", OneHotEncoder(handle_unknown="ignore", sparse_output=False), ["sex"]),
])
pipeline = Pipeline([("prep", "passthrough"), ("ridge", Ridge())])
inner = GridSearchCV(
pipeline,
{
"prep": [preprocessing(StandardScaler()), preprocessing(RobustScaler())],
"ridge__alpha": [1.0, 10.0],
},
scoring="neg_mean_absolute_error",
cv=KFold(2, shuffle=True, random_state=11),
n_jobs=1,
error_score="raise",
)
selector = GAFeatureSelectionCV(
inner,
preserve_dataframe="align_named_columns",
max_features=3,
population_size=5,
generations=1,
cv=KFold(3, shuffle=True, random_state=12),
scoring="neg_mean_absolute_error",
n_jobs=1,
random_state=13,
verbose=False,
error_score="raise",
)
selector.fit(X_train, y_train)
print("Selected input columns", selector.get_feature_names_out().tolist())Selected input columns ['bmi', 'bp', 's5']Inspect the winner and predict
Pass the full holdout frame to selector.predict. It applies the winning mask before calling the refitted inner search. The selector reports original input names. The fitted preprocessor reports the model inputs after scaling and one-hot encoding.
winner = selector.best_estimator_
fitted_prep = winner.best_estimator_.named_steps["prep"]
print("Ridge inputs", fitted_prep.get_feature_names_out().tolist())
print("Ridge alpha", winner.best_params_["ridge__alpha"])
print("Holdout MAE", round(mean_absolute_error(y_test, selector.predict(X_test)), 2))Ridge inputs ['numeric__bmi', 'numeric__bp', 'numeric__s5']
Ridge alpha 10.0
Holdout MAE 47.5Each mask requires several inner fits in every outer fold. The selector repeats the inner search on all training rows for the winning mask. The holdout MAE evaluates the resulting model on the reserved rows. For a two-stage workflow, see select features, then tune. For an estimator that chooses columns by dtype, see categorical feature selection.
Transform the target inside each training fold
The diabetes target is positive. To fit ridge regression on its log scale, wrap the pipeline in a TransformedTargetRegressor and prefix the grid keys with regressor__. The column mask still applies to the inputs of each preprocessing candidate. Both searches score inverse-transformed predictions in the original target units. This variant uses only the training split.
import numpy as np
from sklearn.base import clone
from sklearn.compose import TransformedTargetRegressor
log_inner = clone(inner).set_params(
estimator=TransformedTargetRegressor(
regressor=pipeline, func=np.log, inverse_func=np.exp
),
param_grid={f"regressor__{key}": values for key, values in inner.param_grid.items()},
)
log_selector = clone(selector).set_params(estimator=log_inner).fit(X_train, y_train)
print("Selected input columns for log target", log_selector.get_feature_names_out().tolist())Selected input columns for log target ['bmi', 'bp', 's5']