Lesson 4 of 9
L1 (Lasso), L2 (Ridge) & ElasticNet Regularization Mechanics
When feature count p is large or features are collinear, unconstrained OLS overfits and exhibits high variance. Regularization introduces an inductive bias by adding a penalty on weight magnitudes to the loss function. Ridge (L2 penalty: ||w||²_2) shrinks weights proportionally toward zero, stabilizing variance. Lasso (L1 penalty: ||w||_1) drives non-informative weights strictly to zero, performing automated feature selection. ElasticNet blends both penalties to overcome Lasso's limitations on correlated groups.
Ridge vs Lasso vs ElasticNet Geometric Mechanics
import numpy as np
import pandas as pd
from sklearn.linear_model import Ridge, Lasso, ElasticNet, LinearRegression
from sklearn.preprocessing import StandardScaler
from sklearn.pipeline import Pipeline
# Generate high-dimensional dataset: 50 features, but ONLY 5 true causal predictors
np.random.seed(42)
n_samples = 200
n_features = 50
X = np.random.normal(0, 1, size=(n_samples, n_features))
# True weights: only first 5 features have signal
true_weights = np.zeros(n_features)
true_weights[:5] = [5.0, -4.0, 3.0, -2.5, 1.5]
y = X @ true_weights + np.random.normal(0, 2.0, size=n_samples)
# Train comparison models
models = {
'Unregularized OLS': LinearRegression(),
'Ridge (L2 penalty, alpha=10.0)': Ridge(alpha=10.0),
'Lasso (L1 penalty, alpha=0.5)': Lasso(alpha=0.5),
'ElasticNet (L1 + L2, l1_ratio=0.5)': ElasticNet(alpha=0.5, l1_ratio=0.5)
}
results = []
for name, model in models.items():
model.fit(X, y)
coefs = model.coef_
zero_weights = np.sum(np.isclose(coefs, 0.0, atol=1e-3))
l2_norm = np.linalg.norm(coefs)
results.append({
'Model': name,
'Active Non-Zero Features': n_features - zero_weights,
'Zeroed-Out Features (Sparsity)': zero_weights,
'Weight Vector L2 Norm': f"{l2_norm:.2f}"
})
print("=== REGULARIZATION SPARSITY & CAPACITY COMPARISON ===")
print(pd.DataFrame(results).to_string())Pro Tip: When to Use ElasticNet Over Lasso
If your dataset contains groups of highly correlated features (e.g. 10 features measuring related economic indicators), Lasso arbitrarily picks one feature from the group and zeroes out the other nine. ElasticNet's L2 component encourages grouping effect, shrinking correlated features together while the L1 component induces sparsity.
MlRegularization Visual Representation
Hands-On Challenge: Plotting the Lasso Regularization Path
Use `sklearn.linear_model.lasso_path` to compute and plot the trajectory of all 50 feature coefficients as `alpha` increases from 0.001 to 100.0. Observe which features are zeroed out first and identify the optimal alpha threshold.
Quick Quiz & Key Concept Checks
Common Pitfall: Forgetting that Regularization Strength `alpha` is Scale-Dependent
In Scikit-Learn, the penalty term is unscaled by sample size in `Lasso` and `Ridge`. If you double your dataset size n, the relative weight of the penalty changes. Always tune `alpha` using cross-validation (`RidgeCV`, `LassoCV`) on the specific training sample size.