Skip to content

Feature Selection

Feature selection removes uninformative or redundant features. This reduces overfitting, speeds up training, and can improve performance. Here we compare five approaches on a synthetic dataset with 20 features, 8 of them informative.

Every code block runs in a container in the companion repository, so the numbers are real.

from pathlib import Path
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from sklearn.datasets import make_classification
out = Path("outputs")
out.mkdir(exist_ok=True)
features, y = make_classification(n_samples=500,
n_features=20,
n_informative=8,
n_redundant=2,
random_state=42)
feature_names = [f"feature_{i}" for i in range(features.shape[1])]

The simplest filter. Features with near-zero variance carry no information.

from sklearn.feature_selection import VarianceThreshold
rng = np.random.RandomState(42)
x_noisy = np.column_stack([features, rng.normal(0, 0.001, (500, 5))])
selector = VarianceThreshold(threshold=0.01)
x_filtered = selector.fit_transform(x_noisy)
print(f"Features before: {x_noisy.shape[1]}, after: {x_filtered.shape[1]}")
Features before: 25, after: 20

All five near-zero-variance noise columns are removed.

Univariate methods score each feature independently against the target.

The F-test (ANOVA) measures whether a feature’s mean differs between classes:

from sklearn.feature_selection import SelectKBest, f_classif
sel = SelectKBest(f_classif, k=10).fit(features, y)
f_table = pd.DataFrame({
"feature": feature_names,
"f_score": sel.scores_,
"p_value": sel.pvalues_,
}).sort_values("f_score", ascending=False)
print(f_table.head(6).to_string(index=False))
feature f_score p_value
feature_16 60.224901 4.834258e-14
feature_18 50.742350 3.709522e-12
feature_13 29.243132 9.926065e-08
feature_5 22.595704 2.620671e-06
feature_6 4.321873 3.813677e-02
feature_7 4.307767 3.845142e-02

Mutual information captures nonlinear associations the F-test misses:

from sklearn.feature_selection import mutual_info_classif
mi = mutual_info_classif(features, y, random_state=42)
mi_table = pd.DataFrame({
"feature": feature_names,
"mi_score": mi,
}).sort_values("mi_score", ascending=False)
print(mi_table.head(5).to_string(index=False))
feature mi_score
feature_16 0.055935
feature_13 0.051800
feature_5 0.049058
feature_18 0.033025
feature_6 0.021969

RFE trains a model, drops the least important feature, and repeats. Unlike univariate methods, it accounts for feature interactions.

from sklearn.feature_selection import RFE
from sklearn.linear_model import LogisticRegression
from sklearn.preprocessing import StandardScaler
rfe = RFE(LogisticRegression(max_iter=1000, random_state=42),
n_features_to_select=10).fit(StandardScaler().fit_transform(features),
y)
kept = [name for name, keep in zip(feature_names, rfe.support_) if keep]
print(f"RFE keeps {len(kept)} features:")
for start in range(0, len(kept), 5):
print(" " + ", ".join(kept[start:start + 5]))
RFE keeps 10 features:
feature_1, feature_3, feature_5, feature_7, feature_12
feature_13, feature_15, feature_16, feature_17, feature_18

RFE keeps feature_1 and feature_3, which appear in neither univariate list above. RFE judges each feature inside a model that holds all the others, so a feature that adds little on its own can still survive.

Random forests compute importance as a byproduct of training.

from sklearn.ensemble import RandomForestClassifier
rf = RandomForestClassifier(n_estimators=100, random_state=42).fit(features, y)
importance = pd.DataFrame({
"feature": feature_names,
"importance": rf.feature_importances_,
}).sort_values("importance", ascending=False)
print(importance.head(6).to_string(index=False))
feature importance
feature_16 0.134316
feature_18 0.118628
feature_5 0.097055
feature_13 0.087026
feature_15 0.068941
feature_4 0.048066
top15 = importance.head(15)
fig, ax = plt.subplots(figsize=(6, 5))
ax.barh(top15["feature"][::-1], top15["importance"][::-1], color="#4c72b0")
ax.set_xlabel("Importance")
ax.set_title("Random forest feature importance (top 15)")
fig.tight_layout()
fig.savefig(out / "feature-importance.png", dpi=150)
plt.close(fig)

Random forest feature importance, top 15 features

The top four features (16, 18, 5, 13) rank high by every method, a strong signal they carry real information.

L1 regularization shrinks some coefficients to exactly zero, removing those features. In current scikit-learn, request pure L1 with l1_ratio=1.

lasso = LogisticRegression(solver="saga",
l1_ratio=1,
C=0.1,
max_iter=5000,
random_state=42)
lasso.fit(StandardScaler().fit_transform(features), y)
print(
f"Non-zero features: {(lasso.coef_[0] != 0).sum()} / {len(feature_names)}")
coefficients = pd.DataFrame({
"feature": feature_names,
"coefficient": lasso.coef_[0],
}).sort_values("coefficient", key=abs, ascending=False)
print(coefficients.head(4).round(4).to_string(index=False))
Non-zero features: 11 / 20
feature coefficient
feature_16 0.7348
feature_18 -0.6471
feature_13 -0.6002
feature_5 -0.4529

LASSO kept 11 features and zeroed 9. The coefficient sign gives the direction: feature_16 is positive (raises the probability of class 1), feature_18 negative.

Compare cross-validated ROC-AUC with all 20 features against the top 10 by random forest importance. The forest above was fit on all 500 rows, so its ranking has already seen every validation fold and the test rows. Reusing that ranking here would break the rule in the caution at the end of this page. Instead, SelectFromModel goes inside the pipeline. In each fold a new forest ranks the features on the training folds only, and the held-out fold never decides which ten survive. threshold=-np.inf with max_features=10 keeps exactly ten features.

from sklearn.feature_selection import SelectFromModel
from sklearn.model_selection import (
StratifiedKFold,
cross_val_score,
train_test_split,
)
from sklearn.pipeline import Pipeline
x_train, x_test, y_train, y_test = train_test_split(features,
y,
test_size=0.2,
stratify=y,
random_state=42)
cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)
pipe = Pipeline([("scaler", StandardScaler()),
("clf", LogisticRegression(max_iter=1000, random_state=42))])
# The forest ranks features again inside every training fold.
select_pipe = Pipeline([
("select",
SelectFromModel(RandomForestClassifier(n_estimators=100,
random_state=42),
threshold=-np.inf,
max_features=10)),
("scaler", StandardScaler()),
("clf", LogisticRegression(max_iter=1000, random_state=42)),
])
scores_all = cross_val_score(pipe, x_train, y_train, cv=cv, scoring="roc_auc")
scores_top = cross_val_score(select_pipe,
x_train,
y_train,
cv=cv,
scoring="roc_auc")
print(f"All 20 features: ROC-AUC = {scores_all.mean():.4f} "
f"(+/- {scores_all.std():.4f})")
print(f"Top 10 features: ROC-AUC = {scores_top.mean():.4f} "
f"(+/- {scores_top.std():.4f})")
All 20 features: ROC-AUC = 0.8088 (+/- 0.0336)
Top 10 features: ROC-AUC = 0.8201 (+/- 0.0254)

With selection inside the cross-validation, the top ten features lift ROC-AUC from 0.8088 to 0.8201 and narrow the spread across folds from 0.0336 to 0.0254. The gain is smaller than the fold-to-fold standard deviation, so this run is weak evidence that the ten dropped features hurt the model. On this data, the main gain from selection is a model with half the features and no loss in ROC-AUC.

Method Speed Interactions Good for
Variance threshold Very fast No First pass, remove constants
F-test / mutual info Fast No / Yes Quick ranking of many features
RFE Slow Yes Careful selection, smaller data
Tree importance Fast Yes Quick ranking with any tree model
LASSO Fast No Selection and modeling at once

The next page covers Feature Engineering: creating new features to give the model more signal.

  • scikit-learn feature selection

    The guide explains variance thresholds, univariate scores, recursive elimination, and SelectFromModel. Each method uses different evidence to select a feature, so the methods need separate interpretation.

  • scikit-learn cross-validation guide

    The guide describes held-out and nested evaluation. Use these split rules when feature selection and hyperparameter choice form one prediction procedure.