Sub topic 14
Selecting features: filter, wrapper and embedded methods
This chapter assumes you can build a scikit-learn Pipeline with a ColumnTransformer and run cross_val_score, as covered in earlier chapters. It also assumes you know why fitting any step on validation data causes leakage.
Why select features
Feature selection removes columns that add noise, cost or redundancy. Fewer features can mean faster training, simpler models and less overfitting, especially when you have many columns and few rows. Selection does not always raise the score. Treat it as an experiment and measure it.
Selection looks at the target, so it is a fitted step. If you pick features using the whole dataset and then cross-validate, the validation folds have already influenced your choice. The score will be too optimistic.
Three families of methods
| Family | How it works | Cost | Main risk |
|---|---|---|---|
| Filter | Scores each feature with a statistic, such as correlation or mutual information | Low | Ignores interactions between features |
| Wrapper | Searches subsets by repeatedly fitting a model, such as recursive feature elimination | High | Slow, and can overfit the validation data |
| Embedded | The model's own training yields importances or zero coefficients | Medium | Depends on the chosen model |
Filter methods
SelectKBest keeps the k features with the highest score. Use f_classif for linear relationships and mutual_info_classif when the relationship may be non-linear. A related step, VarianceThreshold, drops columns that are constant or nearly so, and it does not use the target.
from sklearn.feature_selection import SelectKBest, mutual_info_classif
selector = SelectKBest(score_func=mutual_info_classif, k=10)A filter scores each column alone. Two features that only help together can both be dropped, and two near-duplicate features can both be kept.
Wrapper methods
Recursive feature elimination (RFE) fits a model, removes the weakest features, and repeats. RFECV chooses how many features to keep by cross-validation. Wrappers account for feature interactions, but they fit many models, so they get slow on wide data.
Embedded methods
An L1-penalized model such as LogisticRegression(penalty="l1") sets some coefficients to exactly zero. Tree ensembles give feature_importances_. SelectFromModel turns either into a selector by keeping features above a threshold.
from sklearn.feature_selection import SelectFromModel
from sklearn.ensemble import RandomForestClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.pipeline import Pipeline
selector_model = Pipeline([
("prep", preprocess),
("select", SelectFromModel(RandomForestClassifier(n_estimators=200, random_state=0))),
("clf", LogisticRegression(max_iter=1000)),
])This code reuses the preprocess object from the pipelines chapter. Because the selector is a pipeline step, each training fold repeats the selection on its own data.
from sklearn.model_selection import cross_val_score
scores = cross_val_score(selector_model, X, y, cv=5, scoring="roc_auc")
print(scores.mean(), scores.std())Compare this score with the score of the pipeline without the selection step. Keep the selector only if it helps, or if it gives a similar score with fewer features.
Common errors
- Selecting before splitting. Running
SelectKBeston the full dataset, then cross-validating, leaks the target. Put the selector inside the pipeline. - Trusting impurity importances blindly. Tree importances favor high-cardinality and continuous columns. Check with permutation importance on held-out data when the choice matters.
- Dropping correlated features by accident. With correlated columns, a model may give all the importance to one and little to the others. Which one it picks can change between runs.
- Ignoring one-hot columns. After encoding, each category is its own feature. A selector may keep
city_Parisand drop the other cities, which is valid but harder to explain.
Exercise
A teammate runs SelectKBest(k=20) on the full dataset, then calls crossvalscore on the reduced matrix and reports an AUC of 0.91. Why might this number be too high, and how do you fix it?
Show answer
The selector used the target labels from every row, including the rows later used as validation folds, so the chosen features are tuned to those folds. This is leakage. Place SelectKBest as a step in a Pipeline and pass the whole pipeline to crossvalscore, so selection is refit on each training fold only.