Sub topic 14
Selecting features: filter, wrapper and embedded methods
This chapter assumes you can build a scikit-learn Pipeline with a ColumnTransformer, run cross_val_score, and explain data leakage. It also assumes you know basic model terms such as coefficients and feature importances.
Why select features at all
After encoding, a table of ten columns can easily become a matrix of several hundred. Many of those columns carry little signal. Removing them has four benefits:
- Models overfit less, especially when rows are scarce compared to columns.
- Training and prediction get faster.
- The model is easier to explain.
- The serving system has fewer inputs to collect and keep consistent.
Selection does not always raise accuracy. Strong regularized models and gradient-boosted trees often ignore useless columns on their own. Treat selection as a hypothesis, and test it with cross-validation as described in the previous chapter.
Three families
Methods differ in how they judge a feature and how much computing they need.
| Family | How it scores features | Cost | Sees feature interactions? | Examples |
|---|---|---|---|---|
| Filter | A statistic computed per feature, independent of any final model | Low | Mostly no | `VarianceThreshold`, `SelectKBest`, mutual information |
| Wrapper | Refits a model on many candidate subsets and compares scores | High | Yes | `RFE`, `SequentialFeatureSelector` |
| Embedded | The model's own training produces the scores | Medium | Depends on the model | L1 coefficients, tree importances via `SelectFromModel` |
Filter methods
A filter ranks each column by a statistic and keeps the best ones. Start with the cheapest check, which is removing constant columns.
import numpy as np
from sklearn.datasets import make_classification
from sklearn.feature_selection import (
SelectKBest, VarianceThreshold, f_classif, mutual_info_classif,
)
X, y = make_classification(
n_samples=500, n_features=20, n_informative=4,
n_redundant=2, random_state=0,
)
X = np.hstack([X, np.zeros((500, 1))]) # add a constant column
print(VarianceThreshold().fit(X).get_support().sum()) # 20 of 21 survive
for name, score_fn in [("f_classif", f_classif), ("mutual_info", mutual_info_classif)]:
kb = SelectKBest(score_fn, k=5).fit(X, y)
print(name, np.flatnonzero(kb.get_support()))Choose the score to match the relationship you expect:
f_classif(ANOVA F-test) and the correlation-basedf_regressiondetect linear relationships.mutual_info_classifandmutual_info_regressionalso catch nonlinear ones. They are noisier on small samples and slower.chi2needs non-negative inputs, such as counts or one-hot columns.
Filters have two weaknesses. They score each column alone, so a feature that only helps in combination with another can be dropped. They also keep redundant columns: two near-copies of a strong feature both score highly. If you have many correlated columns, drop one of each highly correlated pair, or use a method that sees the whole feature set.
Wrapper methods
A wrapper treats the model as a black box and searches for the subset that scores best.
Recursive feature elimination (RFE) fits the model, removes the weakest features by coefficient or importance, and repeats. Forward SequentialFeatureSelector starts empty and adds the feature that most improves a cross-validated score at each step.
from sklearn.datasets import make_classification
from sklearn.feature_selection import RFE, SequentialFeatureSelector
from sklearn.linear_model import LogisticRegression
from sklearn.preprocessing import StandardScaler
from sklearn.pipeline import make_pipeline
X, y = make_classification(
n_samples=500, n_features=20, n_informative=4,
n_redundant=2, random_state=0,
)
X = StandardScaler().fit_transform(X) # for brevity; use a pipeline in real work
est = LogisticRegression(max_iter=1000)
rfe = RFE(est, n_features_to_select=6, step=2).fit(X, y)
print("RFE:", rfe.get_support(indices=True))
sfs = SequentialFeatureSelector(
est, n_features_to_select=4, direction="forward", cv=5, scoring="roc_auc",
).fit(X, y)
print("SFS:", sfs.get_support(indices=True))SequentialFeatureSelector fits roughly n_features × n_selected × cv models, so it becomes slow on wide data. It also optimizes the cross-validated score it uses to choose, so that score is optimistic. Keep a separate test set or an outer cross-validation loop for the final estimate. RFE is cheaper but depends on the model exposing coef_ or feature_importances_.
Embedded methods
Embedded methods get feature scores from one training run.
- L1 regularization pushes some coefficients to exactly zero. Features with zero coefficients are effectively removed. Scale the inputs first, because the penalty treats all coefficients equally and the coefficient size depends on the feature's units.
- Tree importances come from forests or boosted trees. They are cheap and cope with nonlinear effects. Impurity-based importances are biased toward high-cardinality and continuous columns, so a random ID-like column can look important.
SelectFromModel wraps either approach and keeps features whose importance is above a threshold.
from sklearn.datasets import make_classification
from sklearn.feature_selection import SelectFromModel
from sklearn.linear_model import LogisticRegression
from sklearn.preprocessing import StandardScaler
from sklearn.pipeline import make_pipeline
X, y = make_classification(n_samples=500, n_features=20, n_informative=4, random_state=0)
l1_select = make_pipeline(
StandardScaler(),
SelectFromModel(LogisticRegression(penalty="l1", solver="liblinear", C=0.1)),
).fit(X, y)
print(l1_select[-1].get_support().sum(), "features kept")A smaller C means stronger regularization and fewer surviving features. The threshold argument of SelectFromModel defaults to the mean importance. The string "median" keeps half the features, and a number sets a fixed cutoff.
Selection belongs inside the pipeline
Selection uses the target, so it is a fitted step, like an imputer or target encoder. If you select features on the full dataset and then cross-validate, the validation rows have already influenced which columns were chosen. This is leakage, and it is severe when there are many columns and few rows. Pure noise columns can score well by chance, and selecting among them produces an apparent skill that disappears on new data.
The fix is the same as for every other step: put the selector in the Pipeline, so it refits on each training fold.
import numpy as np
import pandas as pd
from sklearn.compose import ColumnTransformer
from sklearn.ensemble import RandomForestClassifier
from sklearn.feature_selection import SelectFromModel
from sklearn.impute import SimpleImputer
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import cross_val_score
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import OneHotEncoder, StandardScaler
rng = np.random.default_rng(0)
n = 600
X = pd.DataFrame({
"age": rng.integers(18, 80, n).astype(float),
"income": rng.lognormal(10, 0.5, n),
"city": rng.choice(["Oslo", "Rome", "Lima"], n),
})
for i in range(5):
X[f"noise_{i}"] = rng.normal(size=n)
logit = 0.04 * (X["age"] - 50) + 0.8 * (X["city"] == "Oslo") + rng.normal(0, 1, n)
y = (logit > 0).astype(int)
X.loc[rng.random(n) < 0.1, "age"] = np.nan
numeric_cols = ["age", "income"] + [f"noise_{i}" for i in range(5)]
categorical_cols = ["city"]
preprocess = ColumnTransformer([
("num", Pipeline([
("impute", SimpleImputer(strategy="median")),
("scale", StandardScaler()),
]), numeric_cols),
("cat", Pipeline([
("impute", SimpleImputer(strategy="most_frequent")),
("onehot", OneHotEncoder(handle_unknown="ignore")),
]), categorical_cols),
])
selector_model = Pipeline([
("prep", preprocess),
("select", SelectFromModel(
RandomForestClassifier(n_estimators=200, random_state=0),
threshold="median",
)),
("clf", LogisticRegression(max_iter=1000)),
])
scores = cross_val_score(selector_model, X, y, cv=5, scoring="roc_auc")
print(scores.mean(), scores.std())
selector_model.fit(X, y)
names = selector_model.named_steps["prep"].get_feature_names_out()
mask = selector_model.named_steps["select"].get_support()
print(names[mask])The last three lines refit on all the data only to inspect the result. Each cross-validation fold may keep a slightly different subset. If the chosen columns change a lot between folds, the selection is unstable. Treat that as a sign the data cannot support a firm ranking.
Common errors
- Selecting before splitting. This is the leakage described above. It shows up as a cross-validation score much better than the score on truly held-out data.
- Selecting on unscaled data with scale-sensitive scorers. L1 coefficients and RFE on linear models depend on feature scale.
- Reading one-hot columns as separate features. Selection may keep
city_Osloand dropcity_Rome. That is valid, but it means the rawcitycolumn is still needed at serving time. - Trusting importances among correlated features. Correlated columns split importance between them, so each may look weak, and a threshold may drop both.
- Selecting to chase small gains. If the full model and the reduced model score within one standard deviation of each other across folds, prefer whichever is simpler to serve.
Choosing a method
- Remove constant and duplicate columns first. It costs nothing.
- With very many columns, use a filter or an embedded method to cut the set down quickly.
- With a modest number of columns, a small budget of models, and a need for the best subset for one specific model, try a wrapper.
- If the final model is already L1-regularized or tree-based, an extra selection step often adds little.
Exercise
You select the 10 best of 2,000 columns with SelectKBest on the full dataset, then run 5-fold cross-validation on the reduced matrix and get an AUC of 0.92. On a fresh holdout the AUC is 0.58. What went wrong, and how do you fix it?
Show answer
The selector saw the validation rows' labels, so it picked columns that happened to correlate with the target in that sample. This is leakage, and with 2,000 columns many noise columns correlate by chance. Put SelectKBest inside a Pipeline with the model and pass the whole pipeline to cross_val_score. Each fold then refits the selector on its training rows only, and the cross-validation score will fall to a realistic value close to the holdout score.