Skip to main content

Lesson 5 of 9

Filter & Wrapper Feature Selection: Mutual Information, ANOVA & Recursive Feature Elimination

Feature selection eliminates noisy, redundant, and irrelevant features, mitigating the curse of dimensionality, speeding up inference, and boosting model interpretability. Feature selection algorithms are classified into: (1) Filter Methods (fast, model-agnostic statistical ranking: Mutual Information, ANOVA F-test, Chi-Square), (2) Wrapper Methods (iteratively search feature subsets using an estimator: Recursive Feature Elimination [RFE]), and (3) Embedded Methods (regularization penalties: Lasso, Tree feature importances).

25 minBy Priygop Editorial TeamUpdated 2026Peer Reviewed & Verified

Filter (Mutual Info) vs Wrapper (RFECV) Selection in Code

Filter (Mutual Info) vs Wrapper (RFECV) Selection in Code
import numpy as np
import pandas as pd
from sklearn.datasets import make_classification
from sklearn.feature_selection import SelectKBest, mutual_info_classif, RFECV
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import StratifiedKFold

# Generate dataset: 30 features total, but ONLY 5 are truly informative
np.random.seed(42)
X, y = make_classification(
    n_samples=1000, n_features=30, n_informative=5,
    n_redundant=5, n_repeated=0, random_state=42
)
feature_names = [f"feat_{i:02d}" for i in range(30)]

# 1. FILTER METHOD: SelectKBest via Mutual Information
# Fast, O(N * p), model-agnostic
selector_filter = SelectKBest(score_func=mutual_info_classif, k=5)
selector_filter.fit(X, y)
top_filter_indices = selector_filter.get_support(indices=True)
print("=== FILTER METHOD (SelectKBest Mutual Info) ===")
print(f"Top 5 Selected Features: {[feature_names[i] for i in top_filter_indices]}")

# 2. WRAPPER METHOD: Recursive Feature Elimination with Cross-Validation (RFECV)
# Iteratively trains a model, prunes the weakest feature, and validates with CV
rf = RandomForestClassifier(n_estimators=50, random_state=42)
cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)

rfecv = RFECV(
    estimator=rf,
    step=1, # Prune 1 feature per step
    cv=cv,
    scoring='roc_auc',
    n_jobs=-1
)
rfecv.fit(X, y)

print("\n=== WRAPPER METHOD (RFECV with Random Forest) ===")
print(f"Optimal Number of Features Selected: {rfecv.n_features_}")
selected_wrapper = [feature_names[i] for i, selected in enumerate(rfecv.support_) if selected]
print(f"Selected Feature Subset: {selected_wrapper}")
print(f"Peak CV ROC-AUC Score: {np.max(rfecv.cv_results_['mean_test_score']):.4f}")

Pro Tip: When to Use Filter vs Wrapper Methods

Use Filter methods (Mutual Information) as a preliminary coarse filter on massive feature stores (e.g. reducing 5,000 features down to 300 in seconds). Then use Wrapper methods (RFECV) or Embedded methods (Lasso/TreeSHAP) on the top 300 features to select the final optimal 30 features.

Diagram
Loading diagramโ€ฆ

MlFeatureSelection Visual Representation

Hands-On Challenge: Build a Sequential Forward Feature Selector

Use `sklearn.feature_selection.SequentialFeatureSelector` with `direction='forward'` to iteratively add features one by one, stopping when validation ROC-AUC ceases to improve.

Quick Quiz & Key Concept Checks

Common Pitfall: Running Feature Selection Outside Cross-Validation

Selecting features on the entire dataset before splitting into CV folds cherry-picks features that correlate with the test fold labels, producing severe optimistic validation bias. Always perform feature selection inside your cross-validation folds.

Topics in This Module

0/9 done