◈ quant roadmapPart 3 · Ch 22/45
Quantitative Finance — the Mathematics of Markets · chapter 22

22Bias–Variance & Regularization

Chapter 21 left us holding a thermometer and no medicine. We can measure the gap between fit and prediction, and we watched the test error fall, turn and climb. What we cannot do is say why the right arm rises, in parts we could attack one at a time. This chapter builds those parts, and the sentence it turns on is one nobody says out loud. Your fitted model is not a thing you built. It is a draw you got. Sample another year from the same world, run the identical code, and a different function comes out. Once you can see that spray of functions, the error at a point you have never visited splits into exactly three pieces: how far the average of those functions sits from the truth, how widely they scatter around that average, and the noise nobody can touch. Only the first two are yours, and they move in opposite directions as you hand the fit more freedom. So the whole craft is a purchase. You spend a little bias to buy back a lot of variance. Regularization is that purchase made deliberately, on a dial rather than a switch.

Look at what this page stands on, because almost all of it is already yours. Chapter 21 gave us the law that fitting is searching, and the toll that comes with it: the optimism you are charged is set by the size of the search. It gave us the U-curve, watched rather than explained. It gave us the p ≫ n regime and named three exits from it. Chapter 20 gave us Var(β̂) = σ²(XᵀX)⁻¹, the collinearity canyon and the bootstrap. Chapter 16 gave us the sampling distribution, the identity MSE = Var + bias², and the add-and-subtract trick behind Bessel's correction. Chapter 8 gave us tangency, the Lagrange multiplier and its reading as a shadow price. Chapter 7 gave us the SVD and the condition number. That is the whole toolkit, and this chapter is mostly a matter of pointing it in one direction.

Ch 21 handed you a diagnosis and no cure. Drag p — and watch its one remaining lever turn into the biggest search in the course.
Ch 20 · OLS fits Ch 21 · overfitting Ch 22 · you are here IN YOUR HANDS — what Ch 21 already gave you the U‑curve the k/n toll three exits STILL MISSING — the two holes Ch 22 must fill tap a slot ▸ why the right arm rises MISSING a continuous lever MISSING the only lever it left: 2ᵖ on/off subsets Ch 19’s toll began at m = 20 candidates p = 5 32 2 digits p = 10 1,024 4 digits p = 20 1,048,576 7 digits p = 30 1,073,741,824 10 digits p = 100 1.27 × 10³⁰ 31 digits p = 500 3.27 × 10¹⁵⁰ 151 digits subsets to score at p = 10 1,024 4 digits at 1,000 fits a second: about 1 second
p — features on the tabledrag →
p = 10 → 1,024 subsets
guess: subsets at p = 20pick one
Ch 21’s only lever was a row of on/off switches, one per feature. Every subset of them is a candidate model — so there are 2ᵖ of them.
What you’re looking at — the inventory Ch 21 handed over, the two things it could not give you, and the size of the only lever it left
In hand. The U‑curve (test error falls, then rises), the k/n toll (each fitted number is paid for), and three exits. All diagnosis.
The holes. Ch 21 can measure the right arm but never says why it rises — and its only lever is 2ᵖ on/off subsets. p = how many candidate features you have.
The count. 2ᵖ means one more feature doubles the search: 1,024 at p=10, over a million at p=20, 151 digits at p=500 — each score computed on noisy numbers.
Ch 22 fills both. bias² + variance + noise names the mechanism; λ replaces 2ᵖ switches with one continuous dial you can turn.
Fig. 1. Ch 21 left two holes and one lever — and the lever, 2ᵖ subsets, is the biggest search in the course.

So the seam is short. Chapter 21 ended by saying, in its own words, that it had shown the U-curve as a phenomenon without ever taking it apart. It then named the door: constrain, reduce or select. Walking through a door the previous chapter labelled costs us nothing new.

01A diagnosis with no treatment

Two things are missing from what Chapter 21 handed over, and both of them are load-bearing.

The first is a mechanism in parts. Show me a model that is predicting badly, and I cannot yet tell you whether it is failing because it is too rigid to hold the shape of the truth, or too free to ignore the noise. That distinction is not academic, because the two diseases need opposite treatments. Do the wrong one and you walk further from the floor rather than toward it.

Here are two patients, and they are as different as two models can be. The first is a straight line fitted to sixty rows whose truth is genuinely curved. The second is a degree-nine polynomial fitted to twelve rows whose truth is genuinely a straight line. Score both on fresh data and they come back at 0.174 and 0.175. The same number, to two decimals.

Two fits, two scoreboards, one identical number — choose a treatment for each patient, then take the 0.17 apart.
Patient A fit: a straight line train test gap 0.166 0.174 0.008 your call: — the 0.17, taken apart ? made of what? nothing says. 0.101 0.002 0.063 the fixable part: 98% blue Patient B fit: a degree-9 curve train test gap 0.031 0.175 0.144 your call: — the 0.17, taken apart ? made of what? nothing says. 0.000 0.079 0.063 the fixable part: 100% violet
Pick a treatment for each.
What you're looking at — two patients handed the same verdict, 0.17
the one number you get: test error, 0.174 vs 0.175
pile 1 — 0.101 in A, 0.000 in B
pile 2 — 0.002 in A, 0.079 in B
pile 3 — 0.063 in both: the floor no treatment moves
Same score, opposite make-up — so the number alone cannot say which knob to turn. The train/test gap catches B (0.144) and says nothing useful about A (0.008). The piles are the split of expected error; one test number wobbles around it. They get their names in the next figure.
Fig. 2. Two models, two opposite illnesses, one identical scoreboard: 0.174 and 0.175. Take the number apart and A's fixable error is 98% one ingredient while B's is essentially all of the other — which is why a single test number can never tell you what to do next.

Run each one four thousand times and the long-run split is not remotely the same. The line's error is 0.1011 of one kind plus 0.0020 of the other, sitting on a noise floor of 0.0625. The polynomial's is 0.0000 and 0.0793 on the identical floor. Strip the floor away and the line's remaining error is 98% one thing, while the polynomial's is essentially all the other. We have no names for those two piles yet. That is the point.

The one reading Chapter 21 does give us is the gap between training and test error, and it is worth being precise about what that buys. The polynomial trains at 0.002 and tests at 0.175, which is a scream. The line trains at 0.213 and tests at 0.174, which is silence. So the gap does flag the second patient. What it cannot tell you is how much of the line's error is fixable at all, or by how much, or which knob to turn on either one.

The second missing thing is the lever. Everything Chapter 21 left us is a row of on/off switches: which features go in. That sounds like the sober option, and the sober-sounding version of it is best-subset selection. Try every subset, cross-validate each one, keep the winner.

Count the candidates before you agree to that. With ten features there are 1,024 subsets. With twenty there are 1,048,576. With thirty there are over a billion, and with five hundred the count has 151 digits. Now set Chapter 21's own law beside those numbers: the optimism you are charged is set by the size of the search, and Chapter 19 measured what the best of m noisy tries looks like. The careful-sounding remedy is the largest winner's curse in the entire course.

Which hands us the chapter's programme in one sentence. If the toll is the size of the search, then shrink the search. Not the feature list. The search.

02Aiming at a row that does not exist yet

Before we can break the error into parts we have to define it, and we should define it where it actually pays. Two moves get us there, one cosmetic and one substantive.

The cosmetic one is vocabulary, and it is worth doing quickly so it stops being a barrier. What Chapter 20 called predictors are features. The target y is the label. Fitting is training, the β̂ are the learned parameters, and RSS is the loss. Ordinary least squares, entirely unchanged, is already a supervised learning algorithm. The costume is new and the machine underneath is the one you built.

The substantive move is that the question changes. Chapter 20 asked what β is. We are now asking what number to write on a row that is not in the dataset and has not happened yet. So write the world's law without assuming a straight line, because the decomposition does not need one: y = f(x) + ε, where ε has mean zero, variance σ² and no relationship with anything else. Then the quantity we want small is the prediction error at that new row, Err(x₀) = E[(y₀ − f̂(x₀))²].

Now notice what we are aiming at, because it is not y₀. That value carries a fresh ε that no model, no data and no amount of cleverness can reach. The best prediction that could possibly exist is f(x₀) = E[y|x₀], the conditional mean. Everything beyond it is a coin nobody can see. So even a perfect model eats σ², and that is not a footnote. It is the ceiling on the whole enterprise.

Three arrows, three different things all called “error”. Before you drag: if your model were perfect, how big would tomorrow's miss be?
THE ROWS YOU HAVE x₀ · NOT REAL YET e ε yᵢ ŷ(x₀) f(x₀) y₀ e = y − ŷ · computed on rows you HAVE ε = y − f · real, but f is never seen Err(x₀) = y₀ − ŷ(x₀) = +0.00 · not real yet VARIANCE OF y₀ explained: 40% 60% floor sd of y₀ 1.0000 best model 0.7746 gain 22.5%
TOMORROW tap ▸
rolls 0rms |Err| —
YOUR MODEL as fitted
◀ drag to PERFECT ▶bias² 0.49
R² 40% · sd 1.0000 → 0.7746
Press roll: only y₀ moves. The rows you have are frozen.
What you're looking at — three things all called “error”, each measured from a different baseline
e = y − ŷ — the residual: computable, orthogonal to your columns by construction. A leftover, not a forecast.
ε = y − f — the population error: real, but unseeable, because nobody hands you the truth f.
f(x₀) = E[y|x₀] — the best prediction that can exist. Aim anywhere else and you lose, on average.
Err(x₀) — aimed at a row that hasn't happened: y₀ carries a fresh ε, so a perfect model still leaves sd 0.9950.
Fig. 3. A third thing called error, and it is the only one that decides whether you make money. The blue e is a residual: you compute it on rows you already have, and least squares forces it to be orthogonal to your columns — it is a leftover, not a forecast. The red ε is the real population error, and you never see it, because nobody hands you the truth f. But Err(x₀) = E[(y₀ − ŷ(x₀))²] is aimed at a row that has not happened yet, so the very best prediction that can exist is the conditional mean f(x₀) = E[y|x₀] — and even that misses, because y₀ carries a fresh ε nobody can reach. Drag the model to PERFECT and roll again: the miss does not go away. Then press finance 1%, where 99% of tomorrow's return is that floor, and a flawless model shrinks the spread of tomorrow from 1.0000 to 0.9950. That half a percent is the entire prize, and it is why the rest of this chapter is about not throwing it away on variance.

Price that ceiling with a number Chapter 20 already made you accept. A daily-return R² near 0.01 is normal in this business. Read it literally: one per cent of the variance of tomorrow's return is explainable and ninety-nine per cent is the floor. Put it in standard deviations and it is starker still. A model with an R² of 0.01 cuts the spread of what you are predicting from 1.0000 to 0.9950. That half of one per cent is the entire industry.

One bookkeeping note before we move, because the word error now means three different things in three different chapters. There is the residual e, which you compute and which sits at a right angle to the columns by construction. There is the population error ε, which you never see, and which Chapter 20 spent a whole section separating from the residual. And now there is prediction error at a new point, which is an expectation over things that have not happened yet. Keep them apart and the rest of this chapter is easy.

03★★ Your model is a draw, not a decision

Here is the rung the whole chapter pivots on, and it is the one nearly every treatment sprints past.

Chapter 16 proved that a statistic computed from a random sample is itself a random variable, and that your estimate is one dot in a cloud you will never observe. Now read that one level up. β̂ is a statistic. The fitted function f̂ = Xβ̂ is built out of that statistic by arithmetic. So the entire fitted curve is a random object, and f̂(x₀) — one prediction, at one fixed point, from your one model — is a random variable with a distribution.

Say out loud what that distribution is over, because this is the exact inch where readers are lost. It is not over the rows of your dataset. You have spent five chapters averaging over rows, and the notation E[f̂(x₀)] arrives with no subscript to warn you. The randomness being averaged over is which dataset you got.

Before the picture, commit to a number, because the guess is what makes this stick. Twelve data points sit on a gentle curve with noise of size σ = 0.10. That is small, and it looks small: the dots hug the curve. Fit a degree-eleven polynomial, which has twelve coefficients and therefore threads all twelve points exactly. Now I draw nineteen more datasets from the same truth with the same noise, refit the identical model to each, and read all twenty predictions at the single point x₀ = 0.93. How far apart will those twenty numbers be?

One world, twenty draws from it. Guess how far apart twenty refits land at x₀ = 0.93 — seal it — then watch the spray.
one world · 12 points · σ = 0.10 f̂(x₀) measured 0 x₀ = 0.93 +0.40 −0.40 at x₀ = 0.93 noise σ 0.10 spray 0.000 guess 0.40 the 20 straight lines land here One dataset. One curve through all 12. How wide is the spray?
1 · YOUR GUESSdrag →
span 0.40 wide
2 · REFITlocked
3 · COMPARElocked
drag the bar, then seal it
The dots hug the curve — σ = 0.10. The fit passes through every one. Ship it?
What you’re looking at — not one fit, but the distribution of fits you could have got
The 12 points — one sample of the world. Noise σ = 0.10, so they sit in a band about 0.29 wide.
Degree‑11 fits, one per fresh sample. At x₀ the 20 answers span 3.96413.6× the noise they were fitted to.
Straight‑line fits of those same 20 datasets: a pencil beam, span 0.259, sitting 0.148 above the truth.
Your sealed guess. Width = variance, centre offset = bias — both averaged over datasets, not over rows.
Fig. 4. Twelve points, noise σ = 0.10 — visibly small, the dots hug the curve — and a degree‑11 polynomial threading every single one. It looks superb; it is exactly the object a reader would ship. So before anything runs, commit: the same world is about to be sampled twenty times, the same code refitted to each, and all twenty predictions read off at one point, x₀ = 0.93. How far apart will those twenty numbers be? Almost everyone answers in the neighbourhood of the noise — about 0.2; the data only wobbles a little. Seal it, then draw. The gold curves agree beautifully everywhere the data is, and near x₀ they fly apart: the answers span 3.964, roughly 13.6× the 0.29‑wide noise band they were fitted to, and the readout axis has to zoom out several times over to hold them. The model did that amplification itself. Now overlay twenty straight‑line fits of those same twenty datasets: a pencil beam, span 0.259, and every one missing the bend by 0.148 in the same direction. Then the stroke: neither of these pictures is available to you. You have one curve, and from the inside a wild polynomial and a straight line look equally reasonable — both pass near the data, both plot fine, both come with a coefficient table. Name what you just measured and the chapter is already standing: the polynomial’s centre is nearly right and its spread is enormous (variance); the line’s spread is nearly nothing and its centre is wrong (bias). The E in every formula that follows is taken across those twenty pictures — over the datasets you did not get.

Almost everyone answers in the neighbourhood of the noise. The data only wobbles by a tenth, so the answers should wobble by a tenth or two. The twenty predictions run from −2.380 to +1.593. That is a span of 3.974, on a truth whose value there is −0.2129. A wobble of 0.10 in the data came out as a wobble of nearly 4 in the answer, and the model performed that amplification entirely on its own. The reason is mechanical: a curve forced through every point must swing hard between them, so a small vertical nudge at one point becomes a large excursion at the next. Over twenty thousand refits the standard deviation settles at 1.343, which is 13.4 times the noise it was fitted to.

Overlay twenty straight-line fits of the same twenty datasets and you get the opposite object. They span 0.262, so tight you can barely tell them apart, and every one of them misses the same way. The polynomial's average is right and its spread is enormous. The line's spread is nearly nothing and its average is wrong by 0.148. Those two facts have names. The offset of the centre is the bias. The width around that centre is the variance. Both are errors you pay.

And now the stroke, which is one sentence. Neither of those pictures is available to you. You hold exactly one curve. From the inside, a single wild polynomial and a single straight line look equally reasonable, because both pass near the data, both plot fine, and both come with a coefficient table.

You hold exactly one dataset and one fitted curve — now call it: did this fit come from the wide cloud or the tight beam?
your one draw — 12 rows, one fit -2 0 2 -1 0 x★ = 0.85 THE PRINTOUT rows n 12 β̂₀ (const) 0.301 β̂₁ (x) 1.284 0.947 residual SE 0.338 its call at x★ 0.912 one number. no spread attached. the other nineteen: hidden spread: unknown to you other this
Two recipes fit these same 12 rows — one flexible, one rigid. You are shown the winner's curve and its printout. Call it.
sealed calls0 / 0 · —
call it — wide or tight?
What you're looking at — the one thing your sample refuses to show you
Everything you ever get: 12 rows and the curve fitted to them. Same rows either way — only the recipe differs (flexible vs rigid), and the printout — R², residual SE, β̂ — comes out looking fine for both.
The 19 siblings: the same recipe run on 19 other draws of the same truth. Their width is the variance term. The dashed outline is the width the other recipe would have had.
Your prediction at x★. One number, and no error bar was ever attached to it — because measuring the spread would take the 19 datasets you do not have. That unseen width is exactly what lifts the right arm of the U‑curve.
Fig. 5. The invisibility principle, made playable. Twelve rows are drawn from one fixed truth, and two recipes are offered the same rows: a flexible one (a degree‑6 polynomial) and a rigid one (degree‑3). One of them fitted the curve you are shown — and from inside a single sample the two are almost impossible to separate. Both pass near every point, both print a healthy R², both report a residual SE around 0.34, both hand you a tidy β̂ table and a single prediction at x★. Call it, then show the cloud: nineteen siblings — the same recipe re‑run on nineteen other draws of the same truth — fade in behind your curve, and the width that was invisible a second ago is suddenly the loudest thing on the page. Watch your running score sit near 50%. That is the point: variance is a property of the procedure, not of your dataset, so the one draw you hold cannot report it. It is still real, it is still charged to you out‑of‑sample, and it is exactly what makes the right arm of the U‑curve climb.

That is the invisibility at the centre of this subject. The width of the spray is an error you are paying and cannot see from inside your own dataset, and it is the entire reason the right arm of the U-curve goes up. It is also, I think, the honest reason backtests feel so persuasive. You are looking at one draw and reading it as a decision.

04Three lines and two dead cross-terms

Now the algebra, and it uses a move your own hands have already performed.

Start from Err(x₀) = E[(y₀ − f̂(x₀))²] and substitute y₀ = f(x₀) + ε. That ε belongs to the new observation, so it is independent of the training set that produced , and it has mean zero. Its cross-term dies and it contributes exactly σ². What is left is E[(f(x₀) − f̂(x₀))²].

Here we run Chapter 16's trick a second time. Add and subtract E[f̂(x₀)] inside the square, then expand. This is the same add-and-subtract that produced Bessel's correction, and it behaves the same way.

Three lines, two add-and-subtracts — press NEXT and watch both cross-terms die for the same reason.
THE DERIVATION · at the point x₀ Err(x₀) = E[( y₀ − f̂)²] y₀ = f + ε mean 0 · var σ² · indep = E[( ε + D)²] D = f − f̂ the miss = E[ε²] + 2E[εD] + E[D²] ← this term = 0 D = ( f−m ) + ( m−f̂ ) m = E[f̂] the ±m move E[D²]= (f−m)² + 2 (f−m) · E[m−f̂] + E[(f̂−m)²] Err(x₀) = σ² + bias²(x₀) + var(x₀) Ch16: MSE = Var + bias² no new y₀, no σ² the same identity, one term shorter 1 · SUBSTITUTE m = E[f̂(x₀)] STILL RANDOM? trapped inside E[·] THE AUDIT · at x₀ σ² bias² variance
BEAT 1 OF 6 · SUBSTITUTE
IS m STILL RANDOM? tap one
AUDIT · 20 000 FRESH DRAWS
formula total
measured directly
press NEXT · six short beats
What you're looking at — one expectation, opened twice. Both cross-terms die, and both die for the same reason: something inside them has mean zero.
ε — the noise on the fresh observation y₀. Independent of the fit and E[ε] = 0, so it factorises and vanishes, leaving σ²: the floor no model can go under.
(f − m) — the bias gap: truth minus the fit's average prediction. A plain number, so it steps straight out of E[·].
f̂ − m — the wobble: how far this sample's fit lands from its own average. Squared and averaged, that is variance.
the two cross-terms — not waved away. E[ε] = 0 is the assumption on the noise; E[m − f̂] = 0 is the definition of m.
Fig. 6. Now watch the thing get built, because a decomposition you are handed is a decomposition you will forget. Start with what we actually care about at one point x₀: the error we would make on a brand-new observation there, averaged over both the sample we happened to train on and the fresh noise on that new point. Beat 1 is the only modelling step in the whole derivation — write y₀ = f(x₀) + ε, the truth plus a fresh draw of noise. Beat 2 squares the bracket, and the middle term 2E[εD] dies on the spot for two reasons you can say out loud: ε belongs to a point the fit never saw, so it is independent of everything in D and the expectation splits — and then E[ε] = 0 finishes it. Zero times anything is zero. That leaves σ², standing alone, untouchable: no model, however clever, can predict a coin flip that has not happened yet. Beat 3 is the move that does the real work, and it is Ch 16's Bessel trick wearing a different hat — add and subtract the same thing. Call m = E[f̂(x₀)]: not the fit, but the average fit, the centre of the spray you have been watching all chapter. Toggle m between “still random?” and “a number” and watch what turns legal. This is where most people quietly lose the plot: f̂(x₀) is random — it depends on which sample you drew — so it is easy to assume its expectation is random too. It is not. The E has already been taken. m is a number, as fixed as 3, and that single fact is what lets (f − m) walk straight out of the expectation in beat 4. What is left inside is E[m − f̂] = m − E[f̂] = m − m = 0 — and that is the punchline. The cross-term is not assumed away, and it is not approximately small. One factor is a constant; the other has mean zero by the very definition of the letter we just wrote down. It cannot survive. So three terms land, and they are the three you now recognise by sight: σ², the noise floor; bias², how far the average fit sits from the truth; variance, how far the individual fits scatter around their own average. Ch 16 said MSE = Var + bias² for an estimator, and it is the same identity — the same ±m move, the same dead cross-term — just without a fresh noisy observation to predict, so no σ². Beat 6 refuses to take any of it on faith. Take the same spray, 20 000 fresh draws at x₀: add the three parts to get 1.7883, then throw the formula away and measure the squared error directly — 1.7885. Agreement to three decimals is not a story about models; it is arithmetic that happens to be true. And read what those three numbers say: bias² is 0.0000 and variance is 1.7783. This model is not wrong on average. It is wrong differently every time — which is precisely the disease regularisation was invented to treat.

The cross-term is where every textbook waves, so let us not. Write m = E[f̂(x₀)] as a single letter first. That m is a plain number: the expectation has already been taken, and there is no randomness left inside it. The cross-term is then (m − f(x₀)) × E[f̂(x₀) − m]. The second factor is zero by the definition of m, and the first is a constant, so the product is zero and no assumption was needed anywhere.

Three terms survive, and they are the chapter: Err(x₀) = σ² + (E[f̂(x₀)] − f(x₀))² + E[(f̂(x₀) − E[f̂(x₀)])²]. In words, noise plus bias squared plus variance. Look back at Chapter 16 and you will see the same identity one level down. MSE = Var + bias² had no σ² term because there was no fresh observation to predict, only a fixed θ to estimate.

Check it against the spray rather than trusting it. At x₀ = 0.93 the degree-eleven fit has bias 0.0000 and variance 1.8046, on a floor of 0.0100. So the formula predicts a prediction error of 1.8146 at that point. Draw twenty thousand fresh observations at that point and the measured mean squared error is 1.7885, against 1.7883 from the formula on the same draws. The identity is not a story about the error. It is the error.

Two things to say plainly before moving on. The noise term is not spendable: test error can never go below σ², so a model reporting error under the floor is reporting a bug. And the decomposition is pointwise. It holds at x₀, and both bias and variance change as x₀ moves, so the single test number you report is this decomposition averaged over the rows you expect to see.

05Taking the U apart

Re-run Chapter 21's complexity sweep, and this time plot the three parts instead of the total.

Bias squared falls as freedom rises, because a more flexible family can on average get closer to the true f. Variance rises, because every extra direction the fit is allowed to use is one more thing that can chase this particular sample's noise, and Chapter 21 already priced that at k/n. The noise floor is flat, because nothing you do to a model touches it.

Don’t plot the total — plot its three parts. Drag degree right and the U gets built in front of you, band by band.
test error = floor + bias² + variance 0.30 0.20 0.10 0 UNDERFIT OVERFIT the 9 fits · d = 0 spread offset same 9 samples, refit at d drag the degree slider — the U gets painted in as you go
POLYNOMIAL DEGREE0
drag → to assemble the U
variance0.0008
bias²0.1351
noise floor0.0100
TEST ERROR0.1459
too rigid · bias dominates
What you’re looking at — the U-curve is not one curve. It is a falling curve plus a rising curve, sitting on a floor that never moves.
bias² — being wrong the same way every time. Falls 0.1351 → 0.0001: on the right panel the beam of fits stops missing.
variance — being wrong a different way every time. Rises 0.0008 → 0.2812: the same nine samples now fan into a spray.
noise floor — 0.0100, flat as a table. No model, no data and no cleverness can touch it.
test error = the three stacked. Its floor (0.0138 at d = 3) is where the two slopes cancel — not where either part is smallest.
Fig. 7. Stop plotting the total and plot its parts. Drag degree and the stack paints in from the left: a grey noise floor that never budges (0.0100), a blue bias² band collapsing 0.1351 → 0.0001, and a red variance band climbing 0.0008 → 0.2812. The gold top edge is the test error, and it makes a U for no mysterious reason at all — a falling curve plus a rising one has to. Its floor sits at d = 3 (0.0138), where the two slopes cancel, not where either part is smallest. The right panel is the same fact seen on the data: at low degree the nine refits collapse into one tight beam that misses the truth (all bias, no spread); push right and the beam fans into a spray whose average lands on the truth (no bias, all spread). Underfitting is being wrong the same way every time; overfitting is being wrong a different way every time.

On our running curve the numbers are these. At degree 0 the bias squared is 0.1351 and the variance is 0.0008. At degree 3 they are 0.0011 and 0.0027, which is the floor of the total at 0.0138. By degree 11 the bias squared is 0.0001 and the variance has climbed to 0.2812. So the U is not mysterious at all. It is a falling curve plus a rising curve sitting on a constant floor, and its minimum is simply where the two slopes cancel.

Both arms now have mechanisms rather than labels. Underfitting is bias-dominated: the model is too rigid to hold the structure, so it is wrong the same way every time. Overfitting is variance-dominated: the model is free enough to fit this sample's noise, so it is wrong a different way every time. Our two patients from the opening are exactly one of each, and now they are separable.

Which means we have to deal with the word bias before it detonates, because you have met it twice and both times it was a defect.

Two estimates, both wrong on purpose — only one of them can be un-wronged
A · omitted confounder aimed at the wrong quantity off by 0.48 0 2.0 truth 1.00 ±2·SE = 0.99 B · deliberate shrink aimed right, then pulled back off by 0.00 0 2.0 truth 1.00 ±2·SE = 0.99 the verdict A · omitted variable B · chosen shrink can you dial it? — drag to reveal — — drag to reveal — more n fixes it? — drag to reveal — — drag to reveal — what did it buy? — drag to reveal — — drag to reveal —
Both estimates sit off the truth. Predict: whose offset can you undo?
A total error0.690
B total error0.495
B at s = 00.495
best s here0.20
s = 0 — plain least squares. B aims at the truth. A never did.
pick one, then drag the dials
What you're looking at — the same word "bias" on two estimates that could not be more different
the gold line is the truth, β = 1.00 — what both models are trying to hit
A: a confounder was left out, so the bell is centred 0.48 low. More n narrows the bell onto the wrong number; the dial only drags it further off
B: unbiased, then shrunk on purpose. Its offset reads exactly s — slide s back to 0 and it refunds, and the bell narrows by (1−s) as it goes
Fig. 8. Two models, one truth line at β = 1.00, and one pair of dials shared between them. A left a confounder out of the regression, so its sampling distribution is centred at 0.52 — 0.48 too low. Crank n from 50 to 5,000 and A's bell collapses to a needle that is still 0.48 off: more data buys precision about the wrong quantity, and the shrink dial only drags it further away. B is an unbiased estimate that has been shrunk on purpose. Its offset reads exactly s, so s = 0 refunds it completely — and while the offset grows, the spread falls by (1−s), which is the trade ridge is making. Watch B total error against B at s = 0: at n = 50 a shrink of about 0.20 beats plain least squares, and as n grows the best s slides back toward zero, because there is less variance left to buy off. Same word, opposite moral standing: one is a price you chose and can refund, the other is an aim at the wrong target that no amount of data corrects.

Chapter 16's estimator bias was a flaw to be corrected, and Bessel's correction was the fix. Chapter 20's omitted-variable bias was the unforgivable one: the failure that aims your coefficient at a different quantity altogether, that no computational repair reaches, and that does not shrink with n. Later in this chapter we are going to add bias on purpose. Unless the two are separated by name, right here, you will either refuse the trade as obviously wrong or decide Chapter 20 was being dramatic.

The distinction is sharp. Chapter 20's bias is an identification failure: it buys you nothing, you cannot dial it, and more data does not touch it. This chapter's bias is a chosen, quantified, reversible shift, purchased in exchange for variance, and you can set it back to zero whenever you like. Same word, opposite moral standing.

Two smaller corrections ride along, and they point in opposite directions. Chapter 21 may have left you with "simpler is safer", and the left arm of this curve is a picture of rigidity losing money. And you will now go looking for a function that returns bias and variance for your own model. It does not exist. Both quantities are defined over the datasets you did not get, so the decomposition is a thinking tool rather than a measurement.

06Where the variance actually lives

"More freedom, more variance" is true and far too coarse to act on. We need the exact address, because a remedy aimed at the wrong place is indistinguishable from superstition.

Chapter 20 gave the variance of the coefficients as Var(β̂) = σ²(XᵀX)⁻¹. Chapter 7 gave the coordinates in which that matrix is diagonal. Write the SVD as X = UΣVᵀ, so that XᵀX = V D² Vᵀ with the singular values d_j on the diagonal. In the direction v_j, the coefficient's variance is exactly σ²/d_j², and the total variance the fit carries is σ²·Σ 1/d_j².

Read that sum, because it is the whole point. Variance is not spread evenly across a model. It is concentrated in the directions where the data barely moved, since those have the smallest d_j and therefore the largest 1/d_j². A small singular value is not an abstraction: it says that along that particular combination of columns, your rows hardly varied at all, so there is almost no evidence about what happens when it changes.

Var(β̂) = σ2(XTX)−1, read along Ch 7’s singular directions, is just σ2/dj2 — one number per direction. Guess where it hides before you look.
0 1 2 3 4 0 1 2 3 4 β₂ β₁ d₁ — the sum d₂ — the difference YOUR SPLIT OF THE VARIANCE sum 50% difference 50% THE TRUTH — σ²/d² PER DIRECTION sum 0.4% difference 99.6% d₁ — the sum  β₁+β₂ σ²/d₁² = 0.00502 sd 0.091 σ²/d₂² = 1.19832 sd 1.633 corr(x₁,x₂) = 0.9917 · d₁/d₂ = 15.4 d₂ — the difference  β₁−β₂ two directions, one budget — commit before you look
You may fix exactly ONE number in this fit. Where is the variance hiding — in the sum, or in the difference? Split 100%, then seal it.
seal your split to see the truth
What you’re looking at — 200 refits of the same model, and the one direction that owns the spread
d₁, the sum direction (x₁+x₂). Var = σ²/d₁² = 0.00502: d₁ is large because the two features move together a lot, so the sum is pinned — sd(β̂₁+β̂₂) = 0.091. That short blue bar is the whole wobble it allows.
d₂, the difference direction (x₁−x₂). Var = σ²/d₂² = 1.19832: d₂ is tiny because the data barely moved this way (corr 0.9917), so sd(β̂₁−β̂₂) = 1.63399.6% of the whole budget, and the streak the dots make.
Why “more freedom, more variance” is too coarse to act on. Variance is not spread over the model — it sits almost entirely in the one direction the data barely moved in. Fix that single number and 99.6% of it disappears. Ridge does exactly this softly: adding λ to d₂² lifts the small singular value off zero.
Fig. 9. Two predictors at correlation 0.9917, refit 200 times. The cloud is not a blob — it is a long diagonal streak, because Var(β̂) = σ²(XTX)−1 read in Ch 7’s singular directions is simply σ²/dj² along each one: 0.00502 along the sum and 1.19832 along the difference. The bars are drawn to scale — blue is 2σ/d₁, gold is 2σ/d₂, and gold is 15.4× longer — and they land exactly along and exactly across the streak, because those directions are the axes of the cloud. So β̂₁ and β̂₂ each swing by more than a whole unit, some refits even reporting a negative coefficient where the truth is +1.5, while their sum never leaves 3.00 ± 0.09. Press fix β₁−β₂ and the streak collapses to a dot: one pinned number removes 99.6% of the variance. That is the sentence to carry into ridge — the cure is not “less freedom” in general, it is lifting the one singular value the data left near zero.

Take the smallest forcing example: two features at correlation 0.9917, a hundred rows, columns standardized. The singular values come back 14.1126 and 0.9135. The per-direction variances are then 0.00502 and 1.19832. One of two directions carries 99.6% of the total. If you could fix one number in this model, it is not "a bit of each". It is almost entirely that one direction, and the other one is close to free.

And those directions are not features. The V columns here are (−0.707, −0.707) and (+0.707, −0.707), which is to say the sum of the two features and their difference. The bad direction is the difference between two near-twins, and no single column can be blamed for it. Bootstrap the fit two hundred times and you can watch this directly: each coefficient has a standard deviation of 0.818, their difference has 1.633, and their sum has 0.091. The sum is pinned, the split is free, and their correlation is −0.994.

One dial, three chapters — the canyon, the condition number and the variance are the same object
1 · the RSS map how flat is it? β₁ β₂ contours of RSS 1.36 : 1 length ÷ width 2 · the stretch how square is X? d₁ big d₂ small κ = 1.36 d₁ ÷ d₂ 3 · the wobble where does it go? small axis big 65.0% sits on the floor one direction — the floor, d₂, and the variance axis Ch 20 · collinearity Ch 7 · conditioning Ch 22 · variance
Two predictors, correlation ρ. Before you drag it to 0.999 — which panel breaks first?
ⓘ tap a panel to name its chapter
κ = d₁/d₂1.36
d₂ (small)0.837
total variance2.2 σ²
share on d₂65.0%
Three panels, one dial. Tap a panel to see which chapter it came from — then drag ρ and watch all three move together.
predict, then drag ρ right
What you're looking at — three chapters drawing the same arrow
the gold direction is one and the same thing: the canyon floor the fit can slide along, the small singular value d₂, and the axis the fit's variance piles onto — its size is σ²/d₂²
the blue direction is the well-determined one (d₁): steep walls, tiny variance — it barely changes as ρ rises
rings are RSS contours (drawn to a fixed width, so you see the shape); dots are 60 refits on fresh samples. Panel 1's length ÷ width and panel 2's κ are always the same number
Fig. 10. Two predictors that move together with correlation ρ, and one dial that drives three pictures at once. Panel 1 is the least-squares landscape: contours of the residual sum of squares around the best fit β̂. At ρ = 0.30 it is a bowl. Push ρ up and the bottom stretches into a canyon — along the gold arrow you can raise β₁ and lower β₂ and the fit barely gets worse. Panel 2 is the same matrix measured numerically: its two singular values d₁ and d₂ are √(1+ρ) and √(1−ρ), and the condition number κ = d₁/d₂ is Chapter 7's warning light — 1.7 at ρ = 0.5, 4.4 at 0.9, 14.1 at 0.99, 44.7 at 0.999. Notice that panel 1's length ÷ width reads exactly the same number: the canyon's aspect ratio is the condition number. Panel 3 refits the model on 60 fresh samples and plots where the estimates land. The cloud is a streak along the same gold arrow, because Var(β̂) = σ²(X'X)⁻¹ puts σ²/d₂² of wobble on the small direction and only σ²/d₁² on the other — a share of (1+ρ)/2, which is 75% at ρ = 0.5 and 99.95% at 0.999. So the collinearity chapter, the numerical-stability chapter and this chapter's variance term were never three problems: the canyon's floor is the small singular direction, and its width is σ²/d₂². That is also why ridge works — adding λ to the diagonal lifts d₂² off zero, which narrows the canyon, cuts κ, and shrinks the variance, all with one move.

Now weld three chapters together, because this is one object that you have already met under three names. Chapter 7 warned that inverting divides by d, so a small d amplifies error enormously, and gave the condition number to measure it. Chapter 20 drew the RSS canyon, where near-dependent columns turn the bowl into a long flat valley whose floor lets noise slide the estimate a long way. This chapter calls it the variance term. The canyon's floor direction is the small-singular-value direction, and the bootstrap streak you watched in Chapter 20 is σ²/d_min² made visible.

Push the correlation and watch the same three readouts move together. At ρ = 0.5 the condition number is 1.7 and the smaller direction holds 73% of the variance. At ρ = 0.99 it is 14.7 and 99.5%. At ρ = 0.999 it is 47.1, the total variance has grown to 11.10, and the small direction holds essentially all of it.

Which tells us what any fix has to do, and it is more specific than "use fewer features". We need to stop the fit from spending freely in the directions where the data has nothing to say, while leaving it alone where the data spoke loudly.

07Shrink the search, do not cut the list

Chapter 21's law again: the optimism you are charged is set by the size of the search. So make the search smaller, which is the one instruction this whole chapter is built on. Not by deleting columns, which is the row of switches we already rejected, but by putting a fence around the candidates.

Instead of minimising RSS over all of ℝᵖ, minimise it subject to ‖β‖₂² ≤ t. The fit can still use every feature. It just cannot use them all loudly. That is the budget form, and it is worth pausing on how literal it is. A smaller t is a smaller region of coefficient space, which is a smaller candidate set, which is exactly the quantity Chapter 21 charged the toll on.

Drag the fence in — and watch the price of one more unit of freedom appear
OLS drag the ring → the fence β1 β2 0 constraint slack · λ = 0 · OLS minimise RSS(β) subject to ‖β‖² ≤ t fence budget t 7.29 radius ‖β‖ 2.27 λ shadow price 0.00 RSS − best fit 0.000 λ · (‖β‖² − t) = 0 the fence is SLACK widen the fence: Δt = 0.100 RSS falls by 0.000 and λ × 0.100 = 0.000 t λ
The ring starts wide. Predict: does the first part of the drag move the fit?
The ring is wider than OLS, so nothing binds: λ = 0 and this is plain least squares.
predict, then drag the ring in
What you're looking at — one problem wearing two costumes, on one shared axis
the ring: every β inside it obeys ‖β‖² ≤ t — drag it in and the candidate set shrinks
the touching contour: the cheapest RSS still reachable. It touches, it never crosses — and λ is the RSS one more unit of t would refund
OLS: the free least-squares fit. A ring wider than OLS binds nothing — λ = 0, and the penalty form hands OLS straight back
the trail: every fit this fence can produce, from OLS all the way down to zero
Fig. 11. The grey ovals are the RSS canyon: each one is a set of coefficient pairs β = (β1, β2) that fit the data equally badly, and they are long and thin because the two predictors are correlated — you can slide a long way along the floor and barely pay for it. The violet dot at the centre is OLS, the fit with no rules at all. Now put a fence around the origin: keep ‖β‖² ≤ t, and take the best RSS you can reach inside it. Drag the ring in (or drag on the plane itself) and watch three things at once. First, for the whole first stretch of the drag nothing happens — the fence is wider than OLS, so it constrains nothing, λ = 0, and you are looking at plain least squares. That is the KKT complementary-slackness condition λ·(‖β‖² − t) = 0 doing its job: a rule that does not bind has no price. Second, the moment the ring bites, the gold contour touches it — always tangent, never crossing, because if the contour crossed you could slide along it to a point still inside the fence with the same RSS and less length. Tangency means the two gradients are parallel: ∇RSS = −λ·∇‖β‖², and that single line is the whole bridge from the budget form to the penalty form min RSS + λ‖β‖², which the toggle flips between without the touch point moving one pixel. Third, read the panel: widening the budget by Δt drops RSS by exactly λ·Δt. That is what a Lagrange multiplier is — a shadow price, the exchange rate between fit and freedom, quoted in RSS per unit of β-length. So ridge is not a moral preference for small coefficients. It is a fence on the candidate set — the same size-of-the-search that Ch 21 charged you a toll for — and λ is simply how much that fence is worth at the margin.

Now Chapter 8 pays out in full. The objective is a convex bowl and the fence is a convex set, so the constrained minimum sits where an RSS contour is tangent to the fence. The tangency condition is ∇RSS = −λ∇g, and λ is the shadow price: how much RSS one extra unit of budget would buy back. Turn that sentence around and you have the form everyone writes, minimise RSS(β) + λ‖β‖₂².

These are not two methods. They are one problem seen from two sides, joined by a multiplier you already own, with λ up meaning t down. And KKT closes it honestly. If the unconstrained OLS solution already sits inside the fence, the constraint is slack, λ = 0, and you get OLS back unchanged. A knob that does nothing at zero is exactly what a knob should do.

This also kills the framing that ruins the idea for most people. A penalty is not a moral preference for small coefficients, and "discourage large weights" is a sentence that explains nothing. The penalty is a fence, and the fence is a smaller search. Regularization is any term added to the loss whose effect is to shrink the search space.

One warning before we go on, because it will otherwise cause real damage. This λ is Chapter 8's Lagrange multiplier, not Chapter 7's eigenvalue. Two chapters, one letter, and shortly we are going to add this λ to those eigenvalues in the same formula.

08The units become a modelling decision

Before that penalty can mean anything, something has to be true that is not yet. The term ‖β‖₂² adds coefficients from different features together. A coefficient on market capitalisation in dollars, one on a price-to-earnings ratio, one on a percentage: adding those three numbers up means comparing their units.

Here is the fact that makes this load-bearing rather than tidy, and it is worth predicting before you read it. Multiply one feature column by a thousand. Do the OLS predictions change?

CodeRun — this really ran. Column 1 gets multiplied by 1000. Seal both predictions, then press RUN.
$ units.py · numpy 1.26.4 · seed 9 X = rng.normal(size=(120,3)) y = X @ [1.0,0.8,0.3] + 0.35*e Xs = X.copy(); Xs[:,0] *= 1000 fit = solve(A.T@A + lam*I, A.T@y) the penalty fence as recorded col1 ×1000 OLS · no penalty 120 rows · 3 predictors β raw X · · · · · · β col1×1000 · · · · · · max|ŷ−ŷ′| · · · RIDGE · λ = 10 standardise: OFF β raw X · · · · · · β col1×1000 · · · · · · max|ŷ−ŷ′| · · · penalty share of β₁ · · · seal both answers on the right, then press RUN
Same 120 rows, same solver. Only column 1 changes units — ×1000. Predict, then run it.
1 · OLS predictions
2 · RIDGE (λ=10) predictions
3 · standardise inside the fit
seal both, then press RUN
What you're looking at — one script, one dataset, run twice with column 1 in different units
OLS shrugs. β₁ divides by exactly 1000 and the fitted values are the same to 2.554e−13 — scale-equivariant.
Ridge changes its mind. The same rescale moves predictions by up to 0.1712: a different model, from an editing choice.
Why: the penalty adds up β², so a huge unit shrinks β₁ and its share of the fence falls 56.4% → 0.000145% — it is exempt. Standardise inside the fold; the standardiser is a fitted transform too.
Fig. 12. The same 120 rows, the same three predictors, the same solver — and one edit: column 1 is multiplied by 1000, as if someone re-recorded it in millimetres instead of metres. Plain least squares does not care. Its coefficient on that column, β₁, divides by exactly 1000 (0.921760 → 0.00092176), the other two coefficients do not move a digit, and the fitted values agree to 2.554e−13 — which is floating-point for identical. That is scale-equivariance: OLS only cares about the column space, and rescaling a column does not change it. Ridge does care. At λ = 10 the same edit moves predictions by up to 0.1712, and β₁, read back in its original units, climbs 0.8354 → 0.9044. The bar chart is the reason, and it is the whole lesson: the penalty is a single sum, λ∑β², so it compares coefficients across features — and a feature measured in enormous units needs only a tiny coefficient, so it pays almost nothing. Feature 1's share of the fence collapses from 56.4% to 0.000145%: it did not get better, it got exempt, and ridge duly let it run. Switch control 3 to on and both runs return the same coefficients again to 3.997e−14. So standardisation stops being hygiene the instant you add a penalty — it is part of the model. And because the mean and standard deviation it subtracts are estimated from data, the standardiser is a fitted transform: fit it on the training fold only, or Chapter 21's leakage walks straight back in.

They do not. The coefficient obediently divides by a thousand, going from 0.921760 to 0.00092176, and every fitted value is identical to within 2.6e−13. OLS is scale-equivariant: it does not care what units you recorded your data in. Now the second question, and this is where nearly everyone gets caught. Having just watched OLS shrug, do the ridge predictions change?

They change by up to 0.1712. The reason is arithmetic rather than mysterious. That rescaled coefficient is a thousand times smaller, so its square is a million times smaller, so the penalty barely notices it. Feature one's share of the total penalty collapses from 56.4% to 0.000145%. It has been quietly exempted, and read back in the original units its coefficient has moved from 0.8354 to 0.9044: barely shrunk at all.

So the moment you add a penalty, the units your data happens to be recorded in become a modelling decision. The fix is standardization: centre each column and divide by its standard deviation, so that a coefficient means "change in y per one standard deviation of this feature". That is a comparable quantity across features, which is precisely what the penalty needs in order to be adding like to like.

Two riders travel with it, and both of them bite in practice. The intercept is never penalised, because it is a level rather than a direction. Shrink it and your fit starts depending on where you happened to put the zero of y. Convert returns from percent to basis points and a penalised intercept will move your predictions.

The second rider is the one that ships to production. The standardiser is a fitted transform: it estimates a mean and a standard deviation from data. By Chapter 21's rule it therefore belongs inside the fold, computed on training rows only. This is the exact leak Chapter 21 flagged as the one that survives a perfect split, and it is doubly seductive here, because standardizing does not feel like fitting anything. It feels like cleaning.

09Ridge, solved and then read

The penalised loss RSS(β) + λ‖β‖₂² is a convex quadratic in β, so Chapter 8's recipe applies with no ceremony. Set the gradient to zero, and you get (XᵀX + λI)β = Xᵀy, hence β̂_ridge = (XᵀX + λI)⁻¹Xᵀy. One line, no new theory.

But do not read that inverse yet, because there is a version of ridge with no matrix algebra in it at all, and it is the one that makes the penalty something you can point at.

Ridge without a new formula: staple √λ rows under X and run plain least squares. Before you click — which β̂ moves when row 1 lands?
THE ROWS YOU HAND TO OLS x₁ x₂ x₃ y press + ADD A ROW rows in the stack 6 + 0 = 6 coefficients pinned 3 of 3 PLAIN LEAST SQUARES ON THAT STACK 0 1.0 CLOSED FORM (XᵀX+λI)⁻¹Xᵀy the bars are walking to it Each fake row is one sentence: “βʲ is 0” — said at volume √λ.
PREDICT · THEN click +
PENALTY WEIGHT λ4.00
HOW MANY REAL ROWS?
0 prior rows · this is plain OLS
What you're looking at — ridge with no new formula. Staple p extra rows under X, run ordinary least squares on the taller stack, and the ridge estimate falls out.
the real rows — six observations of three predictors x₁,x₂,x₃ and their outcome y. On their own they give plain OLS, λ nowhere in sight.
the prior rows — row j carries √λ in column j, 0 in the others, and 0 for y. Read it aloud: “√λ·βʲ should equal 0”. Evidence, at a volume you set.
β̂ — re-solved by ordinary least squares after every row lands. Each new row drags mostly on its own coefficient; the cyan ticks mark where it ends up.
p > n — 2 rows cannot pin 3 coefficients, so OLS has no unique answer. But the 3 prior rows have rank 3 by themselves, so the stack always does. That is why ridge is defined where OLS is not.
Fig. 13. The same six rows twice over. On their own they give plain least squares: β̂ = 0.921427, 0.774831, 0.300408. Now staple three extra rows underneath — row j carrying √λ in column j, zeros everywhere else, and 0 for y — and run the same ordinary least squares on the taller stack. At λ = 4 the bars walk 0.921427 → 0.753845 as row 1 lands, then 0.774831 → 0.662617, then 0.300408 → 0.248374, arriving at (XᵀX + λI)⁻¹Xᵀy to the last bit of double precision. No penalty term was ever added to a loss function: the penalty is those rows, and √λ is how loudly each one speaks. Drag λ to 0 and they fall silent — three rows of zeros, and you are back to OLS. Then switch to 2 rows · p > n: two observations cannot pin three coefficients, the rank readout drops to 2, and least squares has no unique answer at all — until the prior rows land, because those three rows are rank 3 by themselves. That is the whole reason ridge is defined in the p > n regime where OLS is not.

Stack √λ·I underneath X, and p zeros underneath y. You have added p fake rows. Each one says "this coefficient is zero", and each carries weight √λ. Now run plain ordinary least squares on that augmented dataset. On our three-feature example with λ = 4, augmented OLS returns (0.885070, 0.736897, 0.284760) and the ridge formula returns the same three numbers, agreeing to 2.8e−15. The algebra is one line, since X̃ᵀX̃ = XᵀX + λI.

So the penalty is not punishment and not discouragement. It is prior evidence, written as rows, mixed into your data on the same footing as your observations, with λ setting how loudly it speaks. It also explains in advance why the fit is unique when p > n. You literally added p rows.

Now read the machine in Chapter 7's coordinates, and three consequences fall out at once. Since XᵀX = VD²Vᵀ, adding λI keeps the same eigenvectors and lifts every eigenvalue from d_j² to d_j² + λ.

One dial, two directions — and it squeezes hardest exactly where the data said least
the fit in the data’s own axes v₁ v₂ 0 OLS β̂ β̂(λ) λ = 0 sideways × 1.0000 upward × 1.0000 every direction × d²/(d²+λ) v₁ · d² = 199.5 1.0000 eigenvalue 199.5 → 199.5 v₂ · d² = 0.836 1.0000 eigenvalue 0.836 → 0.836 df(λ) — parameters in use 0 1 parameter 2 df = 2.000 parameters a whole number — this once why df = 2.000 ? v₁ contributes 1.0000 v₂ contributes 1.0000 total 2.000 two whole parameters — for now
log dial · drag → or jump:
df(λ)2.000
eig ratio238.7
toll df/n · n=400.050
ratio 238.7 · near-singular
What you’re looking at — the same two directions, squeezed by different amounts
v₁, the direction the data pinned down (d² = 199.5). λ barely dents it.
v₂, the direction the data barely saw (d² = 0.836) — the fat sliver of uncertainty. It folds away first.
df(λ) = sum of the two bars: a parameter count with a decimal point, ready to drop into Ch 21’s k/n toll.
Fig. 14. Ridge does not add a new machine — it turns one dial. Adding λI to XX leaves the eigenvectors exactly where they were, so the picture on the left keeps the same two axes: v₁, the combination of predictors the data measured sharply (d² = 199.5), and v₂, the combination it barely resolved (d² = 0.836) — the tall violet sliver is that ignorance drawn to scale. Every eigenvalue is lifted d² → d²+λ, so each direction survives multiplied by d²/(d²+λ). Drag the dial and watch what that means: at λ = 0.5 the sharp direction keeps 0.9975 of itself while the vague one keeps 0.6257; by λ = 5 it is 0.9755 against 0.1432. The gold dot falls almost straight down before it slides left — nobody told it which coefficient to punish, the geometry did, and it punished the one the data could not defend. Two counters ride along. The eigenvalue ratio, the near-singularity that made Ch 20’s collinear fit explode, collapses 238.7 → 35.0 → 10.5 → 3.0. And df(λ), the sum of the two bars, counts down 2.000 → 1.623 → 1.450 → 1.119 → 0.949 → 0.674. Open why 1.119? and the fraction stops being strange: you are using one parameter almost whole and the other about a seventh, and 1.119 is simply their sum — a real-valued count of how much model you actually spent. Feed it straight back into Ch 21’s overfitting toll as df(λ)/n and the toll falls with it, which is the whole bargain: buy a little bias, retire most of a parameter, pay less at the out-of-sample till.

First, the coefficient along direction j is multiplied by the shrinkage factor d_j²/(d_j² + λ). That is near one where d_j is large and near zero where it is small. On the collinear design, λ = 5 multiplies the strong direction by 0.9755 and the weak one by 0.1430. That is the surgical shrink we asked for, and nobody had to hand-tune it. The geometry does it.

Second, the smallest eigenvalue is lifted off the floor. The eigenvalue ratio of XᵀX on that design is 238.7, and at λ = 5 it is 35.0, at λ = 20 it is 10.5. Chapter 7's warning, answered. And since d² + λ > 0 always, XᵀX + λI is invertible even when XᵀX is singular. Ridge dissolves Chapter 21's p ≫ n non-uniqueness outright. On forty rows and a hundred columns, two OLS solutions with identical predictions had norms of 1.455 and 7.150; ridge at λ = 1 returns one answer, for a stated reason, instead of the silent pseudo-inverse.

Third, add up the shrinkage factors and you get the effective degrees of freedom, df(λ) = Σ d_j²/(d_j² + λ). On our two-feature design it slides from 2.000 at λ = 0 through 1.450, then 1.119, then 0.674.

A value of 1.119 deserves a stop, because Chapter 20 defined degrees of freedom as a dimension count and counts are integers. What df(λ) counts is fractional usage. The fit uses a well-determined direction almost fully and a poorly-determined one a seventh of the way, and adding those fractions gives a real number that behaves exactly like a count in every formula that used one. At λ = 0 it returns p exactly, and it falls smoothly toward zero as the fence tightens, which is what a dial should do. That is the continuous lever the opening asked for, and it drops straight into Chapter 21's toll as df(λ)/n.

One last framing note, because this formula lives a double life in the literature. Numerical-analysis courses present adding λI as a fix for an ill-conditioned matrix, and statistics courses present it as a fix for overfitting. Those are the same story, and the weld we built is why.

10The first inch of shrinkage is free

Everything so far says the trade is possible. Now ask whether it is ever actually worth making, and get a real answer rather than a habit.

Write both terms as explicit functions of λ, using the shrinkage factors we just derived. The variance is σ²·Σ d_j²/(d_j² + λ)², and the bias squared is Σ λ²β_j²/(d_j² + λ)², with the β_j read in the singular coordinates. At λ = 0 the variance is the number we already computed, and the bias squared is zero.

Race the two curves off the starting line — one leaves flat, the other leaves falling
MSE(λ) = bias²(λ) + variance(λ) + noise the first inch 0 1 2 3 4 5 6 1.0 0.5 0.0 MSE λ = shrinkage strength · λ = 0 is plain OLS ? ? which one wins the first inch? commit, then press NEXT slope -2.8720 slope 0 - leaves flat ZOOM · λ: 0 → 0.05 Δvar -0.1316 Δbias² +0.0016 trade 82 : 1 OLS 1.2033 0.3579 λ* = 2.00 1.2033 → 0.3579 3.4× lower MSE right of here: BIASED λ* = 0.5 λ* = 1.0 λ* = 4.0 BEAT 1 · YOUR CALL Pick one before you look — being wrong here is the lesson.
λ is the shrinkage dial. At λ = 0 you have plain OLS. Nudge it up a hair — which curve moves more?
pick one, then press NEXT
What you’re looking at — two curves leaving the same starting line, and only one of them leaves flat
variance(λ) = σ²p·d/(d+λ)² — the part of the error caused by which sample you happened to get. It leaves λ = 0 on a ramp: slope −2.8720, strictly negative.
bias²(λ) = Σβ²·λ²/(d+λ)² — how wrong you are on average (Σβ² = total squared size of the true coefficients). Its leading term is λ², so it leaves flat: measured slope +7.2e−07, i.e. zero.
Their sum + a constant noise floor. One concrete ridge problem: σ²p = 1.00, Σβ² = 0.50, eigenvalue d = 0.83, noise 0.0052. The dip bottoms at λ* = σ²p/Σβ² = 2.00, MSE 0.3579 against OLS’s 1.2033.
Fig. 15. Two curves leave the same starting line at λ = 0, the point where ridge is nothing but plain OLS. Before you look, say which one moves more over the first inch of shrinkage — then step through and watch. Variance leaves the origin already falling, on a slope of −2.8720: shrink by any amount at all and it drops immediately. Bias² leaves the origin dead flat, because its leading term is λ² — and a squared term has zero slope at zero (Chapter 4). Measure that slope numerically with a step of a millionth and you get +0.00000072, which is not a slope, it is a rounding error. Zoom into the first hundredth of the dial and the trade is 82 : 1 in your favour; at λ = 0.5 it is still 10 : 1. That is the whole reason shrinkage is the generic optimum rather than a hack: the first inch is free on every noisy dataset, so some λ > 0 always beats OLS — here the sum bottoms at λ* = 2.00 with MSE 0.3579 against OLS’s 1.2033. And Gauss–Markov was never violated: it only ever claimed OLS is best among UNBIASED estimators, where “best” means smallest variance. Ridge simply declines to be unbiased and walks out through that word. Be honest about the limit, though: the theorem proves a door exists, not where it is — λ* = σ²p/Σβ² depends on the noise and the true coefficients, neither of which you know. That is what cross-validation is for.

Now the question that decides whether any of this is worth doing. Which of the two wins the first inch of shrinkage? Most readers say it depends on the data, which is the sophisticated answer and it is wrong. Bias squared is quadratic in λ, and Chapter 4 told us a quantity that leaves a point quadratically leaves it flat. The variance leaves steeply. On our design the slope of the variance at zero is −2.8720 and the slope of the bias squared is 7.2e−07, which is zero to numerical precision.

So the derivative of the total at λ = 0 is strictly negative. Not usually. Always, for any dataset with noise in it. There is always some λ > 0 whose total error is strictly lower than OLS's. Watch it happen on the numbers: a step to λ = 0.5 drops the variance by 0.7298 and raises the bias squared by 0.0702, a trade of better than ten to one. The best setting is λ = 2.00, where the total is 0.3579 against OLS's 1.2033. That is 70% of the error removed by a knob.

A careful reader is now holding an objection, and it is the right one. Chapter 20 proved Gauss–Markov: OLS is the best linear unbiased estimator. So how can anything beat it?

Point at the adjective. The theorem's promise is about variance, and only among estimators whose centre is already pinned to the truth. Ridge is biased, so it is not in the competition the theorem was judging. And the quantity that costs you money is MSE, which Chapter 16 already told us is variance plus bias squared. Chapter 16 also said, in as many words, that a biased estimator can beat an unbiased one. This is that sentence, cashed.

Say the honest half too, because this is where the result is usually oversold. The result guarantees that a good λ exists. It does not tell you what it is. Too much λ walks you into the bias-dominated arm and loses money there instead, and the only way to locate the right one is a data-driven search we will build shortly.

11Same fence logic, different fence

Keep the entire machine and change one thing: the shape of the fence. Replace ‖β‖₂² ≤ t with ‖β‖₁ = Σ|β_j| ≤ t. Same budget logic, same bridge to a penalised form RSS + λ‖β‖₁, and one dramatic consequence.

In two dimensions the L2 fence is a disc. The L1 fence is a diamond, and its extreme points sit on the axes. A point on an axis has a coordinate that is exactly zero. So the lasso does not merely shrink coefficients. It sets some of them to exactly zero, which means it selects features.

That much is the famous picture, reproduced in every textbook on the subject. The question it never answers is why the tangency lands on a corner rather than merely passing close to one.

Sweep the aim and watch the answer refuse to move — a corner is sticky, a curve is not
b₁ b₂ drag the blue dot — or sweep θ why a corner catches more a smooth point ● point: 1 normal → 0% a corner ◆ corner: 90° fan → 50%
Blue is the fit with no penalty. Predict: which fence can make a coefficient exactly 0?
solution(1.20, 0.00)
corner share50% of aims
exact zeros◆ 0 · ● 0
predict, then sweep the aim θ
What you're looking at — one drag, two fences, and a corner doing all the work
the blue dot is the plain least-squares fit, the answer with no penalty at all — drag it, or sweep the aim θ. The dashed rings are its loss contours; b₁ and b₂ are the two coefficients
the gold dot is the best answer the fence allows — and the gold arcs on your drag circle mark every aim that lands on a corner. Sweep across one and the answer does not move at all
◆ L1: a corner has a whole 90° fan of outward normals, so it captures a fat, open share of directions — that fan is the subgradient, and it is the entire reason lasso returns exact zeros
● L2: the same four axis points, but every point on it is smooth with one lone normal — a vanishing share, so ridge shrinks toward zero and lands on it essentially never
Fig. 16. Two coefficients, b₁ and b₂, live on this plane. The blue dot is where least squares wants to sit with no penalty at all; the dashed rings around it are its loss contours, growing outward as the fit gets worse. The fence is the budget the penalty imposes, and the gold dot is the cheapest point the budget allows — the first contour that touches the fence. Now sweep θ and watch the gold dot: over a wide arc it does not move at all, parked on a corner with b₂ reading exactly 0.00, and only in the gaps between the gold arcs does it slide along a face. Switch the fence to a circle and repeat the identical sweep: the gold dot slides continuously and the exact-zero tally never leaves 0. The reason is in the right-hand card. A smooth point has exactly one outward normal, so for a contour to touch there the aim must match that single direction — a knife-edge coincidence with zero share. A corner has no single normal; it has a 90° fan of them, and it captures every aim inside that fan — an open, positive share, which the readout tracks live as you change the reach r. That fan is not a picture-book flourish: it is the subgradient of |b| at zero, the whole interval [−1, 1] instead of one derivative, which is simultaneously why lasso sets coefficients to exactly zero and why it has no closed-form solution. Ridge's circle is smooth everywhere, so it shrinks toward zero forever and arrives essentially never.

Here is the reason, and it is pure geometry. At a smooth point of a fence, Chapter 8's condition needs the gradient to line up with the single outward normal at that point. That is one direction out of a continuum, a knife-edge coincidence. At a corner there is no single normal. There is a whole fan of them, so an entire open set of gradient directions gets caught by that one point. Corners capture a positive share of problems, and smooth boundary points capture a vanishing one, so the zeros are not a coincidence you got lucky with. That, and nothing more mystical, is why L1 produces exact zeros and L2 never does.

The same fan explains the thing readers experience as an arbitrary software difference. Lasso has no closed form, because |β| has no derivative at zero, so "set the gradient to zero" is simply unavailable. The object that replaces the gradient there is the subgradient, which is the same fan of directions under another name. Coordinate descent is the practical consequence of a corner, not a quirk of a library.

Now say it quantitatively, in the one case where both have closed forms: orthogonal columns.

Two shrinkage rules on one axis — drag β̂ and watch what each one REMOVES.
swap −3 0 3 β̂ (OLS) what's kept drag the ● — or use the sliders WHAT EACH RULE REMOVES at β̂ = 0.80 RIDGE (L2) −0.2667 a fixed FRACTION: 33.3% LASSO (L1) −0.5000 a fixed AMOUNT: 0.50 (62.5%) “L1 always cuts harder” FOLKLORE — as usually told holds only below β̂ = 1.50
Lasso removes more here
Drag the cyan ● along the axis, or jump to a preset above.
What you're looking at — the dashed 45° line is “no shrinkage”; each rule's drop below it is what that rule REMOVED.
ridge (L2) returns β̂/(1+λ): it removes the same fraction of every coefficient — tiny bite on a small one, huge bite on a big one.
lasso (L1) returns sign(β̂)(|β̂|−λ)₊: it removes the same flat amount λ, so everything inside the shaded dead band is set to exactly 0 — that band is feature selection.
drag past the swap point β̂ = 1+λ and ridge starts removing more: the slogan “L1 is more aggressive” is only true for the small coefficients.
one dial moves both curves here for comparison, but ridge's λ and lasso's λ are different objects — the shape of each rule, not the number, is the claim.
Fig. 17. In the orthogonal case ridge scales the OLS coefficient to β̂/(1+λ) while lasso subtracts λ outright, so lasso is harsher below β̂ = 1+λ and gentler above it — and the flat dead band, where it returns exactly zero, is feature selection.

Ridge multiplies each OLS coefficient by 1/(1 + λ). Lasso subtracts λ from its magnitude and clips at zero, giving sign(β̂)(|β̂| − λ)₊, which is called the soft threshold. Draw the two side by side and read what each one does to a coefficient. Ridge is a straight line through the origin with a gentler slope. Lasso is a dead band, then a 45-degree line offset by λ. That dead band is feature selection, drawn.

And the picture corrects a slogan everybody repeats. At λ = 0.5 in each formula, an OLS coefficient of 0.20 becomes 0.1333 under ridge and 0.0000 under lasso. But an OLS coefficient of 3.00 becomes 2.0000 under ridge and 2.5000 under lasso. Lasso removed 0.50 and ridge removed 1.00. So the lasso is harsher on small coefficients, which it kills outright, and gentler on large ones, which it only nudges. One subtracts a constant amount, the other removes a constant fraction. The two λ's are different objects and the shape is the point.

12Which fence, and the trap inside the answer

Which one, then? The choice is not a matter of taste. It is a statement of belief about the world.

If you think many features each contribute a little and they move together, which is the normal condition in factor research, ridge is right. It keeps correlated twins and splits the credit between them, which is stable precisely because the quantity it is splitting is the one the data actually determined. If you think a few things genuinely matter among hundreds of candidates, lasso is right, and it is the honest continuous version of Chapter 21's third exit.

But there is a trap sitting inside that second answer. Give the lasso two nearly identical predictors and it has to pick one. Chapter 20 already told us it has no basis for choosing, because the sum is pinned and the split is free.

CodeRun — this really ran. Two 0.9791-correlated twins, 200 bootstrap refits. Guess who survives, then RUN.
$ twins.py · scikit-learn 1.5.1 · seed 5 x1, x2 = twins corr(x1,x2) = 0.9791 y = 1.0*x1 + 0.8*x2 + 6 noise cols 200 bootstrap resamples → refit each what decided it corr(x1,y) 0.718 corr(x2,y) 0.708 gap 0.010 LASSO (L1) · 200 refits kept = coefficient ≠ 0 twin 1 x₁ you 50 · · · twin 2 x₂ you 50 · · · the SET of 200 refits 0 β₁ · · · β₂ · · · β₁+β₂ · · · seal both guesses on the right, then press RUN
Twin 2 carries the same information as twin 1. Guess how many of the 200 refits keep each one.
same data, other penalty
drag both guesses, then RUN
What you're looking at — one dataset, refitted 200 times, and the list of "chosen" features re-rolled each time
twin x₁ survives 99.0% of refits — it won by 0.010 of sample correlation with y.
the set changed in 47% of refits: same data, same code, a different "finding".
but β₁+β₂ = 1.583 ± 0.151 holds while each part swings by ~0.45 (corr −0.945). Ridge keeps both, every time.
Fig. 18. Two of the eight predictors are twins: correlated at 0.9791, carrying all but a whisper of the same information, sitting beside six columns of pure noise. Lasso is asked to pick, and pick it does — but look at what it picks. Across 200 bootstrap resamples of the same dataset, twin x₁ is kept 99.0% of the time and twin x₂ only 54.0%, and the selected set is both twins in 53% of the refits and exactly one twin in the other 47%. Same data. Same code. Same seed for the model. A different answer to "which features matter" in nearly half the runs. And the thing that handed x₁ its crown was a gap of 0.010 in sample correlation with y — 0.718 against 0.708 — a difference so small it is itself just noise, which is exactly why it flips when you re-draw the sample. Now the part that makes it click: the coefficients are correlated at −0.945, so when x₁ takes more credit x₂ takes almost exactly that much less, and their sum comes out at 1.583 ± 0.151 — three times steadier than either part alone. The combined effect was never unstable; only the attribution was. Switch the penalty to ridge on the identical data and the choosing stops: both twins appear in all 200 resamples at 1.211 ± 0.233 and 0.830 ± 0.218, the credit split rather than awarded, each coefficient about half as jumpy. That is the honest reading of L1's corner geometry from Figure 16: the diamond's corner sets a coefficient to exactly zero, but when two directions are nearly the same direction, which corner it lands on is decided by a rounding error in your sample. So a selected feature list is not a finding — it is a random object, and the reportable quantity is its stability: refit on resamples, print the selection frequency, and report the quantity that holds (here, the sum) rather than the split your one run happened to produce.

Watch it rather than take the warning. Two twins at correlation 0.9791, both genuinely carrying a coefficient of 1, plus six columns of pure noise, on two hundred rows. In this particular sample the first twin correlates 0.718 with the label and the second correlates 0.708. A gap of one hundredth is the entire basis on which the credit gets handed out.

Bootstrap the fit two hundred times and read which features come back. Twin one survives in 99% of the resamples and twin two in 54%. Both are kept 53% of the time and exactly one is kept the other 47%. The coefficients tell the same story with more precision: β̂₁ = 1.251 ± 0.461 and β̂₂ = 0.332 ± 0.439, correlated at −0.945, while their sum is 1.583 ± 0.151. The sum barely moves and the split swings wildly. Run ridge on the identical data and both twins are present every single time, at 1.211 and 0.830.

So the list of selected features is not a discovery. It is a random object with a distribution. What you report is its stability, meaning how often each feature survives resampling, and not the set your one run happened to produce.

Elastic net splits the difference by adding a little L2 back, minimising with α‖β‖₁ + (1−α)‖β‖₂². That rounds the corners just enough to keep correlated groups together while still zeroing the dead ones.

One more consequence, and it is the one that ends up in research notes. The bias you deliberately bought is still sitting on the coefficients that survived, so their magnitudes are shrunk toward zero. That is why people refit plain OLS on the selected subset, which is called the relaxed or debiased lasso, and it works. It comes with one standing warning: the t-statistics from that refit are lies. The features were chosen by looking at the data, and the refit computes its inference as though the choice had been made in advance. That is Chapter 19's winner's curse, wearing a lab coat.

13Choosing lambda without cheating

λ is a hyper-parameter, which means it is chosen by search rather than by the optimiser, so Chapter 21 already wrote every rule we need. It is chosen on validation folds and never on the test set. In finance those folds are walk-forward with a purge sized to the label horizon. And every fitted transform, including the standardiser, is fitted inside the fold.

Now plot the cross-validation error against λ, with the standard-error bars Chapter 16 taught us to attach.

Choosing λ on validation folds. Press RESHUFFLE and watch the winner move — then guess which λ is really best before you lift the curtain.
WHAT YOU SEE · the CV curve lower is better 11 10 9 1 SE above the floor the whole dip: 0.766 one standard error: 0.918 1 3 10 30 100 300 1000 landings THE TRUTH · 50,000 fresh rows 11 10 noise floor 9.000 λ — the penalty weight (log scale) 🔒 the true score is hidden predict which λ really wins — then REVEAL argmin 1-SE THE HONESTY CARD YOUR PICK λ = 100 lowest CV in this run cross-validation reported 9.178 true score, 50k fresh rows — hidden — optimism — reveal to compare picks irreducible noise: 9.000 0 reshuffles so far
base curve — now reshuffle
Same data, same model — only the random split into folds changes. Each press stacks one red dot where the winning λ landed.
What you’re looking at — a basin shallower than its own error bar, and the pick that pays for it
the cross-validation score at each penalty weight λ (bigger λ = more shrinkage), with its ±1 standard error band. The whole descent into the basin is 0.766; one SE is 0.918. The dip is smaller than the ruler.
the argmin — the lowest point of this split. Reshuffle and it hops between λ=30 and λ=100; after 40 runs the tally is 4 and 36. Nothing about the model changed. That is noise choosing your hyper-parameter.
the true score on 50,000 fresh rows — normally invisible. Its minimum never leaves λ=100, and even there it sits 1.087 above the noise floor of 9.000: the part no model can remove.
the one-standard-error rule: take the largest λ whose CV still lies within one SE of the floor — here λ=300. Out of sample it scores 10.410 against the argmin’s 10.087. It buys stability and simplicity, not a better number.
Fig. 19. The basin is flatter than its own error bar: the entire visible dip is 0.766 while one standard error is 0.918, so the argmin is chosen by whichever way the folds happened to fall — it lands on λ=30 four times in forty and on λ=100 thirty-six, while the true optimum never moves. And the CV score at your chosen λ is optimistic, because picking λ was itself a search: 9.178 reported against 10.087 delivered. That is why the one-standard-error rule is neither superstition nor free lunch — it buys a simpler, steadier choice (λ=300, scoring 10.410) rather than a better score.

On a run with two hundred rows and thirty features, the CV curve dips from 9.626 at λ = 0.1 to 9.178 at λ = 30, then climbs back to 9.943 at 300. The argmin looks clean until you draw the error bars. One standard error there is 0.933, and the whole visible dip between λ = 10 and λ = 300 is 0.766. The entire feature you are reading is smaller than the noise on any one point of it.

So the location of the argmin is being decided by noise, and you can watch that too. Reshuffle the folds forty times and the argmin lands on λ = 100 thirty-six times and on λ = 30 four times. Scored against fifty thousand fresh rows, the truly best setting on this data is λ = 100, with a test error of 9.996 against OLS's 10.367. The noise floor is 9.000, so most of what is left is unreachable.

There is a second problem, and it is Chapter 21's own law turning around on the tool we are using. Taking the minimum of a search over noisy scores is itself a search. So the CV error at the chosen λ is optimistic. Here it says 9.178, while that model's true test error is 10.087. If you must report a number, put an outer loop around the whole λ-choosing procedure. That is nested cross-validation: the inner folds choose λ, the outer folds score the whole procedure that chose it, and no row does both jobs at once.

The one-standard-error rule follows from the flatness. Choose the largest λ, meaning the simplest model, whose CV score is within one standard error of the best. That is not a fudge. It is shrinkage applied to the hyper-parameter itself, justified by the two facts we just watched.

Be honest about what it buys, though, because it is usually oversold. On this data the rule picks λ = 300, whose true test error is 10.410, slightly worse than the argmin's 10.087. It bought a simpler model and a more stable choice, not a better score. That is the trade it always makes, and it is worth making when the basin is flat and you would rather not re-tune every month.

One practical detail carries a real reason behind it, so it is worth a line. Search λ on a logarithmic grid rather than an evenly spaced one. The shrinkage factor d²/(d² + λ) depends on λ relative to , and singular values span orders of magnitude, so a linear grid spends nearly all of its points in a region where nothing changes.

14Three exits closed, and the shape of the idea

Go back to the door Chapter 21 labelled and close all three exits.

Constrain is ridge and lasso: fence the search. Select is lasso, or an economic argument you can defend out loud. Reduce is projecting onto the leading directions before fitting, and Chapter 7's coordinates show it is the same act with a harsher weighting. Principal-components regression uses the first m singular directions fully and the rest not at all, which is a step function of d. Ridge uses every direction by the smooth amount d²/(d² + λ). Same axis, two weighting functions: one a cliff, one a slope. The algorithm behind that projection arrives properly in Chapter 24.

One axis, one λ, three shapes — and a dial that turns what you believe into the number
one axis · d, singular values of X λ = 1.00 1 ½ 0 0.1 1 10 ← weak, noisy directions strong → the exchange rate noise σ² 1.00 belief τ² 1.00 λ = 1.00 you set σ,τ → read λ β mostly within ±1.00 ridge · Gaussian prior you are here · Ch 22 bias² ↑ var ↓ noise — attacks VARIANCE tap to open › attacks BIAS tap to open › the penalty does not price leakage, or the searches you ran by hand — Ch 21 stands
One axis, one λ, three shapes. Flip an exit — then set λ from what you believe.
kept whole2 of 9
set to exactly 00 of 9
smooth — nothing ever hits 0
What you're looking at — three exits turn out to be three weightings of one axis
ridge keeps every direction by d²/(d²+λ) — a slope, so a coefficient shrinks forever and arrives at zero never
PCR is a cliff: the directions above the cut used whole, the rest thrown away entirely
lasso is a threshold: exactly zero below the cut, then climbing — both behaviours in one shape
the gold line is where d² = λ, and λ = σ²/τ² — the noise you admit divided by how big you think the coefficients are. Ridge keeps exactly half of that direction (the gold dot)
Fig. 20. Three exits were named at the top of the chapter — constrain, select, reduce — and they look like three different libraries. Here they are three shapes on one axis. That axis is d, the singular values of X: how much of a direction the data actually contains, with the weak, near-collinear directions on the left and the strong, well-measured ones on the right. Every method here answers exactly one question — how much of each direction do I keep? — and the gold line marks the single place they all pivot: where d² = λ. PCR answers with a cliff, using the directions above the cut in full and discarding everything below. Ridge answers with a slope, d²/(d²+λ), keeping every direction by some amount — and at the cut it keeps exactly half, which is the gold dot. Lasso answers with a threshold: exactly zero below the cut, then climbing, which is why it both selects and shrinks. Nine real directions sit under the curve, so you can watch the bars die or survive as you drag. Now the panel on the right, which is the part that changes what λ is. Minimising RSS + λ‖β‖² is the same act as finding the most probable β under a Gaussian prior centred at zero with variance τ², and the exchange rate is exactly λ = σ²/τ²: the noise you admit is in your data, divided by how large you believe the coefficients are. Run it forwards — set σ and τ, read λ. Run it backwards — set λ, and read off the belief you have just committed to, printed as the band β is claimed to live in. Drag the cut and you are not tuning a constant, you are revising an opinion, and the prior underneath redraws to show it: a smooth Gaussian bell for ridge, a Laplace peak with a corner at zero for lasso — which is the same corner the constraint diamond had, met from the other side — and a spike-and-slab for PCR, which is in-or-out with nothing in between. So λ is a number two people can argue about with evidence, rather than a dial one person turns in silence. The closing strip holds the two terms you now control and the door out: one method will attack the variance term directly, another will attack the bias term, both in Chapter 23. And the red line under it is the sentence that must survive the chapter — the penalty prices the search that ran inside the optimiser, and prices nothing at all about a leaked pipeline or the two hundred variants you tried by hand.

Now the reading that turns the penalty from a device into a statement. Minimising RSS + λ‖β‖₂² is exactly finding the most probable β under a Gaussian prior centred at zero with variance τ², and the exchange rate is λ = σ²/τ². That is the noise in your data divided by how large you believe the coefficients are. Chapter 19 said priors are shrinkage toward zero. This is that sentence with the number filled in, and it means λ is a belief you can argue about with a colleague rather than a constant you tune in silence. The lasso is the same statement with a Laplace prior, whose sharp peak at zero is exactly why it produces exact zeros.

So regularization is not a technique. It is a shape. Whenever the variance of an unconstrained search costs more than the data can pay for, buy it back with structure. Every later chapter is another purchase of the same kind, and you will now recognise them: Chapter 23's bagging averages many fits to attack the variance term directly, boosting fits residuals to attack the bias term, and Chapter 31's covariance shrinkage is this identical move performed on a matrix.

Then the limit, said flatly, because a chapter that ends on a rescue is a dangerous chapter. Regularization does not repair overfitting. It prices it. Every warning from Chapter 21 still stands, unchanged. A leaked pipeline with a beautifully tuned λ is still a leaked pipeline. A strategy selected out of two hundred is still cursed no matter how carefully the survivor was shrunk. The penalty only prices the part of the search that ran inside the optimiser, and the lookbacks you tried, the thresholds you nudged and the reruns after a bad month are all outside it.

Which leaves the door open in a nice place. We now hold two named terms rather than one vague hazard, and the obvious question is what a method would look like that went straight at each one. What attacks the variance term head-on? What attacks the bias term head-on? Chapter 23 is those two answers, and they are called bagging and boosting.

iolinked.com
Written by Ajai Raj