Regularisation, priors, sparsity
Open the interactive lessons →Ridge, Lasso and MAP past questions
Contents
- Orientation: what you will learn and why
- Big picture: one idea in three forms, and the comparison table
- Start here: the pieces you need
- Ridge regression: the formula, the arithmetic and what $\lambda$ does
- The constrained view and choosing a weight vector
- Lasso ($L_1$): sparsity, the diamond picture and comparing weights
- 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
- Write the ridge loss and compute $\hat w_R=(XX^T+\lambda I)^{-1}Xy$ by hand, including $1\times1$ and $2\times2$ cases.
- Predict how the ridge weight and its norm behave for $\lambda=0$, small, large and $\lambda\to\infty$.
- Use the constrained form $\min\text{SSE}$ subject to $\|w\|^2\le\theta$ and pick the winning weight vector.
- Read the contour picture of Lasso: the corner of the diamond, a weight forced to zero, and the total loss at the optimum.
- Recognise Lasso, Ridge and plain regression from their weight vectors, and state what $L_1$ is good for.
- Derive $\lambda$ from a Gaussian or Laplace prior and a Gaussian noise model (MAP), and say when ridge beats the MLE.
Why this topic matters for Quiz 2
Counted only from the PYQs in this project (not a prediction):
| What the PYQs ask | PYQs | Marks |
|---|---|---|
| Ridge: formula, arithmetic and the role of lambda | 5 | 20.5 |
| Constrained form and choosing a weight vector | 3 | 10 |
| Lasso (L1): sparsity, contours, comparing weights | 7 | 13 |
| MAP: regularisation as a prior | 6 | 19 |
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.
Step through every worked example, do the quick checks, then attempt each PYQ before opening its solution.
What is new in this upgrade [ADDED]
- A one-page big picture section (next) with a 2 by 3 grid, a five-way comparison table and a ridge-versus-lasso confusion table.
- Figures: how much ridge shrinks, why the diamond gives zeros, shrinkage functions, coefficient paths, and the data-versus-prior tug of war.
- Exact one-feature lasso, the soft threshold, penalty-constraint dictionary, translation table for every $\tfrac12$ convention, mistake tables, recall questions and a revision flowchart. Everything new is tagged [ADDED].
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.
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
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 squares | Ridge ($L_2$) | Lasso ($L_1$) | MAP, Gaussian prior | MAP, 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 prior | MAP with Laplace prior | Ridge, $\lambda=\sigma^2/\gamma^2$ | Lasso, $\lambda=2\sigma^2/b$ |
| Constraint shape | none | ball $\|w\|^2\le\theta$ | diamond $\|w\|_1\le\theta$ | ball | diamond |
| 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) | no | yes | no | yes |
| Needs $XX^T$ invertible? | yes | no: $XX^T+\lambda I$ is invertible for $\lambda>0$ | no | no | no |
| Effect on size of $w$ | largest | smaller, smoothly | smaller, some become 0 | smaller | smaller, some 0 |
| Overfitting risk | highest | lower | lower | lower | lower |
| 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
| Question | Ridge | Lasso |
|---|---|---|
| What does the penalty add up? | squares of the weights | absolute values of the weights |
| Shape of the allowed region | round ball | diamond with corners on the axes |
| Where do the error ovals usually touch? | a smooth point: no weight is exactly 0 | a corner: one weight is exactly 0 |
| Prior it corresponds to | Gaussian (bell, smooth top) | Laplace (sharp peak at 0) |
| Good when | many features all matter a little; features are correlated | only a few features matter; you want to delete the rest |
| Weakness | keeps every feature, so the model is not sparse | no simple formula; among very similar features it may keep one arbitrarily |
Mnemonics and recognition cues [ADDED]
- Round = Ridge = Rarely zero. Lines (diamond) = Lasso = Loses features.
- L-numbers: $L_2$ squares (two), $L_1$ absolute values (one). Gaussian has a square in its exponent, Laplace has an absolute value.
- "Large lambda, small weights": a big fee makes the model keep only small weights. $\lambda=0$ means no fee.
- Ridge adds $\lambda$ on the diagonal: "ridge" is the raised line along the diagonal of the matrix.
- y cancels in a ratio: for one feature, $\hat w_R/\hat w=\sum x^2/(\sum x^2+\lambda)$ contains no $y$.
Analogy and its limit [ADDED]
| Analogy | What it explains well | Where it breaks |
|---|---|---|
| A fee per page of answer | why large weights must "earn" their size | a 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 0 | why the weight shrinks smoothly as $\lambda$ grows | a 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.
- 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
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
| Distribution | Density | $-\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]
$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.
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$.
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.
- $\lVert w\rVert_2^2$ adds squares; $\lVert w\rVert_1$ adds absolute values.
- A penalty is added to the loss you minimise.
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.
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
$$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.
- Gradient: $\nabla L_R=2X(X^Tw-y)+2\lambda w$.
- Set to $0$: $XX^Tw+\lambda w=Xy$, i.e. $(XX^T+\lambda I)w=Xy$.
- 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 weight | Effect |
|---|---|---|
| $0$ | equals the MLE | ratio of norms $=1$ |
| small | slightly shrunk | close to least squares |
| large | strongly shrunk | risk 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.
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}$.
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$.
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$.
Common mistakes
- Adding $\lambda$ to every entry of $XX^T$ instead of only the diagonal.
- Penalising the intercept as if it were an ordinary weight (not examined here).
- Believing larger $\lambda$ always improves test error; too large underfits.
How much does ridge shrink? [ADDED]
| $\lambda$ | $\hat w_R/\hat w$ for $\sum x^2=200$ | Reading |
|---|---|---|
| 0 | 1.0000 | no penalty: same as least squares |
| 0.1 | 0.9995 | almost no change |
| 1 | 0.9950 | barely shrunk |
| 10 | 0.9524 | about 5 percent smaller |
| 100 | 0.6667 = 2/3 | one third removed (the Aug 2023 Q9 value) |
| 200 | 0.5000 | when $\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 |
|---|---|---|---|
| 0 | 1.6429 | 1.0000 | 0.214 |
| 1 | 1.5333 | 0.9333 | 0.382 |
| 5 | 1.2105 | 0.7368 | 2.831 |
| 10 | 0.9583 | 0.5833 | 6.774 |
| 30 | 0.5227 | 0.3182 | 17.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}$.
| Direction | Eigenvalue $e_i$ | Shrink factor $e_i/(e_i+1)$ at $\lambda=1$ | Meaning |
|---|---|---|---|
| strong (lots of data support) | 29.866 | 0.9676 | almost untouched |
| weak (little data support) | 0.134 | 0.1181 | shrunk 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]
| Mistake | Why it is wrong | Fix |
|---|---|---|
| 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 data | the penalty is on the weights $w$ only | write $\|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 error | training error rises with $\lambda$; validation error is U-shaped |
| Forgetting the factor 2 in the gradient when $\lambda$ has a $\tfrac12$ in front | convention changes the final formula | write 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.
- 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.
Ridge shrinks every weight; larger $\lambda$ shrinks more.
5. The constrained view and choosing a weight vector
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$).
$$\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?"
- Compute $\|w\|^2$ for every candidate.
- Cross out those with $\|w\|^2>\theta$ (not allowed).
- Among the rest choose the smallest error (MSE or SSE; same ordering).
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.
Limits of $\lambda$
- $\lambda=0$: ridge equals least squares, $\|\hat w_R\|^2/\|\hat w\|^2=1$.
- $\lambda=\infty$: $\hat w_R=0$, ratio $0$.
- Moving $\lambda$ from small to large moves from overfit to underfit; the best value is chosen on validation data.
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) | 0 | budget too loose to matter |
| 2.25 | $\le1.5$ | 1.5000 | 1.3333 | on the boundary |
| 1 | $\le1$ | 1.0000 | 9.0000 | tighter 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]
- Step 1: write $\|w\|^2$ for every candidate (sum of squares of its entries).
- Step 2: keep candidates with $\|w\|^2\le\theta$. The boundary counts as allowed.
- Step 3: among the survivors pick the smallest error (MSE or SSE: same order).
- Step 4: if the question says "$L_1$ constraint", use $\|w\|_1=\sum|w_j|$ instead. Everything else is the same.
Variations to be ready for [ADDED] (not PYQs)
| Variation | What changes | Answer rule |
|---|---|---|
| Two feasible candidates have equal error | a tie | the question will break the tie by another rule (smaller norm); read for it |
| No candidate is feasible | the budget is too small | the zero vector is always feasible; with $w=0$ the model predicts $0$ |
| The budget is bigger than every candidate norm | constraint not active | pick the smallest error overall (plain least squares ordering) |
| Constraint $\|w\|_1\le\theta$ | norm changes to the sum of absolute values | recompute 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.
- 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.
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.
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$.
$$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:
- The problem is Lasso (a diamond means $L_1$).
- The optimal point is $(w_1,w_2)=(1,0)$, so $w_2=0$ and feature 2 can be discarded.
- The oval $f=c_1$ (touching) has larger error than the inner oval $f=c_2$ (nearer the unconstrained best at the centre of the ovals), so $c_1>c_2$.
- Total loss at the optimum $=f+\lambda\|w\|_1=c_1+\lambda\cdot1=c_1+\lambda$.
Which weight vector is which?
| Method | Signature in the weights |
|---|---|
| Plain linear regression | largest magnitudes, no zeros |
| Ridge | shrunk toward $0$ but none exactly $0$ |
| Lasso | some 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$
- Reduces overfitting (a penalty limits complexity).
- Produces sparse models (feature selection).
- It does not "always improve accuracy on large data" and it does not increase complexity.
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$.
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]
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 |
|---|---|---|---|
| 0 | 1.6429 | 1.6429 | both equal least squares |
| 10 | 1.2857 | 0.9583 | |
| 30 | 0.5714 | 0.5227 | |
| 46 | 0.0000 | 0.3833 | lasso reaches exactly 0 |
| 60 | 0.0000 | 0.3108 | lasso 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]
| LS weight $a$ | Ridge $a/2$ | Lasso (threshold $0.5$) |
|---|---|---|
| -3 | -1.500 | -2.500 |
| -1 | -0.500 | -0.500 |
| -0.4 | -0.200 | 0.000 |
| 0.3 | 0.150 | 0.000 |
| 0.5 | 0.250 | 0.000 |
| 0.9 | 0.450 | 0.400 |
| 2.5 | 1.250 | 2.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]
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 loss | L1 penalty (Lasso) | |
|---|---|---|
| What gets the absolute value? | the residuals $|w^Tx_i-y_i|$ | the weights $|w_j|$ |
| Comes from | Laplace noise on $y$ (MLE) | Laplace prior on $w$ (MAP) |
| Effect | robust 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]
- Diamond means $L_1$ (Lasso). Ball (circle) means $L_2$ (Ridge).
- The point where the outermost-needed oval touches the region is the answer; read its coordinates.
- A coordinate that is $0$ at that point means that feature is discarded.
- An oval that is farther from the centre of the ovals has a larger error. The oval that touches has a larger error than any oval inside it.
- Total penalised loss at the touch point is the error value of that oval $+\ \lambda\|w\|_1$.
Common mistakes, as a table [ADDED]
| Mistake | Fix |
|---|---|
| Saying Lasso always gives exact zeros | it 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 models | ridge shrinks but does not delete; exact zeros are a lasso property |
| Using $\|w\|^2$ for the penalty of a lasso question | the 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 ridge | in general it does not; only the special cases above are closed-form |
| Choosing the inner oval as the answer | the 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$.
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$.
- The diamond has corners on the axes, which is why some weights become exactly 0.
- Compute both norms of each option before comparing.
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)
- Noise: $y_i\mid x_i,w\sim N(w^Tx_i,\sigma^2)$. Prior: $w\sim N(0,\gamma^2I)$.
- $-\log$ posterior $=\dfrac1{2\sigma^2}\|y-X^Tw\|^2+\dfrac1{2\gamma^2}\|w\|^2+\text{const}$.
- Multiply by $2\sigma^2$ (does not move the minimiser): $\|y-X^Tw\|^2+\dfrac{\sigma^2}{\gamma^2}\|w\|^2$.
- So $\hat w_{MAP}$ is ridge with $\boxed{\lambda=\sigma^2/\gamma^2}$.
| Prior on $w$ | Penalty | Name |
|---|---|---|
| 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$.)
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$.
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]
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.
| Prior | Written 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$ |
|---|---|---|
| 1 | 1.5333 | 1.6429 |
| 10 | 1.6312 | 1.6429 |
| 100 | 1.6417 | 1.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]
| Statement | True? | Reason |
|---|---|---|
| MLE has lower MSE than MAP because it is unbiased | No | MSE = bias² + variance; MAP adds some bias but cuts variance, and for some $\lambda$ the total falls |
| MAP always beats MLE because it uses prior information | No | a bad prior or a large $\lambda$ can hurt; "always" is too strong |
| For some $\lambda>0$, ridge has smaller MSE than MLE | Yes | a small enough shrinkage always trades a little bias for a larger variance reduction |
| Under Gaussian noise the MLE is the least-squares estimate | Yes | the 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.
- A Gaussian prior gives ridge; a Laplace prior gives lasso.
- A tighter prior means stronger regularisation.