Feature selection means keeping the columns that help a model and dropping the rest. Fewer features make a model faster, easier to explain and cheaper to run. Sometimes it also becomes more accurate, because useless columns add noise. This lesson covers the three main families: filter, wrapper and model-based methods.
In this lesson you will learn
- Removing constant columns with
VarianceThreshold - Ranking features with
SelectKBest - How noise columns hurt a distance-based model
- Choosing features with
SelectFromModelandRFE - Doing selection inside a pipeline to avoid leakage
You should know pipelines and cross-validation.
Filter Methods: Score Each Feature on Its Own
Filter methods look at one feature at a time and give it a score, without training the final model. They are quick and a good first pass.
from sklearn.datasets import load_breast_cancer
from sklearn.feature_selection import SelectKBest, VarianceThreshold, f_classif
import numpy as np
data = load_breast_cancer()
X, y, names = data.data, data.target, data.feature_names
print("Features before:", X.shape[1])
# 1. Drop features that hardly vary (here: a constant column we add)
X_plus = np.column_stack([X, np.ones(len(X))])
print("With a constant column added:", X_plus.shape[1])
vt = VarianceThreshold(threshold=0.0).fit(X_plus)
print("After VarianceThreshold:", vt.transform(X_plus).shape[1])
# 2. Keep the 5 features with the strongest ANOVA F-score
selector = SelectKBest(score_func=f_classif, k=5).fit(X, y)
order = np.argsort(selector.scores_)[::-1][:5]
print("\nTop 5 by F-score:")
for i in order:
print(f" {names[i]:<22} {selector.scores_[i]:8.1f}")
Output
Features before: 30
With a constant column added: 31
After VarianceThreshold: 30
Top 5 by F-score:
worst concave points 964.4
worst perimeter 897.9
mean concave points 861.7
worst radius 860.8
mean perimeter 697.2
VarianceThreshold(threshold=0.0)removes any column that has the same value in every row. Such a column cannot help any model.f_classifruns an ANOVA F-test. A high score means the feature’s average is very different between the classes.- The top five are all size and shape measurements, led by “worst concave points”.
- Several of them, such as perimeter and radius, measure almost the same thing. Filter methods do not notice this overlap, which is their main weakness.
When Selection Helps
To see the benefit clearly, the next example adds 100 columns of random noise to the 30 real ones. K-nearest neighbours measures distance across all columns, so the noise drowns out the real signal.
import numpy as np
from sklearn.datasets import load_breast_cancer
from sklearn.ensemble import RandomForestClassifier
from sklearn.feature_selection import SelectFromModel, SelectKBest, f_classif
from sklearn.model_selection import cross_val_score
from sklearn.neighbors import KNeighborsClassifier
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
X, y = load_breast_cancer(return_X_y=True)
rng = np.random.default_rng(0)
X_noisy = np.hstack([X, rng.normal(size=(len(X), 100))]) # add 100 useless columns
knn = KNeighborsClassifier(n_neighbors=5)
forest = RandomForestClassifier(n_estimators=200, random_state=0)
candidates = [
("30 real features", X, make_pipeline(StandardScaler(), knn)),
("130 with noise", X_noisy, make_pipeline(StandardScaler(), knn)),
("SelectKBest k=10", X_noisy, make_pipeline(StandardScaler(), SelectKBest(f_classif, k=10), knn)),
("SelectFromModel", X_noisy, make_pipeline(StandardScaler(), SelectFromModel(forest), knn)),
]
for name, data, pipe in candidates:
print(f"{name:<17} accuracy {cross_val_score(pipe, data, y, cv=5).mean():.3f}")
kept = SelectFromModel(forest).fit(X_noisy, y).get_support()
print("SelectFromModel kept", kept.sum(), "columns;", kept[30:].sum(), "of them are noise")
Output
30 real features accuracy 0.965
130 with noise accuracy 0.926
SelectKBest k=10 accuracy 0.939
SelectFromModel accuracy 0.968
SelectFromModel kept 21 columns; 0 of them are noise
- With only the real features, KNN reaches 96.5% accuracy. Adding the noise drops it to 92.6%.
SelectKBestkeeping 10 columns recovers some of the loss (93.9%).SelectFromModeltrains a random forest and keeps the columns whose importance is above the average. It keeps 21 columns, none of them noise, and reaches 96.8%.- Every selector sits inside the pipeline, so
cross_val_scorerefits it on each training fold. Selecting on the full dataset first would leak information from the test folds.
The Three Families
| Family | scikit-learn tools | How it works | Trade-off |
|---|---|---|---|
| Filter | VarianceThreshold, SelectKBest | Scores each feature with a statistic | Fast, but ignores overlap between features |
| Wrapper | RFE, SequentialFeatureSelector | Trains the model repeatedly, adding or removing features | Accurate, but slow on many features |
| Model-based | SelectFromModel | Uses a model’s coefficients or importances | Good balance; depends on the chosen model |
RFE (recursive feature elimination) fits a model, removes the weakest feature, and repeats until the requested number remain. For example, RFE(LogisticRegression(max_iter=5000), n_features_to_select=5). Lasso is also a model-based selector, because it sets some coefficients to exactly zero; see Ridge and Lasso.
Common Mistakes
- Selecting features on the whole dataset before splitting. The test score then looks better than it really is.
- Assuming fewer features is always more accurate. With clean, useful features, selection often costs a little accuracy.
- Treating
kas fixed. Tune it with grid search like any other setting. - Using
f_classifon a regression target. Usef_regressionormutual_info_regressioninstead.
Practice Exercises
Exercise 1. Print the names of the columns that SelectFromModel keeps on the original 30 features.
Show answer
data = load_breast_cancer()
sfm = SelectFromModel(forest).fit(data.data, data.target)
print(data.feature_names[sfm.get_support()])
Exercise 2. Find the best k for SelectKBest on the noisy data using grid search.
Show answer
from sklearn.model_selection import GridSearchCV
pipe = make_pipeline(StandardScaler(), SelectKBest(f_classif), knn)
search = GridSearchCV(pipe, {"selectkbest__k": [5, 10, 20, 30, 50]}, cv=5)
search.fit(X_noisy, y)
print(search.best_params_, round(search.best_score_, 3))
Frequently Asked Questions
What is the difference between feature selection and PCA?
Feature selection keeps some of the original columns, so they keep their meaning. PCA builds new columns that mix all of the originals, which are harder to explain.
Do tree models need feature selection?
Less than most. Trees pick useful splits on their own, so noise columns hurt them far less than they hurt KNN or SVM. Selection can still make them faster and simpler.
Summary
- Filter methods score features one by one; wrapper and model-based methods use a model.
- Selection matters most when there are many weak or noisy columns.
- Always place the selector inside a pipeline so it is fitted only on training data.
- Tune the number of features with cross-validation.
