Machine Learning Slides 📂 Introduction · 10 of 17 51 min read

Ridge & Lasso Regression Explained — L1 vs L2 Regularisation & ElasticNet

A visual, beginner-friendly guide to regularised linear regression. Learn why plain OLS overfits with many features, how Ridge's L2 penalty shrinks coefficients smoothly and how Lasso's L1 penalty drives them to exactly zero for automatic feature selection, the geometric intuition behind the circle-vs-diamond constraint, ElasticNet's hybrid approach, tuning α with cross-validation, sklearn implementation and six golden rules.

⚖️

Ridge · Lasso · ElasticNet

The three regularised regressions that tame linear models — shrinking wild coefficients, killing useless features, and rescuing OLS from overfitting in high dimensions.
Ridge · L2 Lasso · L1 ElasticNet Bias-Variance Steering

Press Next → or use ← → arrow keys

Section 01

Why Regularisation? — When Plain OLS Breaks

80 features, 500 houses, and a plain OLS that hits 0.97 train and 0.71 test
You engineered 80+ features for a housing model — neighbourhood dummies, interaction terms, polynomial transforms. Ordinary Least Squares finds the coefficients that minimise training error, so it blows the numbers up wherever it needs to and lands on a beautiful train R² = 0.97.

Then you hit the test set: R² = 0.71. Classic overfitting. Two feature columns are strongly correlated? OLS's coefficients swing wildly with any change in data — the multicollinearity crisis. Regularisation is the fix: add a penalty for large coefficients, and the model is forced to prefer modest weights that generalise.
💥
Two Problems, One Cure

Overfitting — coefficients grow enormous to hug the training data. Multicollinearity — correlated features produce unstable, high-variance coefficients. Both dissolve when you add a penalty term to the cost function that discourages large weights.

0.97 → 0.88Test R² after Ridge
46 → 34Features kept by Lasso
αPenalty strength dial
CVAlways tune it
Section 02

The Two Penalties — Squared vs Absolute

Ridge · L2 penalty
Cost = RSS + α · Σ βⱼ²
Adds squared coefficients. Closed-form solution: β̂ = (XᵀX + αI)⁻¹Xᵀy. Shrinks all weights toward zero.
Lasso · L1 penalty
Cost = RSS + α · Σ |βⱼ|
Adds absolute values. No closed form — solved by coordinate descent. Pushes some weights exactly to zero.
🔵
Ridge Behaviour
shrinks — never zeros
Dense output. Every feature stays, but with a smaller coefficient. Great when most features contribute a little.
🟣
Lasso Behaviour
shrinks + selects
Sparse output. Useless features get coefficient = 0 automatically. Great for high-dimensional data with few real predictors.
🟠
Alpha (α)
the steering wheel
α = 0 → plain OLS. Small α → mild pull. Large α → all weights crushed. Tune with cross-validation on a log grid.
💡
The Penalty Is A Budget For Coefficients

The regulariser tells the model: "You may use any coefficients you want — but the bigger they are, the higher the tax you pay." Only truly useful features can afford to keep large weights.

Section 03

Coefficient Shrinkage — Three Regressions, Same Data

OLS · no penalty wild coefficients huge · unstable Ridge · L2 shrinks all coefficients smaller stable · all features kept Lasso · L1 zeros most features → 0 sparse · feature selection
📊
Read Left To Right — The Penalty Story

OLS lets coefficients grow wild. Ridge shrinks them all evenly, keeping every feature. Lasso zeros out the ones the data doesn't need — a built-in feature selector. Same data, three very different models.

Section 04

Why Lasso Zeros — The L1 Diamond vs L2 Circle

Ridge · L2 constraint = CIRCLE smooth boundary · no corners β₁ β₂ solution touches on a smooth curve → β₁,β₂ both ≠ 0 Lasso · L1 constraint = DIAMOND sharp corners on the axes β₁ β₂ β₂ = 0 solution snaps to a corner → β₂ = 0 exactly
📐
The Whole Feature-Selection Story In One Picture

Regularisation constrains coefficients to a shape. The RSS-minimising point wants to sit as close to OLS as possible — so it touches the constraint region at whichever point is closest. A smooth circle touches at a spot where both coefficients are non-zero. A diamond with sharp axis corners almost always touches on a corner — where one coefficient is exactly zero. That's why Lasso does feature selection and Ridge doesn't.

Section 05

Coefficient Paths — As α Grows, Weights Shrink

Ridge · smooth shrinkage α = 0 α = ∞ α → (log scale) coefficient → Lasso · staircase to zero α = 0 α = ∞ α → (log scale)
📉
Different Shrinkage Signatures

Ridge paths smoothly bend toward zero — no coefficient ever hits it. Lasso paths stair-step: at each α threshold, another coefficient snaps to zero and stays there. The Lasso plot is the feature-selection story: read off which α gives you the number of features you want.

Section 06

Tuning α — The Sweet Spot Between Bias & Variance

α → 0 optimal α α → ∞ regularisation strength (log scale) → error → train error test error SWEET SPOT ← overfit · variance dominates underfit · bias dominates →
α valueEffect on modelSymptom
α = 0No regularisation · identical to OLSHigh variance · overfits
α small (10⁻³–10⁻¹)Gentle shrinkageBalanced · usually the sweet spot
α moderate (1–10)Meaningful pull on coefficientsRobust to noisy data
α very large (100+)All weights crushed toward 0High bias · underfits
🎚️
Never Trust The Default α = 1.0

The optimal α depends entirely on your data. Sweep a log-spaced grid (e.g. np.logspace(-3, 4, 100)) via RidgeCV or LassoCV. The valley of the test-error curve is your target.

Section 07

Lasso In Action — Automatic Feature Selection

80 features → Lasso keeps 34, zeros 46 bars show coefficient magnitude · dashes show zeroed features sqft_living 0.412 ✓ bedrooms 0.207 ✓ bathrooms 0.154 ✓ lot × sqft 0.000 ✗ dropped neigh_A 0.118 ✓ neigh_B 0.000 ✗ dropped age −0.088 ✓ zip_id 0.000 ✗ dropped Deployed model: 34 features · simpler · faster · more interpretable
✂️
Two Jobs, One Model

Lasso regularises AND selects features in one shot. No separate feature-selection step required. Redundant neighbourhood dummies, useless interactions, ID-like columns — the L1 penalty snips them all to zero. The surviving 34 features form a simpler, faster, more explainable model.

Section 08

The Three Constraint Shapes — Ridge · Lasso · ElasticNet

Ridge · L2 λ · Σ β² smooth · dense · no feature dropped Lasso · L1 λ · Σ |β| sharp · sparse · feature selection ElasticNet · L1 + L2 αΣ|β| + (1−α)Σβ² hybrid · sparse but stable
ModelPenaltyOutputBest For
RidgeL2 (squared)Dense · all features keptCorrelated features · when everything matters a little
LassoL1 (absolute)Sparse · auto-selectionHigh-dim data · few real predictors · interpretability
ElasticNetL1 + L2 mixSparse but groupedCorrelated features AND need selection · genomics · text
Section 09

Scaling — The Non-Negotiable First Step

Income in ₹ (millions) vs age in years — same penalty, unfair effect
The regularisation penalty punishes coefficients equally, regardless of feature scale. A feature measured in millions (income) will always have a naturally tiny coefficient — the penalty barely touches it. A feature measured in ones (age) will have a large coefficient — and get crushed disproportionately. The result is a model biased by units, not signal.

Fix: standardise every feature to mean 0, std 1 before fitting Ridge/Lasso. StandardScaler is one line. Skip it and every coefficient is meaningless.
💧
Fit The Scaler On Training Data Only

scaler.fit_transform(X_train), then scaler.transform(X_test) — never re-fit on the full data. Fitting on the combined dataset leaks test statistics into training and inflates every score. Better still: wrap it in a Pipeline and let cross-validation handle it automatically.

Section 10

Implementation — RidgeCV, LassoCV, ElasticNetCV

from sklearn.linear_model import RidgeCV, LassoCV, ElasticNetCV
from sklearn.preprocessing import StandardScaler
from sklearn.pipeline import Pipeline
import numpy as np

alphas = np.logspace(-3, 4, 100)                   # log grid — mandatory

# ── Ridge — auto-tuned via CV ────────────────────
ridge = Pipeline([
    ('scaler', StandardScaler()),
    ('ridge',  RidgeCV(alphas=alphas, cv=10)),
]).fit(X_train, y_train)
print(f"best α = {ridge.named_steps['ridge'].alpha_}")

# ── Lasso — needs max_iter bumped up ────────────
lasso = Pipeline([
    ('scaler', StandardScaler()),
    ('lasso',  LassoCV(cv=10, max_iter=10000, random_state=42)),
]).fit(X_train, y_train)
sparse = np.sum(lasso.named_steps['lasso'].coef_ != 0)
print(f"features kept: {sparse}")

# ── ElasticNet — best of both worlds ────────────
enet = Pipeline([
    ('scaler', StandardScaler()),
    ('enet', ElasticNetCV(
        l1_ratio=[.1, .3, .5, .7, .9],             # search the mix too
        alphas=np.logspace(-3, 2, 60),
        cv=10, max_iter=10000, n_jobs=-1,
    )),
]).fit(X_train, y_train)
🧪
The Pipeline Is Non-Negotiable

Wrapping the scaler + model in a Pipeline means the scaler refits on each CV fold's training partition only — no leakage. Do it manually and your CV scores lie by 2–5%.

Section 11

Common Pitfalls — What Silently Breaks Regularised Models

📏
Forgetting To Scale
the #1 mistake
Without StandardScaler, the penalty punishes small-unit features unfairly. Every Ridge/Lasso run needs it.
🎚️
Default α = 1.0
rarely optimal
Always sweep a log grid via RidgeCV/LassoCV. The right α depends on your data — never guess.
💧
Scaler Data Leakage
fit on full data
Fitting the scaler on train+test leaks statistics into training. Always fit on train only, or wrap in a Pipeline.
🚫
Penalising Intercept
β₀ must escape
The intercept is not a coefficient — never penalise it. sklearn handles this correctly by default; custom code often forgets.
🔁
Lasso Convergence
watch the warning
Coordinate descent needs iterations. If you see ConvergenceWarning, bump max_iter to 10,000+.
📊
Comparing Raw Coefficients
apples vs kilos
Coefficient magnitude only means something when features are standardised. Otherwise big β might mean small feature scale.
Section 12

Choosing — Which Regularisation For Which Problem?

🔵
Ridge
Many features, most contribute a little. Correlated groups where you want to distribute weight, not drop one arbitrarily.
🟣
Lasso
High dimensions with few truly predictive features. When you need a sparse, interpretable model — or p > n.
🟠
ElasticNet
Correlated features AND need selection. Genomics, text vectors, wide sensor arrays. Best default when uncertain.
🩺
Medical / Regulated
Lasso for interpretability. Regulators love sparse models with clear feature-effect stories.
💰
Finance / Time Series
Ridge — lagged features are naturally correlated. Ridge distributes weight; Lasso would arbitrarily kill some lags.
🧬
Genomics · p ≫ n
Lasso or ElasticNet. Thousands of gene features, few truly causal — sparse selection is essential.
🎯
When In Doubt, Start With ElasticNet

Let cross-validation search across l1_ratio values — if L1 wins, you get sparsity; if L2 wins, you get stability. Either way, the CV picks the right blend for your data.

Section 13 · Part 1

Golden Rules — 1 to 3

⚖️ REGULARISATION DISCIPLINE · RULES 1–3
1
Always standardise features first. Use StandardScaler. Fit on training data only. Wrap in a Pipeline so CV folds handle it correctly. Without scaling, the penalty punishes based on units, not signal.
2
Never trust the default α. Sweep a log-spaced grid from 10⁻³ to 10⁴ using RidgeCV, LassoCV, or ElasticNetCV. Manual α picking is guesswork.
3
Ridge for correlated features · Lasso for sparse solutions. Ridge distributes weight evenly; Lasso arbitrarily picks one and kills the rest. When features are collinear and you need feature selection, use ElasticNet.
Section 13 · Part 2

Golden Rules — 4 to 6

⚖️ REGULARISATION DISCIPLINE · RULES 4–6
4
Bump max_iter for Lasso. Coordinate descent is iterative. If you see a ConvergenceWarning, raise to 10,000+ or scale features better. Silent non-convergence gives silently wrong coefficients.
5
Read the coefficient path plot before shipping. It shows which features survive at each α, and reveals correlated groups that regularisation treats erratically. This is the ML equivalent of eyeballing the residuals.
6
Never penalise the intercept. β₀ is the baseline, not a feature effect. sklearn excludes it correctly; custom code often forgets. Also, never compare coefficients across models unless features are standardised.
The Regularised Model Deployment Checklist

✅ Features standardised in a Pipeline · ✅ α tuned by CV on log grid · ✅ Ridge vs Lasso vs ElasticNet chosen by problem structure · ✅ Coefficient path inspected · ✅ Convergence confirmed · ✅ Intercept unpenalised.

FINAL

Ridge · Lasso — Two Penalties That Save Linear Models

L2Ridge · smooth shrinkage
L1Lasso · zero-out selection
αTune via CV log grid
📏Scale · always first
ENElasticNet · hybrid
6Golden rules
🎯
The Foundation Is Set

You now understand why plain OLS breaks on wide data, how the L2 circle differs from the L1 diamond, why Lasso produces sparse models and Ridge doesn't, and how α steers the bias-variance dial. Every regularised model you build — LogisticRegression with penalties, GLMs, neural-network weight decay — rests on exactly these ideas.

📚
Where To Go Next

Study Logistic Regression with L1/L2 for classification, then Bayesian Ridge for uncertainty quantification, then Group Lasso for feature-group selection. Practise on Kaggle's House Prices — the classic testbed for regularised regression.

⚖️ End of tutorial · Press to review, or click Restart