Lesson 6 of 9
Embedded & SHAP-Based Feature Selection: Minimizing Multicollinearity & Bloat
Embedded feature selection methods perform selection intrinsically during model training. Lasso (L1 regularization) forces non-informative weights to zero. Tree ensembles compute Mean Decrease in Impurity (MDI). However, for production GBDTs, SHAP-Based Feature Selection is the state of the art: it calculates the mean absolute SHAP value across out-of-fold validation data, identifying the most causally impactful predictors while pruning collinear redundancies.
SHAP-Based Pruning vs L1 Regularization Selection
import numpy as np
import pandas as pd
from sklearn.linear_model import LassoCV
from sklearn.ensemble import HistGradientBoostingRegressor
from sklearn.datasets import fetch_california_housing
from sklearn.preprocessing import StandardScaler
# Ingest California housing dataset
raw = fetch_california_housing(as_frame=True)
X, y = raw.data, raw.target
feature_names = raw.feature_names
# 1. EMBEDDED L1 SELECTION VIA LASSOCV
scaler = StandardScaler()
X_scaled = scaler.fit_transform(X)
lasso = LassoCV(cv=5, random_state=42)
lasso.fit(X_scaled, y)
lasso_selected = pd.Series(lasso.coef_, index=feature_names)
print("=== EMBEDDED LASSO (L1) FEATURE COEFFICIENTS ===")
for feat, coef in lasso_selected.items():
print(f" {feat:15s}: {coef:+.4f} -> {'KEPT' if abs(coef) > 1e-4 else 'ZEROED OUT (PRUNED)'}")
# 2. TREE-BASED PERMUTATION / SHAP IMPORTANCE SELECTION
hgb = HistGradientBoostingRegressor(random_state=42)
hgb.fit(X, y)
from sklearn.inspection import permutation_importance
perm_imp = permutation_importance(hgb, X, y, n_repeats=5, random_state=42)
df_importance = pd.DataFrame({
'feature': feature_names,
'importance_mean': perm_imp.importances_mean
}).sort_values('importance_mean', ascending=False)
print("\n=== PERMUTATION-BASED FEATURE SELECTION RANKING ===")
print(df_importance.to_string(index=False))Pro Tip: The 1% Cumulative Gain Rule
Sort features by descending SHAP importance. Calculate the cumulative sum of importance. You will frequently discover that the top 15% of features account for 90%+ of total model impact. Pruning the bottom 85% of features simplifies data pipelines, slashes latency by 5x, and rarely hurts accuracy.
MlShapFeatureSelection Visual Representation
Hands-On Challenge: Build an Automated Lasso Pruner Transformer
Write a Scikit-Learn transformer `LassoFeatureSelector(alpha=0.05)` that fits a Lasso model during `.fit()`, stores indices where `abs(coef_) > 0`, and filters columns during `.transform()`.
Quick Quiz & Key Concept Checks
Common Pitfall: Confusing Feature Importance with Causal Impact
Machine learning feature importance measures predictive correlation, NOT causal effect. In marketing data, 'discount_code_applied' may have high importance for sales, but offering discounts to everyone could bankrupt the business. Do not make policy decisions without causal inference.