Interview's MateData Science
Interview's Mate

Data Science

Python → ML → MLOps

Visualizer

DSA Visualizer
All 32 lessons
Custom Playground
Try your own examples

Learning

System Design
31 architecture topics
SQL Learning
160 foundations → production topics
AI Engineering
160 LLM → backend topics
Data Science
160 Python → MLOps topics
Data Engineer
160 SQL → streaming topics
Docker
160 Docker learning topics
Kubernetes
160 K8s fundamentals → cloud
Java LearnSoon
Coming soon
Python Learn
Interview Q&A & internals
JavaScript Learn
Closures, async & DOM Q&A
Tech Learn
Search, practise & track Q&A
AI DSA Practice
Solve coding problems
Theme
Home
Data Science topics
Lesson 85/ 160
05. Classical Machine Learning

Regularization (Ridge, Lasso, ElasticNet)

Shrink coefficients with L2/L1 mixes to fight multicollinearity and improve generalization.

IntermediateRidge · Lasso3 quiz questions
Practice Generative AI Q&A
In plain wordsDiagramTheoryStep by stepWhen to use itInterview cluesMistakes to avoidQuiz (3)Practice

In plain words

Regularisation stops a model from relying too heavily on any one feature by adding a cost for big coefficients, which makes it work better on new data.

Think of it like…

A tight budget: ridge forces every department to cut spending a little, lasso eliminates some departments entirely, and elastic net does a mix, which keeps related departments from fighting over the same money.

Where you’ve seen it

Two features are almost duplicates (correlation 0.98), for example monthly_spend and quarterly_spend / 3. OLS gives unstable coefficients such as +8.2 and −6.1 with huge standard errors; a different bootstrap sample flips them to −3.0 and +5.4, so predictions on new data are erratic. Ridge splits the effect sensibly (about 1.1 and 1.0), lasso keeps one (1.9) and zeroes the other, and elastic net with l1_ratio=0.5 keeps both with smaller values. With 300 features and 500 rows, a cross-validated lasso (LassoCV) retains 24 non-zero coefficients and lowers test RMSE from 14.2 (OLS) to 9.8. In the orthonormal-design case the effects are explicit: with an OLS estimate of 3.0 and penalty λ = 1, ridge gives 3.0 / (1 + 1) = 1.5 while lasso soft-thresholds to 3.0 − 1 = 2.0; an estimate of 0.8 becomes 0.4 under ridge but exactly 0 under lasso.

Words you’ll hear

L2 / Ridge
Penalty on the sum of squared coefficients; shrinks all, rarely to zero.
L1 / Lasso
Penalty on the sum of absolute coefficients; produces sparse models.
ElasticNet
A weighted mix of L1 and L2 penalties.
Shrinkage
Pulling coefficient estimates toward zero to reduce variance.

Visual diagram

Loading interactive diagram

Theory & deep dive

The objectives and what each penalty does

Ridge minimises ‖y − Xβ‖² + λ‖β‖₂²; lasso minimises (1/2n)‖y − Xβ‖² + λ‖β‖₁ (scikit-learn's scaling); elastic net combines λ(ρ‖β‖₁ + (1 − ρ)/2 ‖β‖₂²). Ridge has a closed form β = (XᵀX + λI)⁻¹Xᵀy that makes XᵀX invertible even with collinear columns (adding λ to the diagonal), which is why it tames multicollinearity. Lasso has no closed form but is solved efficiently by coordinate descent; its diamond-shaped constraint region has corners on the axes, so solutions often land exactly at zero for some coefficients. In an orthonormal design, ridge scales every OLS coefficient by 1/(1 + λ) (3.0 becomes 1.5 at λ = 1), while lasso soft-thresholds it (sign(β̂)(|β̂| − λ)₊: 3.0 becomes 2.0 and 0.8 becomes 0).

Behavioural differences: ridge keeps all features and shrinks correlated ones together, good for prediction with many small effects; lasso selects features and is good when only a few matter, but with correlated features it picks one somewhat arbitrarily and can be unstable across samples; elastic net groups correlated features (keeps or drops them together) and handles p > n better than lasso (which selects at most n features). All introduce bias (coefficients are shrunk), so coefficients aren't unbiased effect estimates and standard inference needs care; use them mainly for prediction and screening, or use post-selection refits and appropriate methods for inference.

Closed-form shrinkage

Orthonormal design, OLS estimates 3.0 and 0.8, λ = 1. Ridge: 3.0/2 = 1.5 and 0.8/2 = 0.4. Lasso: 3.0 − 1 = 2.0 and max(0, 0.8 − 1) = 0. Ridge shrinks proportionally; lasso subtracts a fixed amount and zeroes small effects.

Key takeaway: Ridge shrinks proportionally, lasso soft-thresholds to zero, elastic net blends them; all trade bias for lower variance.

Choosing and tuning the penalty in practice

Always standardise numeric features inside a pipeline (make_pipeline(StandardScaler(), RidgeCV(alphas=np.logspace(-3, 3, 50)))), since otherwise a feature measured in large units is penalised less. Don't penalise the intercept. Choose λ by cross-validation (RidgeCV, LassoCV, ElasticNetCV) and consider the one-standard-error rule: the largest penalty whose CV error is within one SE of the minimum gives a simpler, more stable model. Search l1_ratio over values such as 0.1, 0.5, 0.9. Plot the coefficient path (coefficients versus λ) to see when features enter or leave, and examine stability by refitting on bootstrap samples (which features are selected consistently?).

Choose the method by situation: many correlated predictors and a prediction goal → ridge or elastic net; a desire for a sparse, explainable model with mostly independent signals → lasso; p ≫ n (genomics, text) → elastic net or lasso with stability checks. For classification, the same penalties apply to logistic regression via C (the inverse of strength) and penalty; trees use depth and leaf-size constraints and boosting uses shrinkage and reg_lambda. Remember that regularisation doesn't fix a misspecified model, leakage or non-stationarity; it reduces variance only. Track the train-validation gap before and after to confirm that the penalty did its job.

A tuned pipeline

pipe = make_pipeline(StandardScaler(), ElasticNetCV(l1_ratio=[.1, .5, .9], cv=5)). On 300 features, 500 rows it selects l1_ratio 0.5 with 41 non-zero coefficients and test RMSE 9.6, slightly better than pure lasso (9.8, 24 features) and far better than OLS (14.2).

Key takeaway: Standardise, tune alpha and l1_ratio by CV, use the 1-SE rule and verify stability and the generalisation gap.

How it works, step by step

Step 1 of 4
Analyst

1. Standardise inside a pipeline

Scale numeric features within the training fold so penalties treat them equally.

make_pipeline(StandardScaler(), ...)
Key numbers at this step
Don't
penalise the intercept

When to use it & trade-offs

What it is

Regularisation adds a penalty on coefficient size to the training loss, trading a little bias for a large drop in variance. Ridge (L2) penalises the sum of squared coefficients and shrinks them smoothly toward zero; Lasso (L1) penalises the sum of absolute values and can set coefficients exactly to zero, performing feature selection; ElasticNet mixes both (an l1_ratio between 0 and 1) and is more stable than lasso when features are correlated. The strength is a hyperparameter (λ, called alpha in scikit-learn) chosen by cross-validation, and features must be standardised first so the penalty treats them equally.

Why it matters: With many features, correlated features or few samples, plain OLS has high variance: coefficients swing wildly between samples and generalise poorly. Regularisation stabilises them, handles multicollinearity (ridge), builds sparse interpretable models (lasso) and is the same idea behind weight decay in neural networks and C in logistic regression and SVMs. Knowing when each penalty helps is a standard interview and practical topic.

When to reach for it

  • Models with many or correlated features
  • Small samples with high variance
  • Feature screening and sparse baselines

When to avoid or be careful

  • Regularising unscaled features
  • Interpreting shrunken coefficients as unbiased effects
  • Expecting regularisation to fix leakage or a wrong specification

Regularisation methods

Ridge (L2)
Best for: Correlated features and prediction accuracy

Strengths: Stable; closed form; handles collinearity.

Watch out: Keeps all features; no selection.

Lasso (L1)
Best for: Sparse, interpretable models

Strengths: Automatic feature selection.

Watch out: Unstable among correlated features; selects at most n.

ElasticNet
Best for: Many correlated features, p larger than n

Strengths: Groups correlated features; sparse yet stable.

Watch out: Two hyperparameters to tune.

Interview signals & numbers to know

When this topic comes up

  • “Coefficients flip sign between samples”
  • “Too many features for the rows”
  • L1 versus L2
  • Weight decay
  • alpha and l1_ratio

Benchmarks & rules of thumb

β̂ / (1 + λ) -
ridge shrinkage in an orthonormal design
sign(β̂)(|β̂| − λ)₊ -
lasso soft-thresholding
14.2 → 9.8 -
test RMSE with a cross-validated lasso in the example

Common mistakes & follow-ups

Common interview mistakes

  • Forgetting to scale features before penalising.
  • Choosing alpha on the test set.
  • Assuming lasso's selected features are the only causal ones.

Likely interviewer follow-ups

  • Why does lasso give sparse solutions but ridge doesn't?
  • How do you choose the regularisation strength?
  • When would you prefer elastic net?
Interview tip: Show the orthonormal shrinkage numbers (3.0 → 1.5 for ridge, 2.0 for lasso, 0.8 → 0). They explain the sparsity difference in one line.

Knowledge check

Loading quiz

Put it into practice

Practice related interview Q&A

Apply Regularization (Ridge, Lasso, ElasticNet) with data science interview Q&A and hands-on practice.

Open Data Science Q&A →Machine Learning Q&A
Previous topic
Linear & Polynomial Regression
Next topic
Logistic Regression