Regularization adds a penalty for large coefficients to a model’s loss. It reduces overfitting, handles correlated features and – in the case of Lasso – can automatically remove useless features.
What You Will Learn
- L2 (Ridge) and L1 (Lasso) penalties
- Compare Linear, Ridge and Lasso on real data
- How alpha controls strength
- Elastic Net
- Tuning alpha with cross-validation
Prerequisites
The Idea
| Model | Loss minimised | Effect |
|---|---|---|
| Linear regression | Squared error | No penalty |
| Ridge (L2) | Squared error + α·Σw² | Shrinks all coefficients towards 0 |
| Lasso (L1) | Squared error + α·Σ|w| | Can set some coefficients exactly to 0 |
| Elastic Net | Mix of L1 and L2 | Selection plus stability with correlated features |
Compare on the Diabetes Dataset
import numpy as np
from sklearn.datasets import load_diabetes
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LinearRegression, Ridge, Lasso
from sklearn.model_selection import cross_val_score
X, y = load_diabetes(return_X_y=True) # 442 patients, 10 features
for name, m in [("Linear", LinearRegression()), ("Ridge a=1", Ridge(alpha=1)),
("Lasso a=0.5", Lasso(alpha=0.5))]:
pipe = make_pipeline(StandardScaler(), m)
r2 = cross_val_score(pipe, X, y, cv=5, scoring="r2").mean()
coef = pipe.fit(X, y)[-1].coef_
print(name, round(r2, 3), np.round(coef, 1), (np.abs(coef) < 1e-6).sum())
Linear 0.482 [ -0.5 -11.4 24.7 15.4 -37.7 22.7 4.8 8.4 35.7 3.2] 0 Ridge a=1 0.482 [ -0.4 -11.3 24.8 15.4 -30.1 16.7 1.5 7.5 32.8 3.3] 0 Lasso a=0.5 0.482 [ -0. -10.3 25. 14.7 -7.8 -0. -8.4 3.3 25. 2.9] 2
Explanation: All three give the same cross-validated R² (0.482) here, but the coefficients differ. Features 5 and 6 (blood-serum measures) are highly correlated, so plain regression gives them large opposite weights (−37.7 and 22.7). Ridge shrinks them; Lasso sets two coefficients exactly to zero – a simpler model with the same accuracy. Always scale features first, because the penalty depends on coefficient size.
Effect of alpha
for a in [0.1, 1, 5, 10]:
pipe = make_pipeline(StandardScaler(), Lasso(alpha=a))
zeros = (np.abs(pipe.fit(X, y)[-1].coef_) < 1e-6).sum()
print(a, zeros, round(cross_val_score(pipe, X, y, cv=5).mean(), 3))
0.1 1 0.482 1 3 0.482 5 5 0.466 10 6 0.439
Explanation: Larger alpha = stronger penalty = more zero coefficients. Up to alpha 1 we drop 3 features for free; beyond that the model starts underfitting and R² falls.
Tune alpha Automatically
from sklearn.linear_model import RidgeCV, LassoCV, ElasticNetCV
lasso = make_pipeline(StandardScaler(), LassoCV(cv=5, random_state=0)).fit(X, y)
print(lasso[-1].alpha_)
Explanation: The *CV classes search a range of alphas with cross-validation. ElasticNetCV also tunes l1_ratio (0 = Ridge, 1 = Lasso).
Regularization Elsewhere
- LogisticRegression uses L2 by default;
C= 1/α, so smaller C means stronger regularization. - Trees: max_depth, min_samples_leaf; XGBoost: lambda (L2) and alpha (L1).
- Neural networks: weight decay (L2), dropout, early stopping.
Series
ML fundamentals series: What is ML · Types of ML · Train/Test Split · Overfitting & Bias-Variance · Regularization · Confusion Matrix · ROC & AUC · Cross-Validation · Ensembles · DBSCAN
Interview Questions
Q: Ridge vs Lasso?
Ridge (L2) shrinks coefficients smoothly; Lasso (L1) can make them exactly zero, performing feature selection.
Q: Why scale before regularization?
The penalty depends on coefficient size, which depends on feature units.
Q: What does C mean in LogisticRegression?
Inverse regularization strength; smaller C = stronger penalty.
Practice Exercises
- Plot Lasso coefficients against alpha on a log scale (a regularization path).
- Compare ElasticNetCV with LassoCV on the same data.
Summary
Ridge shrinks, Lasso shrinks and selects, Elastic Net mixes both. Scale features, tune alpha with cross-validation and prefer the simplest model with equal accuracy.
Next: Confusion Matrix
Machine Learning Tutorials, Courses and Certifications