ML Study Hub

Home / MLT / Week 6

Week 6 · Ridge and LASSO: taming overfitting

Official syllabus line: Supervised Learning - Regression - Ridge/LASSO
About 70 minQuiz 2 material (see exam radar)BSCS2007 · Arun Rajkumar
Before you start: MLT week 5 (linear regression), MLF week 8 (convex functions help but are not required).
Watch first: the animated story of this weekAbout 1-2 minutes of real 3D animation with a friendly voice. Pause any time.
Read the words of the video
  1. Imagine a very eager student changing their answers to fit every little detail of practice questions, even noise. They fit practice data beautifully but fail on new questions. Our computer models can do this too, learning too much noise. We give the model a 'leash' to keep its answers sensible.
  2. We add a penalty for large 'weights' – the numbers the model learns. Ridge regression uses a soft leash: it gently pulls all weights smaller, but never to zero. LASSO regression uses a sharp leash: it can pull some weights exactly to zero, turning off unhelpful features.
  3. Let's see an example. If a model's best 'weight' for a feature is 3 without a penalty. Ridge, with a penalty, will shrink it, maybe to 1 or 0.3, but always keeps it positive. LASSO, however, with a strong enough penalty, can make that weight exactly zero, completely removing that feature.
  4. For your exam, remember that Ridge never makes weights exactly zero; LASSO can. Both add penalties to stop models from learning noise and overfitting. We choose the right 'leash strength', called lambda, by finding what works best on new data. Great job learning this complex idea!

The one-minute story

Think of it like this

A model with too much freedom is like a very eager student who changes their answer to fit every little detail of the practice questions, including noise. Their weights (the numbers the model learns) swing wildly: +900 here, −870 there, cancelling each other out. It fits the practice data beautifully and falls apart on a new question.

The cure is a leash on the weights. We add a penalty for large weights to the thing we are minimising. Now the model must be useful and modest.

  • Ridge puts a soft leash: every weight is pulled gently towards zero, but none is ever cut loose entirely.
  • LASSO puts a sharp leash: it can pull some weights exactly to zero, which switches those features off. It chooses which features matter.

Same idea, two flavours, two different personalities.

By the end of this week you can:

  • explain overfitting and why large weights are a warning sign;
  • derive and use the ridge solution (XTX+λI)−1XTy(X^TX+\lambda I)^{-1}X^T\mathbf y;
  • explain LASSO and why it gives sparse weights;
  • interpret both as MAP estimation (Gaussian prior vs Laplace prior);
  • pick λ\lambda by cross-validation and reason about bias and variance.

Words you need

Words you need
  • Regularisation - adding a penalty to discourage complicated models.
  • λ\lambda - the penalty strength. λ=0\lambda=0 means no penalty.
  • ℓ2\ell_2 penalty ∥w∥2=∑wj2\|\mathbf w\|^2=\sum w_j^2 (ridge). ℓ1\ell_1 penalty ∥w∥1=∑∣wj∣\|\mathbf w\|_1=\sum|w_j| (LASSO).
  • Shrinkage - making the weights smaller than the least-squares ones.
  • Sparse - mostly zeros.
  • Bias - systematic error from a model being too simple. Variance - sensitivity of the model to the particular training sample.

Idea 1: Why penalise?

If two features are almost copies of each other, least squares can give them huge opposite weights that nearly cancel. If XTXX^TX is singular (columns dependent) it is even worse: there are infinitely many equally good solutions. Penalising the size of the weights fixes both problems: it prefers small, stable weights.

Idea 2: Ridge regression (ℓ2\ell_2 penalty)

Minimise fit + penalty:

Lridge(w)=∥y−Xw∥2+λ∥w∥2\mathcal L_{\text{ridge}}(\mathbf w)=\|\mathbf y-X\mathbf w\|^2+\lambda\|\mathbf w\|^2

Take the gradient and set it to zero: −2XT(y−Xw)+2λw=0-2X^T(\mathbf y-X\mathbf w)+2\lambda\mathbf w=0, giving

wridge=(XTX+λI)−1XTy\boxed{\mathbf w_{\text{ridge}}=(X^TX+\lambda I)^{-1}X^T\mathbf y}

Things to notice:

  • Adding λI\lambda I adds λ\lambda to every eigenvalue of XTXX^TX, so for any λ>0\lambda>0 the matrix is invertible, even if XTXX^TX was singular. Ridge always has a unique answer.
  • λ→0\lambda\to0: back to least squares. λ→∞\lambda\to\infty: w→0\mathbf w\to\mathbf 0.
  • The objective is strictly convex (MLF week 8) so there is exactly one minimum.
  • In the simplest case of one feature, wridge=∑xiyi∑xi2+λ\mathbf w_{\text{ridge}}=\dfrac{\sum x_iy_i}{\sum x_i^2+\lambda}: the penalty just inflates the denominator, shrinking ww.
Solved example: 1. Ridge in one dimension

Question. Data x=(1,2,3)x=(1,2,3), y=(2,3,5)y=(2,3,5). Fit y=wxy=wx by ridge with λ=0,  1,  14\lambda=0,\;1,\;14.

Solution. ∑xy=23\sum xy=23 and ∑x2=14\sum x^2=14, so w=2314+λw=\dfrac{23}{14+\lambda}.

λ\lambdaww
0 (plain least squares)2314=1.643\frac{23}{14}=1.643
12315=1.533\frac{23}{15}=1.533
142328=0.821\frac{23}{28}=0.821

As λ\lambda grows the slope is pulled towards zero, but never reaches it.

Solved example: 2. Ridge rescues a singular problem

Question. Two features are exact copies: X=(112233)X=\begin{pmatrix}1&1\\2&2\\3&3\end{pmatrix} and y=(2,4,6)T\mathbf y=(2,4,6)^T. Least squares has no unique answer. What does ridge with λ=1\lambda=1 give?

Solution. XTX=(14141414)X^TX=\begin{pmatrix}14&14\\14&14\end{pmatrix} is singular (determinant 0): any w1+w2=2w_1+w_2=2 fits perfectly. With ridge: XTX+I=(15141415)X^TX+I=\begin{pmatrix}15&14\\14&15\end{pmatrix}, invertible, and XTy=(28,28)TX^T\mathbf y=(28,28)^T. By symmetry w1=w2=ww_1=w_2=w and 15w+14w=2815w+14w=28, so w=2829≈0.966w=\frac{28}{29}\approx0.966 for each. Ridge splits the credit equally between the twin features, and shrinks the total slightly (from 22 to 1.931.93).

Idea 3: LASSO (ℓ1\ell_1 penalty)

Llasso(w)=∥y−Xw∥2+λ∥w∥1\mathcal L_{\text{lasso}}(\mathbf w)=\|\mathbf y-X\mathbf w\|^2+\lambda\|\mathbf w\|_1

The absolute value has a sharp corner at 0 so the objective is not differentiable there, and there is no closed form in general (we use iterative methods). But it has a famous property: it sets some weights exactly to 0, a built-in feature selector.

Try it yourself

Both curves are (w−3)2(w-3)^2 plus a penalty. Drag lambda. Ridge's minimum slides smoothly towards 0 but never touches it; LASSO's minimum hits 0 and stays there once the penalty is big enough.

For one feature whose unpenalised best weight is zz, minimising (w−z)2+λ∣w∣(w-z)^2+\lambda|w| gives the soft-threshold:

wlasso=sign⁡(z) max⁡ ⁣(∣z∣−λ2,  0)w_{\text{lasso}}=\operatorname{sign}(z)\,\max\!\Big(|z|-\frac\lambda2,\;0\Big)

and the ridge version of the same problem, (w−z)2+λw2(w-z)^2+\lambda w^2, gives wridge=z1+λw_{\text{ridge}}=\dfrac z{1+\lambda}.

Solved example: 3. Ridge vs LASSO on one number

Question. Unpenalised best z=3z=3. Compare ridge and LASSO for λ=2\lambda=2 and λ=8\lambda=8.

Solution. Ridge: 31+2=1\frac3{1+2}=1 and 31+8=0.333\frac3{1+8}=0.333. LASSO: max⁡(3−1,0)=2\max(3-1,0)=2 and max⁡(3−4,0)=0\max(3-4,0)=\mathbf0.

For λ=8\lambda=8, LASSO has set the weight to exactly zero while ridge still keeps a small non-zero value.

The geometry (why LASSO makes zeros)

Equivalent view: minimise the squared error subject to a budget on the weights: ∥w∥22≤c\|\mathbf w\|_2^2\le c (ridge) or ∥w∥1≤c\|\mathbf w\|_1\le c (LASSO). The error has elliptical contour lines. The ridge budget region is a round disc; the LASSO region is a diamond with corners on the axes. The first contour to touch a smooth disc touches it anywhere; but it very often first touches the diamond at a corner, and a corner sits on an axis, where one weight is exactly 0.

Idea 4: The Bayesian meaning

From MLT week 5: Gaussian noise gives the squared-error fit term. Add a prior on the weights:

Prior on w\mathbf wMAP objectiveMethod
Gaussian N(0,τ2)\mathcal N(0,\tau^2)squared error +λ∥w∥22+\lambda\|\mathbf w\|_2^2, λ=σ2/τ2\lambda=\sigma^2/\tau^2Ridge
Laplace ∝e−∣w∣/b\propto e^{-|w|/b}squared error +λ∥w∥1+\lambda\|\mathbf w\|_1LASSO

A Laplace density has a sharp spike at 0, so it "believes in zeros", which explains the sparsity. A tighter prior (small τ\tau) means a bigger λ\lambda.

Idea 5: Choosing λ\lambda and the bias-variance trade-off

  • Small λ\lambda: flexible, low bias, high variance (overfits).
  • Large λ\lambda: stiff, high bias, low variance (underfits).
  • Training error rises with λ\lambda; validation error is U-shaped: best somewhere in the middle. Pick λ\lambda by cross-validation.
  • Standardise the features first (the penalty treats all weights equally, so features on different scales would be punished unfairly), and normally do not penalise the intercept.
  • Elastic net mixes both penalties.

Your turn

Your turn: 1. Ridge in one dimension

Data x=(1,2)x=(1,2), y=(3,5)y=(3,5). Compute the ridge weight for y=wxy=wx with λ=5\lambda=5 (check the λ=0\lambda=0 case too).

Need a hint?

w=∑xy/(∑x2+λ)w=\sum xy/(\sum x^2+\lambda).

Show the full solution

∑xy=3+10=13\sum xy=3+10=13, ∑x2=1+4=5\sum x^2=1+4=5. λ=0\lambda=0: w=2.6w=2.6. λ=5\lambda=5: w=1310=1.3w=\frac{13}{10}=\mathbf{1.3}.

Your turn: 2. Soft-threshold

The unpenalised best weights for three features are 4, 1.5, −34,\,1.5,\,-3. What are the LASSO weights (per-feature problem) with λ=4\lambda=4? And ridge with λ=1\lambda=1?

Need a hint?

Soft-threshold at λ/2=2\lambda/2=2.

Show the full solution

LASSO: 4→24\to2; 1.5→01.5\to0 (since 1.5<21.5<2); −3→−1-3\to-1. Ridge (÷2\div2): 2,  0.75,  −1.52,\;0.75,\;-1.5. LASSO zeroed the middle feature; ridge did not.

Your turn: 3. Direction of the effect

For each, say whether it goes up or down as λ\lambda increases: (a) training error (b) the size of the weights (c) variance of the predictions (d) bias.

Need a hint?

More penalty means a stiffer model.

Show the full solution

(a) up, (b) down, (c) down, (d) up.

Your turn: 4. Which statements are true?

(a) Ridge always gives a unique solution for λ>0\lambda>0. (b) LASSO can set weights exactly to zero. (c) Ridge is MAP with a Laplace prior. (d) Ridge has a closed-form solution.

Need a hint?

Review the table in Idea 4.

Show the full solution

(a) True. (b) True. (c) False: ridge is a Gaussian prior; LASSO is Laplace. (d) True: (XTX+λI)−1XTy(X^TX+\lambda I)^{-1}X^T\mathbf y.

Your turn: 5. Choosing lambda

Validation errors for λ=0, 0.1, 1, 10, 100\lambda=0,\,0.1,\,1,\,10,\,100 are 9.0, 5.1, 3.2, 4.0, 8.59.0,\,5.1,\,3.2,\,4.0,\,8.5. Which λ\lambda would you choose and why?

Need a hint?

Smallest validation error.

Show the full solution

λ=1\lambda=1 (error 3.23.2). The curve is U-shaped: smaller λ\lambda overfits, larger underfits.

Exam radar

Exam radar

MLT Quiz 2 summaries mention ridge in 7 papers. In the End Term: ridge regression in 20 papers (and "Ridge Regression (L2 Regularization)" in 13), overfitting in 19, underfitting in 15. LASSO is named in the course syllabus, so expect it too.

Typical: "which of the following is the ridge solution?", "what happens to the weights as λ→∞\lambda\to\infty?", "which regulariser produces sparse weights?", "ridge as MAP with which prior?", and a one-dimensional ridge calculation.

Watch out - real exam trap
  • Ridge never gives exact zeros; LASSO can.
  • Ridge penalty is on squared weights; the intercept is usually not penalised.
  • Bigger λ\lambda means more bias, less variance.
  • Gaussian prior ↔\leftrightarrow ridge; Laplace prior ↔\leftrightarrow LASSO (easy to swap by accident).
  • Features must be on comparable scales before regularising.

Quick quiz

Quick quiz

The ridge regression solution is...

  • (X^T X)^-1 X^T y
  • (X^T X + lambda I)^-1 X^T y
  • (X X^T)^-1 y
  • X^T y / lambda
Ridge adds lambda times the identity to X^T X before inverting.

As lambda grows very large, ridge weights tend to...

  • infinity
  • the least-squares weights
  • zero
  • one
The penalty dominates and pulls all weights towards zero.

Which penalty tends to produce exactly-zero weights?

  • l2 (ridge)
  • l1 (LASSO)
  • no penalty
  • none of them
The l1 penalty has a corner at zero that can trap weights there.

Select all TRUE statements. (select all that apply)

  • Ridge is MAP estimation with a Gaussian prior on the weights.
  • Increasing lambda increases the bias of the model.
  • Ridge regression can make a singular X^T X problem worse.
  • LASSO has a simple closed-form solution for every data set.
Adding lambda I makes the matrix invertible, and LASSO generally needs an iterative solver.

Recap

Remember this
  • Ridge: ∥y−Xw∥2+λ∥w∥2⇒w=(XTX+λI)−1XTy\|\mathbf y-X\mathbf w\|^2+\lambda\|\mathbf w\|^2\Rightarrow\mathbf w=(X^TX+\lambda I)^{-1}X^T\mathbf y. Always invertible; shrinks smoothly; Gaussian prior.
  • LASSO: ∥y−Xw∥2+λ∥w∥1\|\mathbf y-X\mathbf w\|^2+\lambda\|\mathbf w\|_1. Sparse weights; no closed form; Laplace prior; soft-threshold in 1-D.
  • λ↑\lambda\uparrow: bias ↑\uparrow, variance ↓\downarrow, training error ↑\uparrow. Choose λ\lambda by cross-validation; standardise features.
Formulas to keep
  • Ridge: w=(XTX+λI)−1XTy\mathbf w=(X^TX+\lambda I)^{-1}X^T\mathbf y; 1-D: ∑xy∑x2+λ\frac{\sum xy}{\sum x^2+\lambda}; per-feature shrink z1+λ\frac z{1+\lambda}
  • LASSO soft-threshold: sign⁡(z)max⁡(∣z∣−λ/2,0)\operatorname{sign}(z)\max(|z|-\lambda/2,0)
  • MAP: Gaussian prior →λ=σ2/τ2\to\lambda=\sigma^2/\tau^2 (ridge); Laplace prior →\to LASSO
Connected weeks (learn them together)

Practise with real exam questions

These come straight from past papers (with the real figures and the official answer key). Open 18 real questions on this week   All Quiz 2 papers