Ridge, Lasso and MAP

Regularisation, priors, sparsity

7 lessons · 21 past questions · 62.5 marks in the papers collected here

Open the interactive lessons →Ridge, Lasso and MAP past questions

Diagrams, animations, quizzes and checked solutions are on the interactive pages.

Contents

  1. Orientation: what you will learn and why
  2. Big picture: one idea in three forms, and the comparison table
  3. Start here: the pieces you need
  4. Ridge regression: the formula, the arithmetic and what $\lambda$ does
  5. The constrained view and choosing a weight vector
  6. Lasso ($L_1$): sparsity, the diamond picture and comparing weights
  7. MAP: regularisation as a prior

1. Orientation: what you will learn and why

Plain least squares can behave badly: with few data points, many features or noisy labels it produces huge weights that follow the noise. Regularisation adds a price on large weights. Ridge charges for the squared size of $w$ ($L_2$), Lasso charges for the sum of absolute values ($L_1$) and can switch weights off completely. MAP explains both as "least squares plus a prior belief about $w$".

What you will be able to do

Why this topic matters for Quiz 2

Counted only from the PYQs in this project (not a prediction):

What the PYQs askPYQsMarks
Ridge: formula, arithmetic and the role of lambda520.5
Constrained form and choosing a weight vector310
Lasso (L1): sparsity, contours, comparing weights713
MAP: regularisation as a prior619

In total 21 PYQs worth 62.5 marks across 9 papers (12 MCQ, 5 MSQ, 4 numeric). The $2\times2$ ridge arithmetic and the "what does $\lambda$ do" facts appear again and again.

How this topic connects

It extends the Linear regression topic: the loss is the same plus a penalty. The probabilistic story reuses the Gaussian noise model there. Cross-validation (a later topic) is how $\lambda$ is chosen.

Tags: [SRC] from your files, [DERIVED] answer I worked out because the bank gives no key, [ADDED] my own example, [FLAG] disagreement with the bank.
How to use this page

Step through every worked example, do the quick checks, then attempt each PYQ before opening its solution.

What is new in this upgrade [ADDED]

See the problem: weights that explode

Fit $y=w_0+w_1x+w_2x^2$ exactly through $x=1,\,1.1,\,1.2$. With $y=2.0,\,2.4,\,2.1$ the weights are $(-40.5,\;77.5,\;-35)$. Change only the middle value to $2.0$ and they become $(7.5,\;-10.5,\;5)$. A change of $0.4$ in one label moved a weight by $88$: the fit is following noise. Ridge charges a price for large weights, so this cannot happen cheaply.

The route through this topic
the piecesridgeconstrained view and lassoMAP

2. Big picture: one idea in three forms, and the comparison table

[ADDED] Read this page first. It shows the whole topic on one screen. Every later section is one cell of the grid below.

One idea, three ways to write it

Penalty formadd λ·(size of w) to the lossConstraint formminimise the error inside a shapeBayesian formbelieve a prior, maximise posteriorRidge (L2)SSE + λ‖w‖²ball: ‖w‖² ≤ θw ~ N(0, γ²I)Lasso (L1)SSE + λ‖w‖₁diamond: ‖w‖₁ ≤ θw ~ Laplace(0, b)Same estimator in all three columns. Translation: Gaussian prior gives λ = σ²/γ²; small θ means large λ.
The row decides the shape of the penalty (squares or absolute values). The column decides how you write it. Rows and columns are linked: a ball goes with squares and a Gaussian, a diamond goes with absolute values and a Laplace.

The idea in one line. Do not trust large weights. Large weights fit noise. So make the model pay for size. You can say "pay a fee" (penalty), "stay inside a budget" (constraint) or "I believed the weights were small before I saw data" (prior). The three sentences describe the same estimator.

Comparison table: five estimators side by side

Plain least squaresRidge ($L_2$)Lasso ($L_1$)MAP, Gaussian priorMAP, Laplace prior
Objective$\|X^Tw-y\|^2$$\|X^Tw-y\|^2+\lambda\|w\|_2^2$$\|X^Tw-y\|^2+\lambda\|w\|_1$$\frac1{2\sigma^2}\|y-X^Tw\|^2+\frac1{2\gamma^2}\|w\|^2$$\frac1{2\sigma^2}\|y-X^Tw\|^2+\frac1b\|w\|_1$
Same as-MAP with Gaussian priorMAP with Laplace priorRidge, $\lambda=\sigma^2/\gamma^2$Lasso, $\lambda=2\sigma^2/b$
Constraint shapenoneball $\|w\|^2\le\theta$diamond $\|w\|_1\le\theta$balldiamond
Closed form?yes, $(XX^T)^{-1}Xy$yes, $(XX^T+\lambda I)^{-1}Xy$no (needs an iterative method)yes (ridge formula)no
Exact zeros in $w$?no (rarely)noyesnoyes
Needs $XX^T$ invertible?yesno: $XX^T+\lambda I$ is invertible for $\lambda>0$nonono
Effect on size of $w$largestsmaller, smoothlysmaller, some become 0smallersmaller, some 0
Overfitting riskhighestlowerlowerlowerlower
Exam cue"minimise MSE""$\lambda\|w\|^2$", "ball", "invertible""$\|w\|_1$", "diamond", "discard a feature""prior $N(0,\gamma^2I)$""prior Laplace", "$\arg\min$"

Ridge versus Lasso: the confusion table

QuestionRidgeLasso
What does the penalty add up?squares of the weightsabsolute values of the weights
Shape of the allowed regionround balldiamond with corners on the axes
Where do the error ovals usually touch?a smooth point: no weight is exactly 0a corner: one weight is exactly 0
Prior it corresponds toGaussian (bell, smooth top)Laplace (sharp peak at 0)
Good whenmany features all matter a little; features are correlatedonly a few features matter; you want to delete the rest
Weaknesskeeps every feature, so the model is not sparseno simple formula; among very similar features it may keep one arbitrarily

Mnemonics and recognition cues [ADDED]

Analogy and its limit [ADDED]

AnalogyWhat it explains wellWhere it breaks
A fee per page of answerwhy large weights must "earn" their sizea real fee is linear in size; ridge charges the square, so one big weight costs far more than two small ones
A spring pulling each weight to 0why the weight shrinks smoothly as $\lambda$ growsa spring never pulls exactly to 0; that is why ridge gives no exact zeros, but lasso (a constant-force pull) does

Recall questions

Which penalty can set a weight to exactly zero?

Lasso ($L_1$), because the diamond has corners on the axes. Ridge only shrinks.

Is the ridge solution defined when $XX^T$ is singular?

Yes. For $\lambda>0$ the matrix $XX^T+\lambda I$ is invertible, so $\hat w_R=(XX^T+\lambda I)^{-1}Xy$ exists.

Gaussian prior with variance $\gamma^2$ and noise variance $\sigma^2$. What is $\lambda$?

$\lambda=\sigma^2/\gamma^2$. A tight prior (small $\gamma^2$) gives a large $\lambda$.

Laplace noise on $y$. Is that Lasso?

No. Laplace noise gives an absolute-value loss $\sum|r_i|$. Lasso is an absolute-value penalty on $w$, which comes from a Laplace prior.

Tips and tricks
  • Every form is the same trade: fit the data, but charge for large weights.
  • Check whether a loss is a sum or a mean, since that changes what $\lambda$ means.

3. Start here: the pieces you need

Piece 1. Norms measure the size of a vector

Definition: $L_2$ and $L_1$ norm

For $w=(w_1,\dots,w_d)$: $\|w\|_2^2=w_1^2+\dots+w_d^2$ (sum of squares) and $\|w\|_1=|w_1|+\dots+|w_d|$ (sum of absolute values).

Example: $w=(3,-4)$: $\|w\|_2^2=9+16=25$, $\|w\|_1=3+4=7$. A vector $(1,2,0,3)$ has $\|w\|_2^2=14$.

Piece 2. Matrix inverse of a $2\times2$

For $A=\begin{bmatrix}a&b\\c&d\end{bmatrix}$ the determinant is $\det A=ad-bc$ and $A^{-1}=\dfrac1{\det A}\begin{bmatrix}d&-b\\-c&a\end{bmatrix}$ (swap the diagonal, negate the off-diagonal, divide by the determinant).

Example: $A=\begin{bmatrix}2&1\\1&3\end{bmatrix}$: $\det=5$, $A^{-1}=\tfrac15\begin{bmatrix}3&-1\\-1&2\end{bmatrix}$. Check: first row times first column $=\tfrac15(6-1)=1$ ✓.

Piece 3. Probability of the parameters (Bayes' rule again)

Before seeing data we hold a prior belief $P(w)$. After seeing data, the posterior is $P(w\mid\text{data})\propto P(\text{data}\mid w)\,P(w)$ (likelihood times prior). The MAP estimate is the $w$ with the largest posterior. Since $\log$ is increasing, maximise $\log P(\text{data}\mid w)+\log P(w)$, or minimise its negative.

Piece 4. Two bell shapes

DistributionDensity$-\log$ density (up to a constant)
Gaussian $N(0,\gamma^2)$$\propto e^{-w^2/(2\gamma^2)}$$\dfrac{w^2}{2\gamma^2}$
Laplace$(0,b)$$\dfrac1{2b}e^{-|w|/b}$$\dfrac{|w|}{b}$

Squares come from Gaussians; absolute values come from Laplace. That single fact explains Ridge versus Lasso.

Two more tools [ADDED]

Tool 5: a singular matrix and why the fix works

$XX^T$ is singular (has no inverse) when two features carry the same information, or when there are fewer points than features. Example: two copies of the same feature, $X=\begin{bmatrix}1&2&3\\1&2&3\end{bmatrix}$. Then $XX^T=\begin{bmatrix}14&14\\14&14\end{bmatrix}$ and $\det=14\cdot14-14\cdot14=0$. No inverse, so the plain formula $(XX^T)^{-1}Xy$ fails.

Adding $\lambda I$ with $\lambda=1$ gives $\begin{bmatrix}15&14\\14&15\end{bmatrix}$, $\det=225-196=29\ne0$. Now the inverse exists. That is the whole reason ridge is called a stabiliser: a small positive number on the diagonal makes the matrix invertible.

Tool 6: the "dead zone" function (soft threshold)

Write $(u)_+=\max(u,0)$. The soft threshold by $t$ is $S_t(a)=\operatorname{sign}(a)\,(|a|-t)_+$: shrink $|a|$ by $t$, but never below $0$. Examples with $t=0.5$: $S_t(3)=2.5$, $S_t(-1)=-0.5$, $S_t(0.3)=0$, $S_t(0.5)=0$, $S_t(0.9)=0.4$.

All the Lasso formulas on this page are soft thresholds. Remember it as: subtract $t$ from the size, floor at zero, keep the sign.

What is $S_{0.5}(-0.2)$?

$|-0.2|=0.2<0.5$, so the answer is $0$.

What is $S_{0.5}(-2)$?

$\operatorname{sign}=-1$ and $(2-0.5)=1.5$, so the answer is $-1.5$.

Worked example: a penalty as a prior

A Gaussian prior $w\sim N(0,\tau^2)$ has $-\log p(w)=\dfrac{w^2}{2\tau^2}+\text{const}$. A Laplace prior with scale $b$ has $-\log p(w)=\dfrac{|w|}{b}+\text{const}$. So a squared penalty comes from a Gaussian prior and an absolute-value penalty from a Laplace prior. Example: $\tau^2=0.5$ gives the penalty $w^2$ exactly.

Tips and tricks
  • $\lVert w\rVert_2^2$ adds squares; $\lVert w\rVert_1$ adds absolute values.
  • A penalty is added to the loss you minimise.
A penalised loss
measure the fit errormeasure the weight sizemultiply size by lambdaminimise the sum

4. Ridge regression: the formula, the arithmetic and what $\lambda$ does

Intuition

If least squares may choose any weights, noise can push them to huge values that fit the training points exactly. Ridge adds a spring pulling every weight toward $0$: a weight must "earn" its size by reducing the error enough.

Everyday analogy

A student can write any answer on a test, but each extra page costs money. They keep the pages that improve the grade the most and skip the rest. $\lambda$ is the price per unit of weight size.

Definition and derivation

Formula: ridge loss and solution

$$L_R(w)=\|X^Tw-y\|^2+\lambda\|w\|^2,\qquad \hat w_R=(XX^T+\lambda I)^{-1}Xy$$ $\lambda\ge0$ is the penalty strength, $I$ the $d\times d$ identity.

  1. Gradient: $\nabla L_R=2X(X^Tw-y)+2\lambda w$.
  2. Set to $0$: $XX^Tw+\lambda w=Xy$, i.e. $(XX^T+\lambda I)w=Xy$.
  3. For $\lambda>0$ the matrix $XX^T+\lambda I$ is always invertible, so $\hat w_R$ always exists (even when $XX^T$ is singular).

One feature

$\hat w_R=\dfrac{\sum x_iy_i}{\sum x_i^2+\lambda}$ and the plain solution is $\hat w_{MLE}=\dfrac{\sum x_iy_i}{\sum x_i^2}$. So $$\frac{\hat w_R}{\hat w_{MLE}}=\frac{\sum x_i^2}{\sum x_i^2+\lambda},\qquad \frac{\hat w_{MLE}}{\hat w_R}=\frac{\sum x_i^2+\lambda}{\sum x_i^2}.$$ The label vector $y$ cancels, so you can answer without knowing $y$.

What $\lambda$ does

$\lambda$Ridge weightEffect
$0$equals the MLEratio of norms $=1$
smallslightly shrunkclose to least squares
largestrongly shrunkrisk of underfitting
$\infty$goes to $0$$\|\hat w_R\|^2/\|\hat w\|^2\to0$

If several $w$ minimise the plain error (a flat valley), ridge picks the one with the smallest norm.

Worked example: Simple: one feature

Problem. $x=(1,-2,2)$, $y=(4,-7,9)$, $\lambda=3$.

What is asked. $\hat w_{MLE}$ and $\hat w_{ridge}$.

Idea / formula used. $\hat w=\dfrac{\sum x_iy_i}{\sum x_i^2+\lambda}$.

$\sum x_iy_i=4+14+18=36$ and $\sum x_i^2=1+4+4=9$.
MLE ($\lambda=0$): $36/9=4$.
Ridge: $36/(9+3)=3$.
Answer: $4$ and $3$ (ridge is smaller)
Common mistake: adding $\lambda$ to the numerator.
Worked example: Exam level: $2\times2$ ridge

Problem. $X=\begin{bmatrix}2&0\\1&1\end{bmatrix}$ (columns are data points), $y=(2,3)^T$, $\lambda=1$.

What is asked. $\hat w$.

Idea / formula used. $\hat w=(XX^T+\lambda I)^{-1}Xy$.

$XX^T=\begin{bmatrix}4&2\\2&2\end{bmatrix}$, so $XX^T+I=\begin{bmatrix}5&2\\2&3\end{bmatrix}$.
$Xy=(2\cdot2+0,\;1\cdot2+1\cdot3)=(4,5)$.
Determinant $15-4=11$; inverse $\tfrac1{11}\begin{bmatrix}3&-2\\-2&5\end{bmatrix}$.
$\hat w=\tfrac1{11}(12-10,\;-8+25)$.
Answer: $\hat w=(2/11,\;17/11)$
Common mistake: using $X^TX$ and $X^Ty$ when points are columns.
Worked example: Tricky: which product is it?

Problem. $X=\begin{bmatrix}1&2\\0&1\end{bmatrix}$ (columns are points), $y=(1,3)^T$, $\lambda=2$. A friend gets $(-3/17,\,13/17)$.

What is asked. The correct $\hat w$ and the friend's mistake.

Idea / formula used. Points are columns, so the matrix is $XX^T$ and the vector is $Xy$.

$XX^T=\begin{bmatrix}5&2\\2&1\end{bmatrix}$; adding $2I$ gives $\begin{bmatrix}7&2\\2&3\end{bmatrix}$.
$Xy=(1+6,\;3)=(7,3)$.
Determinant $21-4=17$; $\hat w=\tfrac1{17}(3\cdot7-2\cdot3,\;-2\cdot7+7\cdot3)$.
The friend used $X^TX$ and $X^Ty$.
Answer: $\hat w=(15/17,\;7/17)$
Common mistake: not checking whether rows or columns are the data points; if no option matches, check this first.

Common mistakes

How much does ridge shrink? [ADDED]

λ = 0: ratio 1 (no change)λ = 100: ratio 2/3λ = 200: ratio 1/2λ = 600: ratio 1/4penalty λratio ŵ ridge / ŵ least-squarestends to 0 as λ → ∞01002003004005006000.250.50.751
One feature with $\sum x^2=200$ (the data of the Aug 2023 Q9 pattern). The vertical axis is $\hat w_R/\hat w=\sum x^2/(\sum x^2+\lambda)$. Each red dot is a value you can compute by hand. The curve falls quickly at first and then slowly, and it never touches $0$.
$\lambda$$\hat w_R/\hat w$ for $\sum x^2=200$Reading
01.0000no penalty: same as least squares
0.10.9995almost no change
10.9950barely shrunk
100.9524about 5 percent smaller
1000.6667 = 2/3one third removed (the Aug 2023 Q9 value)
2000.5000when $\lambda=\sum x^2$ the weight halves

Rule of thumb: compare $\lambda$ with $\sum x^2$. If $\lambda\ll\sum x^2$ the penalty barely matters. If $\lambda\gg\sum x^2$ the weight is almost $0$. The "which $\lambda$ underfits most" question is therefore always answered by the largest $\lambda$ in the list: it shrinks most.

The running example, with numbers [ADDED]

One feature, $x=(1,2,3)$, $y=(2,3,5)$ (the data used in the linear regression topic). Here $\sum xy=23$ and $\sum x^2=14$, so $\hat w_R=23/(14+\lambda)$.

$\lambda$$\hat w_R=\frac{23}{14+\lambda}$$\hat w_R/\hat w$ with $\hat w=23/14$training SSE
01.64291.00000.214
11.53330.93330.382
51.21050.73682.831
100.95830.58336.774
300.52270.318217.780

The training error rises as $\lambda$ rises ($0.214\to17.780$). That is the price of shrinking: ridge accepts a worse fit on the training points in the hope of a better fit on new points.

Why $\lambda I$ and not something else: ridge as extra data [ADDED]

There is a neat way to see ridge. Add $d$ fake data points: the $j$-th fake point has feature $\sqrt\lambda$ in position $j$ and $0$ elsewhere, and label $0$. Fitting plain least squares to the real plus fake points gives exactly the ridge solution. Reason: the fake points add $\sum_j(\sqrt\lambda\,w_j-0)^2=\lambda\|w\|^2$ to the squared error. Check with the worked example below ($\lambda=1$): stacking $\begin{bmatrix}1&2&1&0\\3&4&0&1\end{bmatrix}$ with labels $(3,5,0,0)$ and solving the normal equations gives $(0.5429,\,0.8857)$, the same as the ridge formula.

Direction by direction: where ridge shrinks most [ADDED]

$XX^T$ has eigenvalues that measure how much data "supports" each direction. For $XX^T=\begin{bmatrix}5&11\\11&25\end{bmatrix}$ (the worked example) the trace is $30$ and the determinant is $4$, so the eigenvalues are $29.866$ and $0.134$. In the eigen-directions, ridge multiplies the least-squares coordinate by $\dfrac{e_i}{e_i+\lambda}$.

DirectionEigenvalue $e_i$Shrink factor $e_i/(e_i+1)$ at $\lambda=1$Meaning
strong (lots of data support)29.8660.9676almost untouched
weak (little data support)0.1340.1181shrunk to about a ninth

The check in code: rebuilding $\hat w_R$ from these two factors gives $(0.5429,\,0.8857)$, the same as the direct formula. Take-away: ridge trusts the well-supported directions and distrusts the poorly-supported ones. This is exactly why it helps when features are nearly copies of each other.

Duplicate features: ridge splits the weight equally [ADDED]

Take two copies of $x=(1,2,3)$ and $y=(2,3,5)$. Least squares cannot decide how to share the weight, since only $w_1+w_2=23/14$ matters (the matrix is singular, see Tool 5). Ridge with $\lambda=1$ gives $\hat w_R=(0.7931,\,0.7931)$, each exactly $23/29$. Among all weight pairs with the same fit, equal sharing has the smallest $\|w\|^2$, which is what ridge prefers. (Same idea as the PYQ statement "ridge picks the least-norm solution".)

Careful: ridge shrinks the size of $w$, not every coordinate [ADDED]

The length $\|\hat w_R\|$ falls steadily as $\lambda$ grows (the code checks this for $\lambda=0,\dots,120$ on the data of the path figure in the Lasso section). But an individual coordinate can rise. With two strongly correlated features there, $w_2$ goes from 0.137 (at $\lambda=0$) up to 0.774 (at $\lambda=10$), because ridge moves some weight from the "noisy" combination onto the other feature. So "all weights shrink" is a good rule for one feature and for the norm, but it is not a theorem for each coordinate when features are correlated.

Common mistakes, as a table [ADDED]

MistakeWhy it is wrongFix
Adding $\lambda$ to every entry of $XX^T$the penalty is $\lambda\|w\|^2$, whose gradient is $2\lambda w$, i.e. $\lambda I$add $\lambda$ only on the diagonal
Using $\lambda I$ of size $n\times n$$XX^T$ is $d\times d$ (features), not $n\times n$read $X$ as $(d,n)$ first; $I$ matches $d$
Penalising the label or the datathe penalty is on the weights $w$ onlywrite $\|w\|^2$ not $\|X\|^2$
Inverting the ratio$\hat w/\hat w_R=(\sum x^2+\lambda)/\sum x^2>1$; $\hat w_R/\hat w<1$decide which weight is on top before dividing
Saying the training error falls with $\lambda$the ridge weight is not the minimiser of the plain errortraining error rises with $\lambda$; validation error is U-shaped
Forgetting the factor 2 in the gradient when $\lambda$ has a $\tfrac12$ in frontconvention changes the final formulawrite the loss, differentiate, then solve; never recall by memory

Recall questions

$\sum x^2=50$, $\lambda=50$. What is $\hat w_R/\hat w$?

$50/(50+50)=0.5$.

Why is $XX^T+\lambda I$ invertible for $\lambda>0$?

$XX^T$ only has eigenvalues $\ge0$. Adding $\lambda$ makes every eigenvalue at least $\lambda>0$, so none is zero and the determinant is nonzero.

Does the ridge training error go up or down as $\lambda$ grows?

Up (or stays equal). The plain least-squares weight is the unique minimiser of training error; ridge moves away from it.

Tips and tricks
  • In one dimension with loss $\sum(y_i-wx_i)^2+\lambda w^2$, $w=\dfrac{\sum x_iy_i}{\sum x_i^2+\lambda}$.
  • $\lambda=0$ gives least squares; very large $\lambda$ pushes $w$ toward 0.
Memory line

Ridge shrinks every weight; larger $\lambda$ shrinks more.

5. The constrained view and choosing a weight vector

Picture it

A dog on a leash gets as close to the food as the leash allows.

Intuition

Penalty form and constraint form are two ways to say the same thing. "Keep the weights inside a ball of squared radius $\theta$ and minimise the error there" is ridge with some $\lambda$ that depends on $\theta$. A small ball (small $\theta$) means strong shrinkage (large $\lambda$).

Formula: constrained ridge

$$\min_w\ \|X^Tw-y\|^2\quad\text{subject to}\quad\|w\|^2\le\theta$$ Among all weight vectors that satisfy $\|w\|^2\le\theta$ (the feasible ones), ridge picks the one with the smallest error.

How to answer "which candidate is selected?"

  1. Compute $\|w\|^2$ for every candidate.
  2. Cross out those with $\|w\|^2>\theta$ (not allowed).
  3. Among the rest choose the smallest error (MSE or SSE; same ordering).
Worked example: Exam level: pick the candidate

Problem. $\theta=6$. Candidates with training MSE: $w_1=(2,1,1)$, $5$; $w_2=(1,1,1)$, $7$; $w_3=(3,2,1)$, $3$; $w_4=(2,2,0)$, $4$.

What is asked. Which solves: minimise MSE subject to $\|w\|_2^2\le\theta$?

Idea / formula used. First remove candidates that break the budget, then compare errors.

Squared norms: $6,3,14,8$.
Only $w_1$ and $w_2$ satisfy $\le6$.
Of these, $w_1$ has the smaller MSE ($5<7$).
Answer: $w_1$
Common mistake: picking $w_3$ because its MSE is lowest.

Limits of $\lambda$

Trap: both ends

For $\lambda=0$ the ratio is $1$ (not $0$); for $\lambda=\infty$ it is $0$ (not $1$). Remember: no penalty means no change.

Penalty form and constraint form: the dictionary [ADDED]

For one feature, $x=(1,2,3)$, $y=(2,3,5)$, least squares gives $\hat w=23/14\approx1.6429$, so $\hat w^2\approx2.6990$. If the budget $\theta$ is at least that, the budget is not binding and the answer is plain least squares ($\lambda=0$). If $\theta$ is smaller, the solution sits on the boundary $w=\sqrt\theta$, and the matching penalty is $\lambda=23/\sqrt\theta-14$ (from $23/(14+\lambda)=\sqrt\theta$).

Budget $\theta$Allowed $|w|$Chosen $w$Matching $\lambda$Reading
4$\le2$1.6429 (budget not used)0budget too loose to matter
2.25$\le1.5$1.50001.3333on the boundary
1$\le1$1.00009.0000tighter budget, larger $\lambda$

Direction rule: smaller $\theta$ (tighter budget) corresponds to larger $\lambda$ (higher fee). The two numbers move in opposite directions.

The candidate-selection procedure as a flow [ADDED]

Variations to be ready for [ADDED] (not PYQs)

VariationWhat changesAnswer rule
Two feasible candidates have equal errora tiethe question will break the tie by another rule (smaller norm); read for it
No candidate is feasiblethe budget is too smallthe zero vector is always feasible; with $w=0$ the model predicts $0$
The budget is bigger than every candidate normconstraint not activepick the smallest error overall (plain least squares ordering)
Constraint $\|w\|_1\le\theta$norm changes to the sum of absolute valuesrecompute the norms; the rest is identical

Which $\lambda$ underfits? A ladder [ADDED]

For the Aug 2023 Q9 pattern ($\sum x^2=200$) the shrink factor at $\lambda=0,0.1,1,10,100$ is $1.0000, 0.9995, 0.9950, 0.9524, 0.6667$. The most shrunk, hence the most underfit, is the largest $\lambda$, $100$. Rule: underfit = too much shrinkage = largest $\lambda$. Overfit = too little = smallest $\lambda$ (0).

A tighter budget $\theta$ means a larger or smaller $\lambda$?

Larger. Tight budget, strong shrinkage.

Is a candidate with $\|w\|^2=\theta$ exactly allowed?

Yes. The constraint is $\le\theta$, so the boundary is allowed.

Tips and tricks
  • First discard weight vectors that break the constraint, then compare the loss of the rest.
  • If the least-squares solution already satisfies the constraint, it is the answer.
Choosing a weight vector
check the constraintdiscard vectors that break itcompute the loss of the resttake the smallest

6. Lasso ($L_1$): sparsity, the diamond picture and comparing weights

Intuition

Ridge shrinks every weight a bit; Lasso can shrink some weights exactly to $0$, which deletes a feature. This is automatic feature selection.

Everyday analogy

Think of the set of allowed weights as a shape. For $L_2$ it is a round ball, for $L_1$ it is a diamond with sharp corners on the axes. The error contours are ovals that grow until they first touch the shape. A round ball is touched at a generic point; a diamond is usually touched at a corner, where one coordinate is $0$.

Formula: Lasso loss

$$L_{lasso}(w)=\|X^Tw-y\|^2+\lambda\|w\|_1,\qquad \|w\|_1=\sum_j|w_j|$$ There is no simple closed form in general (the absolute value has a corner at $0$).

Reading the contour figure

Blue diamond $|w_1|+|w_2|\le1$; oval contours of the squared error $f$ lie to the right; the outer oval $f=c_1$ touches the diamond at the corner $(1,0)$. Then:

Which weight vector is which?

MethodSignature in the weights
Plain linear regressionlargest magnitudes, no zeros
Ridgeshrunk toward $0$ but none exactly $0$
Lassosome entries exactly $0$ (sparse)

Example: $w_1=(0.32,-0.12,\mathbf0,0.42,\dots)$ has an exact zero: Lasso. $w_2$ has the biggest entries ($0.38,-0.31,\dots$): plain regression. $w_3$ has small entries with none zero: Ridge.

Advantages of $L_1$

Worked example: Simple: loss at the optimum

Problem. The optimum of a Lasso problem is $w=(0,-3)$, where the squared-error part equals $c_1$. Penalty weight $\lambda$.

What is asked. The total loss.

Idea / formula used. Total $=f+\lambda\|w\|_1$.

$\|w\|_1=|0|+|-3|=3$.
Total $=c_1+3\lambda$.
Answer: $c_1+3\lambda$
Common mistake: using $\|w\|_2^2=9$, which is the ridge penalty.
Trap: sparsity is not guaranteed

Corners make zeros likely, not certain. And "the weight is $0$" tells you to discard that feature for this $\lambda$.

Seeing why corners produce zeros [ADDED]

w₁w₂least squaresRidge: ball ‖w‖² ≤ 1touches at (0.92, 0.38)w₁w₂least squaresLasso: diamond |w₁|+|w₂| ≤ 1touches at the corner (1, 0)
Both panels use the same error ovals (dashed rings grow outward from the black dot, the least-squares point; the solid red ring is the first one that touches the allowed region). Left: the round ridge ball is touched at a smooth point, so both weights are non-zero. Right: the lasso diamond is touched at the corner $(1,0)$, so $w_2=0$. The code finds both touch points by searching along the boundary.

Why does the diamond tend to be touched at a corner? An expanding oval first meets the region at the point of the region that is "closest" in oval distance. The diamond sticks out furthest along the axes, so the oval usually reaches a corner first. The ball has no corners, so no coordinate is singled out.

The one-feature lasso, with an exact formula [ADDED]

Minimise $\sum(wx_i-y_i)^2+\lambda|w|$. Differentiating $\sum(wx_i-y_i)^2$ gives $2\sum x_i(wx_i-y_i)=2Sw-2\sum xy$ with $S=\sum x^2$. The absolute value has slope $+\lambda$ for $w>0$ and $-\lambda$ for $w<0$, and a corner at $0$. Setting the total slope to zero on each side gives the soft threshold $$\hat w_L=\operatorname{sign}(s)\,\frac{(|s|-\lambda)_+}{2S},\qquad s=2\sum x_iy_i.$$ So the weight is exactly $0$ whenever $\lambda\ge2\sum xy$. Running example: $s=46$, $2S=28$, so $\hat w_L=(46-\lambda)/28$ for $\lambda\le46$ and $0$ after.

$\lambda$Lasso $\hat w_L$Ridge $\hat w_R$Note
01.64291.6429both equal least squares
101.28570.9583
300.57140.5227
460.00000.3833lasso reaches exactly 0
600.00000.3108lasso stays 0; ridge is still positive

The code checks each row against a brute-force search for the minimiser of the loss.

Shrinkage functions: ridge scales, lasso subtracts [ADDED]

-3-2-1123-3-2-1123least-squares weight apenalised weightno penalty (slope 1)Ridge: slope 0.50Lasso: shifted toward 0, flat dead zonedead zone−0.50.5
For features that do not overlap ($XX^T=I$) the least-squares weight is $a=Xy$. Ridge returns $a/(1+\lambda)$: a straight line tilted down. Lasso returns the soft threshold $\operatorname{sign}(a)(|a|-\lambda/2)_+$: the line shifted toward zero with a flat piece (the dead zone) where the weight is exactly $0$. Drawn for $\lambda=1$.
LS weight $a$Ridge $a/2$Lasso (threshold $0.5$)
-3-1.500-2.500
-1-0.500-0.500
-0.4-0.2000.000
0.30.1500.000
0.50.2500.000
0.90.4500.400
2.51.2502.000

Reading the table: ridge halves everything. Lasso removes $0.5$ from the size and kills anything whose size is at most $0.5$ ($-0.4$, $0.3$, $0.5$ all become $0$).

Coefficient paths: a complete picture of both [ADDED]

020406080100120-112penalty strength λweight valueLasso w₁Ridge w₁Ridge w₂ (never exactly 0)Lasso w₂ = 0w₂ hits 0 at λ = 49
Two features, six data points, strongly correlated (data in the code, drawn from this section): $x_1=(1,2,3,4,5,6)$, $x_2=(2,1,4,3,6,5)$, $y=(3.1,4.2,6.3,8.4,10.1,12.3)$. Solid lines are $w_1$, dashed are $w_2$. Blue: ridge. $w_1$ glides down smoothly; $w_2$ first rises (the features are correlated; see the careful note in the Ridge section) and then falls; neither ever equals exactly $0$. Red: lasso, $w_2$ is exactly $0$ from $\lambda=49$ onward, so the model has deleted feature 2.

Numbers behind the picture: least squares $w=(1.937,\ 0.137)$; lasso at $\lambda=20$: $(1.881,\ 0.081)$; lasso at $\lambda=60$: $(1.740,\ 0)$ (feature 2 deleted).

L1 loss versus L1 penalty: a table to prevent a common confusion [ADDED]

L1 lossL1 penalty (Lasso)
What gets the absolute value?the residuals $|w^Tx_i-y_i|$the weights $|w_j|$
Comes fromLaplace noise on $y$ (MLE)Laplace prior on $w$ (MAP)
Effectrobust to outliers in $y$sparse weights, feature selection
Written as$\min\sum_i|w^Tx_i-y_i|$$\min\|X^Tw-y\|^2+\lambda\|w\|_1$

Reading a lasso picture: a checklist [ADDED]

Common mistakes, as a table [ADDED]

MistakeFix
Saying Lasso always gives exact zerosit gives zeros when $\lambda$ is large enough (or the corner is touched); a very small $\lambda$ can leave all weights non-zero
Saying Ridge gives sparse modelsridge shrinks but does not delete; exact zeros are a lasso property
Using $\|w\|^2$ for the penalty of a lasso questionthe lasso penalty is $\sum|w_j|$; for $w=(1,0)$ both are 1 but the rule differs
Believing the lasso has a closed form like ridgein general it does not; only the special cases above are closed-form
Choosing the inner oval as the answerthe inner oval is not reachable inside the region; the touching one is

Recall questions

In the diamond picture the ovals touch at $(0,1)$. Which feature is discarded?

Feature 1, because $w_1=0$.

$\lambda\ge2\sum xy$ in one-feature Lasso. What is $\hat w_L$?

Exactly $0$.

Is a Lasso solution always sparse?

No. Sparsity is likely and increases with $\lambda$, but it is not guaranteed for every $\lambda$.

Interactive explorer

One feature with $\sum x_i^2=4$ and $\sum x_iy_i=8$, so least squares gives $w=2$. Raise the penalty and compare: ridge shrinks the weight gradually, lasso drives it to exactly $0$ at $\lambda=16$.

Tips and tricks
  • The diamond has corners on the axes, which is why some weights become exactly 0.
  • Compute both norms of each option before comparing.
Memory line

Lasso can make weights exactly zero.

How Lasso is actually solved [ADDED]

With several features, Lasso has no closed-form formula in general (the one-feature formula is the special easy case). $|w|$ has a corner at $0$, so it has no single slope there. Any slope between $-1$ and $+1$ is allowed at the corner; these are called sub-gradients, and iterative sub-gradient methods are used. Ridge, by contrast, always has $(XX^T+\lambda I)^{-1}Xy$.

7. MAP: regularisation as a prior

Intuition

MLE asks "which $w$ makes the data most likely?". MAP asks "which $w$ is most believable after seeing the data, given what I believed before?". A prior that says "weights are probably small" produces exactly a ridge penalty; a prior with sharp peak at $0$ (Laplace) produces a Lasso penalty.

Derivation (Gaussian prior, Gaussian noise)

  1. Noise: $y_i\mid x_i,w\sim N(w^Tx_i,\sigma^2)$. Prior: $w\sim N(0,\gamma^2I)$.
  2. $-\log$ posterior $=\dfrac1{2\sigma^2}\|y-X^Tw\|^2+\dfrac1{2\gamma^2}\|w\|^2+\text{const}$.
  3. Multiply by $2\sigma^2$ (does not move the minimiser): $\|y-X^Tw\|^2+\dfrac{\sigma^2}{\gamma^2}\|w\|^2$.
  4. So $\hat w_{MAP}$ is ridge with $\boxed{\lambda=\sigma^2/\gamma^2}$.
Formula: MAP and regularisation
Prior on $w$PenaltyName
Gaussian $N(0,\gamma^2I)$$\lambda\|w\|_2^2$, $\lambda=\sigma^2/\gamma^2$Ridge
Laplace$(0,b)$ (with unit-variance noise, $b=2/\lambda$)$\lambda\|w\|_1$Lasso

Tight prior (small $\gamma^2$) means large $\lambda$: strong shrinkage. Many data points make the likelihood dominate, so MAP approaches the MLE.

Laplace prior worked out

Noise $N(0,1)$: $-\log\text{lik}=\tfrac12\sum(w^Tx_i-y_i)^2$. Prior Laplace$(0,b)$ with $b=2/\lambda$: $-\log\text{prior}=\|w\|_1/b=\tfrac\lambda2\|w\|_1$. Sum $=\tfrac12\big[\sum(\cdot)^2+\lambda\|w\|_1\big]$, so $\hat w_{MAP}=\arg\min\sum(w^Tx_i-y_i)^2+\lambda\|w\|_1$. It is an argmin (never argmax, since we minimise a negative log).

The $\tfrac12\lambda$ convention

If the ridge loss is written $\tfrac12\sum(\cdot)^2+\tfrac\lambda2\|w\|^2$ and the model is $y\sim N(w^Tx,1)$ with prior $N(0,\sigma^2I)$, then $-\log$ posterior $=\tfrac12\sum(\cdot)^2+\tfrac1{2\sigma^2}\|w\|^2$. Matching terms gives $\lambda=1/\sigma^2$. (Compare: with a general noise variance $s^2$ and prior variance $\gamma^2$, $\lambda=s^2/\gamma^2$; here $s^2=1$ and $\gamma^2=\sigma^2$.)

MLE versus MAP: which is better?

The MLE is unbiased but can have large variance. Ridge/MAP is biased but with smaller variance; for some $\lambda>0$ its mean squared error is lower than the MLE's. It does not hold for every $\lambda$ and it does not always hold "because it uses prior information".

Laplace noise

If the noise is Laplace instead of Gaussian, the MLE minimises $\sum|r_i|$ (absolute errors) rather than squares. Squares grow quadratically with a big error, so outliers dominate; absolute errors grow linearly, so that fit is more robust. (This is a loss choice, not a penalty on $w$.)

Worked example: Exam level: $\lambda$ from variances

Problem. $y\mid x\sim N(w^Tx,\sigma^2)$ with $\sigma^2=4$, prior $w\sim N(0,\gamma^2I)$ with $\gamma^2=0.5$.

What is asked. The ridge $\lambda$ for the loss $\|X^Tw-y\|^2+\lambda\|w\|^2$.

Idea / formula used. $\lambda=\sigma^2/\gamma^2$.

$\lambda=4/0.5=8$.
Noisy data (large $\sigma^2$) or a tight prior (small $\gamma^2$) both increase $\lambda$.
Answer: $8$
Common mistake: inverting the ratio and answering $1/8$.
Trap: same words, different symbols

Different papers use $\sigma^2$ for the noise or for the prior. Always rewrite the two variances yourself: $\lambda=(\text{noise variance})/(\text{prior variance})$.

The tug of war between data and prior [ADDED]

MLE 1.643MAP 1.533prior centre 00123weight wnegative log: smaller is betterdata termprior termsum (posterior)
One weight, data $x=(1,2,3)$, $y=(2,3,5)$, noise variance $\sigma^2=1$, prior variance $\gamma^2=1$. Blue: the data term (it is lowest at the least-squares value $23/14=1.643$; shifted by a constant so its minimum is 0). Grey dashed: the prior term (lowest at 0). Red: their sum. The red minimum, the MAP estimate $23/15=1.533$, lies between the two.

With $\sigma^2=\gamma^2=1$ we have $\lambda=\sigma^2/\gamma^2=1$, so $\hat w_{MAP}=23/(14+1)=1.5333$. With a tighter prior $\gamma^2=0.25$, $\lambda=4$ and $\hat w_{MAP}=23/18=1.2778$. Tighter belief, bigger pull towards $0$.

The translation table for every common convention [ADDED]

Exam questions write the loss in different ways. The factor $\tfrac12$ is the usual source of error. Let $s^2$ be the noise variance, $\gamma^2$ the Gaussian prior variance and $b$ the Laplace scale. Start from $-\log\text{posterior}=\dfrac{1}{2s^2}\text{SSE}+\text{penalty term}$ and multiply by a constant to match the way the loss is written.

PriorWritten loss$\lambda$ in terms of $s^2,\gamma^2,b$Example check
Gaussian $N(0,\gamma^2I)$$\text{SSE}+\lambda\|w\|^2$$\lambda=s^2/\gamma^2$$s^2=2,\gamma^2=0.5\Rightarrow\lambda=4$
Gaussian $N(0,\gamma^2I)$$\tfrac12\text{SSE}+\tfrac\lambda2\|w\|^2$$\lambda=s^2/\gamma^2$ (same)same numbers, $\lambda=4$
Laplace$(0,b)$$\text{SSE}+\lambda\|w\|_1$$\lambda=2s^2/b$$s^2=2,b=0.5\Rightarrow\lambda=8$
Laplace$(0,b)$$\tfrac12\text{SSE}+\lambda\|w\|_1$$\lambda=s^2/b$same numbers, $\lambda=4$

All four rows are checked in code by minimising both versions of the loss on a grid and comparing the minimisers. Special cases from the PYQs: unit noise ($s^2=1$) with the $\tfrac12$ form and prior variance written $\sigma^2$ gives $\lambda=1/\sigma^2$. Laplace$(0,2/\lambda)$ with unit noise gives $\text{SSE}+\lambda\|w\|_1$ (since $2s^2/b=2/(2/\lambda)=\lambda$).

More data, weaker prior [ADDED]

Repeat the data of the running example $k$ times. Then $\sum x^2=14k$ and $\sum xy=23k$, and MAP with $\lambda=1$ is $23k/(14k+1)$.

Copies $k$MAP $23k/(14k+1)$MLE $23/14$
11.53331.6429
101.63121.6429
1001.64171.6429

As the data grows, the likelihood term grows with it and the fixed prior term matters less, so MAP approaches the MLE. This is also why regularisation matters most when data is scarce.

The pattern behind the MSE statements [ADDED]

StatementTrue?Reason
MLE has lower MSE than MAP because it is unbiasedNoMSE = bias² + variance; MAP adds some bias but cuts variance, and for some $\lambda$ the total falls
MAP always beats MLE because it uses prior informationNoa bad prior or a large $\lambda$ can hurt; "always" is too strong
For some $\lambda>0$, ridge has smaller MSE than MLEYesa small enough shrinkage always trades a little bias for a larger variance reduction
Under Gaussian noise the MLE is the least-squares estimateYesthe NLL is a constant plus SSE over $2\sigma^2$

Recall questions

Prior variance gets smaller. Does $\lambda$ grow or shrink?

Grow. $\lambda=s^2/\gamma^2$.

Laplace prior gives which penalty and which method?

An $L_1$ penalty, so Lasso. It is an $\arg\min$ of the negative log posterior.

What happens to the MAP estimate as the data set grows?

It moves toward the MLE because the data term dominates the fixed prior term.

Tips and tricks
  • A Gaussian prior gives ridge; a Laplace prior gives lasso.
  • A tighter prior means stronger regularisation.

Practise this topic →

Weeks covering this topic

Other MLT topics