Packing for a trip, you could take everything you own, but the bag gets heavy, you can't find what you need, and some of it was never going to be useful. Models face the same trade-off with features. Extra columns cost time and money to collect, make the model slower and harder to explain, and some models get noticeably worse when given columns that are just noise.
Feature selection methods pick a smaller set of useful columns. They come in three families: filters score each feature on its own, wrappers try subsets of features with a model, and embedded methods let the model drop features while it trains. Here all three face the same test: California housing with 20 columns of pure random noise added, to see which methods can tell real features from fake ones, and which models even care.
What you need first: feature engineering basics, KNN explained, ridge and lasso regression, scikit-learn pipelines and data leakage.
Key terms
- Feature selection: choosing a subset of the existing features; unlike feature engineering, it creates nothing new.
- Filter method: scores each feature against the target on its own, before any model is trained.
- Wrapper method: tries different subsets of features with a model and keeps the subset that scores best.
- Embedded method: selection that happens inside training, such as lasso setting coefficients to exactly zero.
- Mutual information: how much knowing a feature reduces uncertainty about the target; unlike correlation, it also catches curved relationships.
The test: 8 real features, 20 fake ones
import numpy as np
import pandas as pd
from sklearn.datasets import fetch_california_housing
from sklearn.model_selection import KFold, cross_val_score
housing = fetch_california_housing(as_frame=True)
X_real, y = housing.data, housing.target
rng = np.random.default_rng(0)
noise = pd.DataFrame(rng.normal(size=(len(X_real), 20)), columns=[f"noise_{i}" for i in range(20)])
X = pd.concat([X_real, noise], axis=1)
cv = KFold(n_splits=5, shuffle=True, random_state=0)
print(X.shape)
(20640, 28)
Download the data: california-housing.csv (1.9 MB), or from the original source, the StatLib repository. The code above loads it for you, so you only need the file to open it in a spreadsheet or work offline: load it with
pd.read_csv("california-housing.csv").
rng.normal(size=(20640, 20)) makes 20 columns of random numbers with no link to house prices. pd.concat(..., axis=1) puts them beside the 8 real columns. Because the fake columns are known, every method below can be checked.
Which models care?
Predict first: a KNN model measures distance across every column. Gradient boosting chooses one column at a time for each split. Which will the 20 noise columns hurt more?
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.neighbors import KNeighborsRegressor
from sklearn.ensemble import HistGradientBoostingRegressor
for name, model in [("KNN", make_pipeline(StandardScaler(), KNeighborsRegressor(n_neighbors=10))),
("Gradient boosting", HistGradientBoostingRegressor(random_state=0))]:
with_noise = cross_val_score(model, X, y, cv=cv, scoring="r2").mean()
real_only = cross_val_score(model, X_real, y, cv=cv, scoring="r2").mean()
print(f"{name:18}: R² {real_only:.3f} with the 8 real features, {with_noise:.3f} with 20 noise columns added")
KNN : R² 0.696 with the 8 real features, 0.371 with 20 noise columns added
Gradient boosting : R² 0.836 with the 8 real features, 0.831 with 20 noise columns added
KNN collapses: R² falls from 0.696 to 0.371 when the noise is added. Its idea of "nearby houses" now depends on 28 columns, 20 of which are random, so its nearest neighbours are mostly neighbours in noise. Gradient boosting barely notices (0.836 against 0.831): each split picks the single most useful column, and random columns are almost never the most useful, so they're simply ignored. Feature selection matters most for models that use every column equally, such as KNN, K-means and SVMs with an RBF kernel.
Feature selection filter methods: score each feature alone
A filter gives every feature a score against the target and keeps the top ones. Two common scores: the F-test, which measures straight-line relationships, and mutual information, which catches any kind of relationship.
from sklearn.feature_selection import f_regression, mutual_info_regression
f_scores, _ = f_regression(X, y)
mi_scores = mutual_info_regression(X, y, random_state=0)
ranking = pd.DataFrame({"F-test": f_scores, "mutual info": mi_scores}, index=X.columns)
print("F-test top 8: ", list(ranking["F-test"].nlargest(8).index))
print("mutual info top 8:", list(ranking["mutual info"].nlargest(8).index))
print(ranking.loc[["Longitude", "Latitude", "noise_0"]].round(3))
F-test top 8: ['MedInc', 'AveRooms', 'Latitude', 'HouseAge', 'AveBedrms', 'Longitude', 'Population', 'AveOccup']
mutual info top 8: ['Longitude', 'MedInc', 'Latitude', 'AveRooms', 'AveOccup', 'HouseAge', 'AveBedrms', 'Population']
F-test mutual info
Longitude 43.699 0.400
Latitude 438.005 0.372
noise_0 0.338 0.001
f_regression returns two arrays, the scores and their p-values; _ throws the second away. nlargest(8) keeps the 8 highest scores.
Both filters put all 8 real features at the top, with every noise column below them. They disagree about order: the F-test ranks Longitude sixth, with a score of 44 against 438 for Latitude, while mutual information ranks it first. Prices don't rise or fall steadily from west to east; they peak in particular places, such as the coast around Los Angeles and San Francisco. That's a curved relationship, which mutual information catches and a straight-line test mostly misses. A noise column scores almost nothing on both: 0.338 and 0.001.
Embedded methods: let lasso decide
Lasso regression adds a penalty that pushes weak coefficients to exactly zero, so the features it keeps are its selection. LassoCV chooses the penalty strength by cross-validation:
from sklearn.linear_model import LassoCV
lasso = make_pipeline(StandardScaler(), LassoCV(cv=5, random_state=0)).fit(X, y)
kept = X.columns[lasso[-1].coef_ != 0]
print(f"penalty chosen: {lasso[-1].alpha_:.4f}")
print(f"kept {len(kept)} features, {sum(c.startswith('noise') for c in kept)} of them noise")
penalty chosen: 0.0034
kept 13 features, 6 of them noise
lasso[-1] is the last step of the pipeline, the fitted lasso model. coef_ != 0 marks the features it kept.
Lasso keeps 13 features, and 6 of them are noise. It also drops Population, a real but weak feature. With a light penalty (0.0034), which cross-validation chose because it predicts best, a noise column only needs to explain a sliver of random variation to keep a small coefficient. The kept noise coefficients are tiny, though, 0.005 or less against at least 0.036 for every real feature kept, so the coefficient sizes separate real from fake better than the zero-or-not rule does. Lasso picks a penalty for prediction, not for selection.
Wrapper methods: recursive feature elimination
Recursive feature elimination (RFE) trains a model, drops the weakest feature, retrains on the rest, and repeats until the requested number is left:
from sklearn.feature_selection import RFE
from sklearn.linear_model import LinearRegression
rfe = RFE(LinearRegression(), n_features_to_select=8).fit(StandardScaler().fit_transform(X), y)
print("RFE kept:", list(X.columns[rfe.support_]))
RFE kept: ['MedInc', 'HouseAge', 'AveRooms', 'AveBedrms', 'AveOccup', 'Latitude', 'Longitude', 'noise_5']
rfe.support_ is True for the features RFE kept. The features are scaled first, because RFE ranks a linear model's features by the size of their coefficients, and sizes are only comparable on the same scale.
RFE keeps 7 real features and one noise column, noise_5, in place of Population. A linear model gives Population almost no weight, so to RFE it looks no better than noise. A wrapper inherits the blind spots of the model inside it: features that matter in a curved way or only in combination can be dropped by a linear wrapper.
Experiment: selection inside the pipeline
Experiment: put the mutual information filter inside a pipeline before KNN, so it's refitted on each training fold. Predict first: can it bring KNN back to its real-features-only score?
from sklearn.feature_selection import SelectKBest
selecting_knn = make_pipeline(StandardScaler(), SelectKBest(mutual_info_regression, k=8),
KNeighborsRegressor(n_neighbors=10))
print(f"KNN with selection inside the pipeline: R² {cross_val_score(selecting_knn, X, y, cv=cv, scoring='r2').mean():.3f}")
KNN with selection inside the pipeline: R² 0.696
SelectKBest(mutual_info_regression, k=8) keeps the 8 features with the highest mutual information, measured on whatever data it's fitted on.
Yes: R² 0.696, the same as KNN given only the real features. Inside each training fold, mutual information picks the right 8 columns, and KNN is back to measuring distance in the features that matter. The noise cost nothing once it was removed.
See it fail: selecting before cross-validation
Why insist on putting selection inside the pipeline? Here's a dataset that is pure noise: 200 rows, 2,000 random features and random labels. No model can do better than 50% on it. Select the 20 features most related to the labels, using all the rows, then cross-validate a model on them:
from sklearn.model_selection import StratifiedKFold
from sklearn.feature_selection import f_classif
from sklearn.linear_model import LogisticRegression
X_noise = rng.normal(size=(200, 2000))
y_noise = rng.integers(0, 2, 200)
folds = StratifiedKFold(n_splits=5, shuffle=True, random_state=0)
chosen = SelectKBest(f_classif, k=20).fit(X_noise, y_noise).get_support()
leaky = cross_val_score(LogisticRegression(max_iter=1000), X_noise[:, chosen], y_noise, cv=folds).mean()
honest = cross_val_score(make_pipeline(SelectKBest(f_classif, k=20), LogisticRegression(max_iter=1000)),
X_noise, y_noise, cv=folds).mean()
print(f"selected on all rows, then cross-validated: accuracy {leaky:.3f}")
print(f"selected inside each training fold: accuracy {honest:.3f}")
selected on all rows, then cross-validated: accuracy 0.775
selected inside each training fold: accuracy 0.465
get_support() returns True for the 20 chosen columns, and X_noise[:, chosen] keeps only those.
On data with no pattern at all, selecting features on all the rows produces a cross-validated accuracy of 0.775. With 2,000 random features and only 200 rows, some features match the random labels well purely by chance, and choosing them using every row means choosing features that happen to fit the validation rows too. Inside the pipeline, each fold chooses its own 20 features from its training rows only, and the score falls to 0.465: chance, which is the truth. This is the same leakage as in data leakage, and it's especially dangerous with many features and few rows, as in genetics or text data.
Which method when?
| Method | Speed | Catches | Weakness | Use when |
|---|---|---|---|---|
| F-test filter | Very fast | Straight-line relationships | Misses curves and interactions | A quick first cut with many features |
| Mutual information filter | Fast | Any relationship with one feature | Misses features useful only in combination | A general first cut |
| Lasso | Fast | Features useful to a linear model | With a weak penalty, keeps noise | Linear models, many features |
| RFE | Slow (one fit per removed feature) | Features useful to the chosen model | Inherits the model's blind spots | Moderate numbers of features |
| Permutation importance | Slow | Features a fitted model relies on | Shared credit between correlated features | Explaining and pruning a final model |
And whichever you use: does the model even need it? Tree ensembles shrug off noise; distance-based models (KNN, K-means, SVM with an RBF kernel) don't.
Practice
- Without running code: two features are perfect copies of each other. What will a mutual information filter do with them?
Show the answer
Keep both or neither: each scores exactly the same on its own, so a filter can't see that the second adds nothing once the first is in. Filters judge features one at a time; wrappers and lasso can notice redundancy.
- Use
SelectKBest(f_regression, k=8)inside the KNN pipeline instead of mutual information. Is the R² the same?
Show the answer
f_knn = make_pipeline(StandardScaler(), SelectKBest(f_regression, k=8), KNeighborsRegressor(n_neighbors=10))
print(round(cross_val_score(f_knn, X, y, cv=cv, scoring="r2").mean(), 3))
0.691
Almost: 0.691 against 0.696. The F-test also finds all 8 real features, and the small difference comes from folds where its choices differ slightly. On this data, either filter is enough to rescue KNN.
- Make lasso stricter with
Lasso(alpha=0.05)inside the pipeline. How many noise features survive now, and how many real ones?
Show the answer
from sklearn.linear_model import Lasso
strict = make_pipeline(StandardScaler(), Lasso(alpha=0.05)).fit(X, y)
kept_strict = X.columns[strict[-1].coef_ != 0]
print(len(kept_strict), list(kept_strict))
4 ['MedInc', 'HouseAge', 'Latitude', 'Longitude']
No noise survives, but only 4 real features do: MedInc, HouseAge, Latitude and Longitude. A stronger penalty removes the noise and the weaker real features with it. There's no penalty that keeps exactly the real ones, which is why lasso is a predictor first and a selector second.
- Without running code: why can gradient boosting ignore 20 noise columns, while KNN can't?
Show the answer
Each split in a tree uses the one column that reduces the error most, and a random column almost never wins, so the noise is simply never used. KNN has no such choice: its distance adds up differences in every column, so random columns change who counts as a neighbour.
- A colleague drops every feature with a correlation below 0.1 to the target before splitting the data. What two problems do you point out?
Show the answer
First, leakage: the choice used the test rows, so test scores will be optimistic, as the pure-noise example showed. Second, correlation only measures straight-line relationships one feature at a time: a feature with a curved effect, or one useful only together with another, could be dropped although it helps.
Interview questions
What are the main types of feature selection?
Filter methods score features independently of a model (correlation, F-test, mutual information, chi-squared). Wrapper methods search over subsets using a model's performance (recursive feature elimination, forward or backward selection). Embedded methods select during training (lasso's L1 penalty, tree-based importance).
How do you avoid leakage in feature selection?
Fit the selection on training data only: put it inside a pipeline so that cross-validation refits it on each training fold, and never use the test set or the full dataset to choose features.
Does feature selection always improve accuracy?
No. Tree ensembles and regularised models often lose little from extra features, and dropping useful ones hurts. Selection helps most with distance-based models, small datasets with many features, and when fewer features are wanted for speed, cost or explanation.
Key takeaways
- Feature selection keeps a subset of existing features: filters score them alone, wrappers try subsets, embedded methods select while training.
- Noise features ruined KNN here and barely touched gradient boosting: check whether your model needs selection at all.
- Filters found all 8 real features; lasso with a cross-validated penalty kept 6 noise columns; RFE swapped a weak real feature for noise.
- Put selection inside the pipeline, or cross-validation scores are optimistic: selection outside it made pure noise look 77% accurate.
- No method is perfect; compare the final model's validated score with and without selection.
Frequently asked questions
How many features should I keep?
Treat it as a setting: try several values of k inside the pipeline with cross-validation, and pick the smallest number that scores about as well as the best.
Is feature importance from a random forest a good selection method?
It's a reasonable first look, but impurity-based importance favours features with many distinct values and splits credit between correlated features. Permutation importance on validation data is more reliable.
What's the difference between feature selection and PCA?
Selection keeps some original columns, so they keep their meaning. PCA builds new columns from combinations of all of them; it reduces dimensions but the new columns are hard to explain.
What to learn next
- Check whether a model's probabilities can be trusted in probability calibration, the next lesson.
- Revisit how lasso zeroes coefficients in ridge and lasso regression.
- Revisit why fitting on all the data leaks in data leakage.