Empirical Risk Minimization
The book’s framing for this section is blunt: “the ‘learning’ part of machine learning boils down to estimating parameters based on training data.” This page is one way to do that, and its distinguishing feature is that no probability distribution ever gets written down.
Empirical risk minimization was popularised by the support vector machine (Chapter 12), but the book is careful that its principles are general — they “allow us to ask the question of what is learning without explicitly constructing probabilistic models.”
What you’ll learn
Section titled “What you’ll learn”- The four design choices of §8.2, and which section answers each.
- §8.2.1: the hypothesis class, and why enlarging it can never raise the training risk. Measured: 0 increases in 15 steps.
- §8.2.2: the loss function, the empirical risk of Equation 8.6, and the i.i.d. assumption that licenses using an empirical mean at all.
- Equation 8.9, the least-squares problem in matrix form, and why it has a closed-form answer.
- Equation 8.10, the expected risk — the thing you actually want and can never compute.
- Measured: the training risk falls monotonically to while the expected risk climbs to , a ratio of 862.
- The book’s closing remark that the loss you optimise is not the measure you are judged on — with two predictors whose ranking reverses between squared and absolute loss.
Intuition: grading yourself on the practice exam
Section titled “Intuition: grading yourself on the practice exam”You want a student who does well on the final. You only have the practice questions.
So you grade on the practice questions and hope. That is empirical risk minimization: minimise the average error on the data you have, because the average error on data you do not have is unavailable by definition.
The failure mode is immediate and it is the subject of §8.2.3 and §8.2.4. A student allowed to memorise the practice answers scores perfectly and learns nothing. And you cannot detect this by looking at the practice score — a memoriser and a genius have identical practice scores. The whole problem is that the quantity you can measure and the quantity you care about are different quantities.
flowchart TD D["training data
(x_1, y_1) ... (x_N, y_N)"] Q1["1. what functions may the predictor be?
Section 8.2.1"] Q2["2. how do we score it on the training data?
Section 8.2.2"] Q3["3. how do we make it generalise?
Section 8.2.3"] Q4["4. how do we search the space of models?
Section 8.2.4"] D --> Q1 --> Q2 --> RE["R_emp, Eq 8.6
computable"] RE --> Q3 --> Q4 RT["R_true, Eq 8.10
the expectation over ALL data"] RE -.->|"underestimates"| RT Q3 --> RT Q4 --> RT style RT stroke-dasharray: 4 3
The dashed node is the point of the whole section. is what “good” means, it is defined as an expectation over an infinite population, and it is not available. Everything else is machinery for coping with that.
§8.2.1 The hypothesis class
Section titled “§8.2.1 The hypothesis class”Given examples with scalar labels , we want a predictor and a good parameter such that
Write for the predictor’s output.
Example 8.1 picks the class: affine functions. Using the unit-feature trick from §8.1,
so . Every straight-line predictor in the chapter’s figures is this.
§8.2.2 The loss function, and the empirical risk
Section titled “§8.2.2 The loss function, and the empirical risk”A loss function takes a label and a prediction and returns a non-negative number. The book notes “error” is often used to mean loss.
Then comes the assumption that makes the whole framework work:
One assumption that is commonly made in machine learning is that the set of examples is independent and identically distributed.
Independence (§6.4.5) means two data points do not statistically depend on each other, which means “the empirical mean is a good estimate of the population mean” (§6.4.1). That is what licenses averaging the loss over the training set rather than doing something more careful.
Stacking examples into and labels into :
This is the empirical risk, and minimising it is empirical risk minimization. Note it depends on three things — the predictor and the data — which is what makes the notation worth carrying: the same has a different empirical risk on a different dataset, and §8.2.4 exploits exactly that.
Example 8.2: least squares
Section titled “Example 8.2: least squares”Take the squared loss . Then
and with the linear predictor ,
This is the least-squares problem, and it has a closed-form solution via the normal equations — developed properly in §9.2. Measured on degree-3 features: both forms of Equation 8.9 give , as they must.
Equation 8.10: the expected risk
Section titled “Equation 8.10: the expected risk”Here is what we actually want:
The expectation is over the infinite set of all possible data and labels. The book’s own note is that this is also called the population risk.
Two things follow, and they are §8.2.3 and §8.2.4:
- How should we change training so that it generalises well? → regularisation.
- How do we estimate the expected risk from finite data? → cross-validation.
Worked example by hand
Section titled “Worked example by hand”Take four points and fit the affine class by hand, then check what a richer class does.
Step 1: the affine fit. With the unit feature, . Then , , , , :
So , giving predictions and residuals .
Step 2: the empirical risk.
Step 3: what a quadratic does. Add an column. The data was generated by exactly — check: , , , . So the quadratic class contains a member with , and least squares will find it: .
Step 4: what that proves and what it does not. The quadratic beat the affine model to on training risk. It happens to be right here — but the reason it won is only that it had three parameters for four points. A cubic would also achieve , and so would every higher degree. Training risk cannot distinguish “correct” from “flexible enough to interpolate”. With four points a degree-3 polynomial achieves exactly zero on any data whatsoever, and that is the trap.
See it move
Section titled “See it move”The four design choices interact. Change the class and watch both risks move in opposite directions:
From scratch
Section titled “From scratch”import numpy as np
def make(n, seed, noise=0.35):
rng = np.random.default_rng(seed)
x = np.sort(rng.uniform(-3, 3, n))
return x, np.sin(1.4 * x) + 0.3 * x + noise * rng.standard_normal(n)
def design(x, deg):
"""The hypothesis class of Section 8.2.1: unit feature first, Eq 8.5."""
return np.vander(x / 3.0, deg + 1, increasing=True)
def empirical_risk(y, yhat):
"""Equation 8.6 with the squared loss of Example 8.2."""
return float(np.mean((y - yhat) ** 2))
xtr, ytr = make(25, seed=3) # the training set
xte, yte = make(4000, seed=99) # a stand-in for the infinite population
# --- Example 8.2 in matrix form, Eq 8.9 ----------------------------------
A = design(xtr, 3)
theta = np.linalg.lstsq(A, ytr, rcond=None)[0]
N = len(ytr)
print("Equation 8.9 written two ways, degree 3:")
print(f" (1/N) ||y - X theta||^2 = "
f"{np.linalg.norm(ytr - A @ theta) ** 2 / N:.9f}")
print(f" (1/N) sum (y_n - theta.x_n)^2 = {empirical_risk(ytr, A @ theta):.9f}")
# --- Eq 8.6 against Eq 8.10 ---------------------------------------------
print(f"\n{'degree':>7} {'R_emp (Eq 8.6)':>16} {'R_true (Eq 8.10)':>18} "
f"{'ratio':>8} {'||theta||':>13}")
rows = []
for d in range(0, 16):
Ad = design(xtr, d)
th = np.linalg.lstsq(Ad, ytr, rcond=None)[0]
remp = empirical_risk(ytr, Ad @ th)
rtrue = empirical_risk(yte, design(xte, d) @ th)
rows.append((d, remp, rtrue, float(np.linalg.norm(th))))
print(f"{d:>7} {remp:>16.6f} {rtrue:>18.6f} {rtrue / remp:>8.2f} "
f"{np.linalg.norm(th):>13.4f}")
best = min(rows, key=lambda r: r[2])
worst = rows[-1]
print(f"\nlowest expected risk at degree {best[0]}: {best[2]:.6f}")
print(f"R_emp never increases: "
f"{int(sum(1 for a, b in zip(rows, rows[1:]) if b[1] > a[1] + 1e-12))} "
f"increases in 15 steps")
print(f"at degree 15 the ratio is {worst[2] / worst[1]:.0f}x and "
f"||theta|| is {worst[3]:.1f}")
print(f" which is {worst[3] / best[3]:.0f} times its value at degree {best[0]}")
# --- Section 8.2.2's closing remark: loss is not the measure -------------
print("\nTwo predictors, three measures (Section 8.2.2's remark):")
rng = np.random.default_rng(5)
n = 200
truth = np.zeros(n)
A_pred = 0.55 * np.ones(n) # wrong everywhere, but only a little
B_pred = np.zeros(n)
B_pred[:12] = 3.4 # exact on 188 points, badly wrong on 12
measures = {
"squared": lambda r: (r ** 2).mean(),
"absolute": lambda r: np.abs(r).mean(),
"tolerance": lambda r: (np.abs(r) > 1.0).mean(),
}
print(f"{'measure':>11} {'A':>12} {'B':>12} winner")
for name, fn in measures.items():
va, vb = fn(truth - A_pred), fn(truth - B_pred)
print(f"{name:>11} {va:>12.4f} {vb:>12.4f} "
f"{'A' if va < vb else 'B'}")
print("A is wrong on all 200 points by 0.55; B is exact on 188 and off by 3.4")
print("on 12. Squared loss and the tolerance measure prefer A; absolute loss")
print("prefers B. Optimising one of these does not optimise another.")Equation 8.9 written two ways, degree 3:
(1/N) ||y - X theta||^2 = 0.146372862
(1/N) sum (y_n - theta.x_n)^2 = 0.146372862
degree R_emp (Eq 8.6) R_true (Eq 8.10) ratio ||theta||
0 0.993663 0.961461 0.97 0.0701
1 0.599241 0.555955 0.93 1.1256
2 0.565048 0.600537 1.06 1.3082
3 0.146373 0.186855 1.28 5.4910
4 0.129272 0.211295 1.63 6.2030
5 0.100580 0.152753 1.52 11.2386
6 0.100253 0.151857 1.51 11.8253
7 0.100134 0.154089 1.54 10.4195
8 0.099982 0.153867 1.54 14.7397
9 0.090056 0.244194 2.71 158.3732
10 0.087573 0.271401 3.10 260.7562
11 0.084463 0.220716 2.61 762.6160
12 0.066555 0.670332 10.07 4200.4882
13 0.051236 3.894409 76.01 12569.5246
14 0.051216 4.084932 79.76 12095.5872
15 0.046494 40.077320 862.00 81050.6045
lowest expected risk at degree 6: 0.151857
R_emp never increases: 0 increases in 15 steps
at degree 15 the ratio is 862x and ||theta|| is 81050.6
which is 6854 times its value at degree 6
Two predictors, three measures (Section 8.2.2's remark):
measure A B winner
squared 0.3025 0.6936 A
absolute 0.5500 0.2040 B
tolerance 0.0000 0.0600 A
A is wrong on all 200 points by 0.55; B is exact on 188 and off by 3.4
on 12. Squared loss and the tolerance measure prefer A; absolute loss
prefers B. Optimising one of these does not optimise another.On real data
Section titled “On real data”Reading the plot
Section titled “Reading the plot”The first figure is the section’s whole argument in two curves. The blue curve is , Equation 8.6 — the thing you can compute. It falls at every single step, from at degree to at degree . There is no kink, no elbow, and no signal in its shape that says stop here.
The red curve is , Equation 8.10 — estimated on points the model never saw. It turns at degree with a value of , and then climbs to . The ratio between them reaches . The shaded band is the generalisation gap, and the book’s definition of overfitting is exactly that the training risk underestimates the expected risk: measured here, the ratio exceeds from degree onward and never returns.
The right panel is worth pairing with the left because it shows the symptom rather than the disease. The book’s remark, citing Bishop (2006), is that “the magnitude of the parameter values becomes relatively large if we run into overfitting”. Measured: goes from at the best degree to at degree — a factor of . That is a signal you can compute from training data alone, and it is precisely what §8.2.3’s penalty term attacks.
The second figure separates two kinds of failure. The left panel’s red line is the affine class of Equation 8.4, and its problem is not that the optimiser did badly — it is that no member of the class can bend. That is underfitting, and it is a property of the class you chose, not of the search you ran. More iterations, a better step size, a different initialisation: none of it helps.
The right panel is the fact that makes model selection necessary. Enlarging the class raised the training risk zero times in fifteen attempts, and that is not a property of this dataset. A degree- polynomial is a degree- polynomial with the top coefficient set to zero, so the larger class literally contains the smaller one’s best answer. Any criterion that only looks at training risk will always choose the largest class available. Given that, §8.2.3 and §8.2.4 are not refinements; they are the only things standing between you and degree .
The third figure is the one people skip and shouldn’t. Predictor A is mediocre everywhere; predictor B is excellent almost everywhere and terrible occasionally. Which is better? The honest answer is it depends what you are going to do with it — and the three measures disagree.
Squared loss puts A ahead by , because squaring turns twelve errors of into a large number. Absolute loss puts B ahead by , because it counts A’s two hundred small errors at face value. The tolerance measure — does the prediction land within ? — scores A at exactly , a perfect record, because .
So the same two predictors are ranked in two different orders by three reasonable measures. The book’s point is that the loss you optimise is chosen for optimisation convenience (squared loss is smooth and has a closed form; the tolerance measure has zero gradient almost everywhere), while the measure you are judged on comes from the application. When those differ, a training log full of falling squared loss tells you nothing about the number you will be evaluated on.
Pitfalls
Section titled “Pitfalls”Compare
Section titled “Compare”| empirical risk, Eq 8.6 | expected risk, Eq 8.10 | |
|---|---|---|
| what it averages over | your training points | the infinite population |
| computable | yes | no, ever |
| notation | ||
| depends on the data | yes, explicitly | no — the data is integrated out |
| behaviour as the class grows | never increases | turns |
| measured at degree 6 | ||
| measured at degree 15 | ||
| estimated by | — | a test set, or §8.2.4’s cross-validation |
| design choice | question | section |
|---|---|---|
| hypothesis class | what functions may be? | §8.2.1 |
| loss function | how well does do on the training data? | §8.2.2 |
| regularisation | how do we build predictors that generalise? | §8.2.3 |
| search procedure | how do we explore the space of models? | §8.2.4 |
-
Why can the training risk never increase when you enlarge the hypothesis class?
Nested classes contain each other's optima, so this is structural rather than empirical — measured, zero of fifteen steps raised the training risk. The consequence is the important part: any criterion based on training risk alone will always choose the largest class available.
pch.quizShowAnswer
B — Because a degree-d polynomial IS a degree-(d+1) one with the top coefficient zero, so the larger class contains the smaller one's best answer — Nested classes contain each other's optima, so this is structural rather than empirical — measured, zero of fifteen steps raised the training risk. The consequence is the important part: any criterion based on training risk alone will always choose the largest class available.
-
What does the book define overfitting as, precisely?
The definition is a relation between two numbers for one fixed predictor, not a property of the parameter count. Measured on the sweep, the ratio exceeds one from degree 2 onward and reaches 862 by degree 15 — while the training risk kept falling.
pch.quizShowAnswer
B — The training risk UNDERESTIMATING the expected risk for a given predictor — The definition is a relation between two numbers for one fixed predictor, not a property of the parameter count. Measured on the sweep, the ratio exceeds one from degree 2 onward and reaches 862 by degree 15 — while the training risk kept falling.
-
Predictor A is off by 0.55 on all 200 points; B is exact on 188 and off by 3.4 on twelve. Which is better?
Three reasonable measures, two different winners. The book's remark is that the loss you optimise is usually chosen for optimisation convenience while the measure you are judged on comes from the application — so a training log of falling squared loss says nothing about a reported mean absolute error.
pch.quizShowAnswer
C — It depends on the measure: squared and tolerance prefer A, absolute prefers B, and the ranking genuinely reverses — Three reasonable measures, two different winners. The book's remark is that the loss you optimise is usually chosen for optimisation convenience while the measure you are judged on comes from the application — so a training log of falling squared loss says nothing about a reported mean absolute error.
-
What role does the i.i.d. assumption play in Equation 8.6?
Section 8.2.2 gives exactly this justification, pointing at Sections 6.4.5 and 6.4.1. With time series or repeated measures the assumption fails and the average training loss is no longer estimating what you think — a problem that arrives before any question of overfitting.
pch.quizShowAnswer
B — Independence makes the empirical mean a good estimate of the population mean, which is what licenses averaging the loss at all — Section 8.2.2 gives exactly this justification, pointing at Sections 6.4.5 and 6.4.1. With time series or repeated measures the assumption fails and the average training loss is no longer estimating what you think — a problem that arrives before any question of overfitting.
-
You fit a degree-(N-1) polynomial to N points and get exactly zero training risk. What have you learned?
Interpolation and correctness are indistinguishable from the training risk. In the worked example the quadratic that reached zero happened to be right, but a cubic would also reach zero on the same four points — and the training risk cannot tell them apart.
pch.quizShowAnswer
B — Nothing: any degree-(N-1) polynomial interpolates any N points, so zero training risk is guaranteed regardless of the data — Interpolation and correctness are indistinguishable from the training risk. In the worked example the quadratic that reached zero happened to be right, but a cubic would also reach zero on the same four points — and the training risk cannot tell them apart.
🧪 Try It Yourself
Section titled “🧪 Try It Yourself”Exercise 1 – Equation 8.9, two ways
Section titled “Exercise 1 – Equation 8.9, two ways”Exercise 2 – The training risk never rises
Section titled “Exercise 2 – The training risk never rises”Exercise 3 – The generalisation gap
Section titled “Exercise 3 – The generalisation gap”Exercise 4 – The parameter norm is the symptom
Section titled “Exercise 4 – The parameter norm is the symptom”Exercise 5 – Three measures, two winners
Section titled “Exercise 5 – Three measures, two winners”Recall card
Section titled “Recall card”- Four design choices, and the book numbers them: the hypothesis class (8.2.1), the loss function (8.2.2), regularisation (8.2.3), and the search procedure (8.2.4).
- Equation 8.6, the empirical risk, is the average loss over your N training points. Note it takes THREE arguments — the predictor and the data — because the same f scores differently on different data, which is what cross-validation exploits.
- The i.i.d. assumption is load-bearing. Independence is what makes the empirical mean a good estimate of the population mean, and therefore what licenses averaging the loss at all. Time series and repeated measures break it.
- Equation 8.10, the expected risk, is an expectation over the infinite population. It is what “good” means and it is never computable.
- Overfitting is defined as a relation between the two: the training risk UNDERESTIMATING the expected risk for a fixed predictor. It is not a statement about parameter counts.
- A bigger class can never fit the training data worse, because a degree-d polynomial is a degree-(d+1) one with a zero top coefficient. Measured: zero increases in fifteen steps. So training risk alone always endorses the largest class available.
- Measured sweep: training risk falls from 0.993663 to 0.046494 while the expected risk turns at degree 6 (0.151857) and reaches 40.077320 at degree 15 — a ratio of 862.
- The symptom you CAN compute is the parameter norm. It goes from 11.8253 at the best degree to 81050.6045 at degree 15, a factor of 6854 — which is the book’s Bishop (2006) remark, and exactly what Section 8.2.3 penalises.
- Underfitting is a property of the class, not the search. The affine class cannot bend; no step size or initialisation fixes that.
- Zero training risk proves nothing. Any degree-(N-1) polynomial interpolates any N points, so interpolation and correctness are indistinguishable from the training risk.
- The loss you optimise is not the measure you are judged on. Measured: predictor A beats B on squared loss (0.3025 to 0.6936) and loses on absolute loss (0.5500 to 0.2040). The ranking reverses, and the book notes the mismatch is usual rather than exceptional.
- Example 8.2’s least-squares problem has a closed form, via the normal equations of Section 9.2 — one of the few places in the chapter where the optimisation is free.
Next: the two repairs — bias the search, and estimate the risk you cannot compute. Regularization and Cross-Validation
pch.coffeeTagline
pch.coffeeCtapch.feedbackHeading
pch.feedbackSubheading