Part II · Chapter 5

How a machine learning problem is set up

By the end of this page you can take any vague request — "predict whether this patient is ill" — and write it down as $\X$, $\Y$, $\D$, $\ell$, $\H$, and an $\argmin$, which is the only form a computer can actually solve.

Essentials

How to turn a vague request into $\X$, $\Y$, $\D$, $\ell$, $\H$ and an $\argmin$ — the only form a computer can solve.

Everything below is the explanation and the practice. If you are short on time, read this box, then go to the problems.

Why we stopped writing rules

For decades "AI" mostly meant rule-based AI: an expert and a programmer writing out the conditions for each conclusion explicitly — IF pressure > 90 AND valve_state = open THEN raise alarm — thousands of rules in a hand-maintained if/else forest. The notes' example, AT&T diagnosing telephone-line faults from logs, is a domain where that is the right tool, and the three reasons why are exactly the reasons it collapses elsewhere: the input is already symbolic (named events, not raw physics), the experts can say their rules out loud, and the rule count is finite and stable.

The pixel-space argument

Now change one thing: the input is a photograph and the question is "is there a cat in this picture?" The notes put it in one line — how do you describe a picture in pixel space? — and that line is why machine learning exists.

A modest $1000 \times 1000$ colour photo is $1000 \times 1000 \times 3 = 3{,}000{,}000$ numbers, each in $\{0,\dots,255\}$. There is no field called has_cat; there is pixel[417][233].red = 118, and your rule has to be written in those terms. Try it — "if pixel $(417,233)$ is brownish and…" — and it falls apart immediately:

Key idea

The deepest problem is not that the rules would be numerous. It is that you do not know what your own rules are. You recognise a cat in about 150 milliseconds and cannot introspect a single condition you used — you cannot type in knowledge you have no conscious access to. But you can look at 10,000 pictures and say "cat / not cat" for each. Examples are cheap where rules are impossible, and machine learning is the discipline of turning examples into a rule automatically, without the rule ever passing through a human's vocabulary.

Common mistake

Concluding "rules are obsolete." The course notes say rule-based AI is "OK for some applications," and it is: tax calculation, chess move legality, payroll, access control, a thermostat. Where the rules are known, stable, auditable and legally mandated, a rule system wins — it is exactly reproducible, it explains itself, and it needs zero data. Reach for learning when the rules exist in the world but not in anyone's head.

The setup: inputs, outputs, and the function in between

The formal skeleton. Everything in Part II hangs on it.

Definition

Inputs live in a set $\X$ (the input space). Outputs, also called labels, live in a set $\Y$ (the output space or label space).

Our goal is to come up with a function $$ h : \X \to \Y $$ such that for a new input $x \in \X$ whose true label is $y$, we have $h(x) = y$.

Every symbol, in words:

Note what $h$ is not: a lookup table of answers you already have. $h$ must be defined on all of $\X$, including inputs nobody has ever seen — the requirement that makes the problem hard, and whose name is generalization.

Training data

Definition

We are given examples $\big(x^{(1)}, y^{(1)}\big), \big(x^{(2)}, y^{(2)}\big), \dots, \big(x^{(N)}, y^{(N)}\big)$, collected into $$ \D = \big\{ \big(x^{(i)}, y^{(i)}\big) \big\}_{i=1}^{N}. $$ These are called the training data, or samples, or datapoints — three names for the same thing. $N$ is the sample size, and $x^{(i)} \in \X,\ y^{(i)} \in \Y$ for all $i \in \{1,2,\dots,N\}$.

Common mistake

Notation alert — the single most misread symbol in this course.

$x^{(i)}$ is the $i$-th sample. The superscript is an index, not an exponent. $x^{(3)}$ is the third datapoint; it is not $x$ cubed.

The parentheses do the work: $x^{(i)}$ (index) versus $x^i$ (power). Do not drop them when writing by hand.

Second layer: when each input is a vector of $d$ features, $x^{(i)}_j$ is the $j$-th feature of the $i$-th sample. Superscript in parentheses = which datapoint; subscript = which feature. So $x^{(4)}_2$ is "sample 4, feature 2" — constant in linear regression, so get it straight now.

A dataset is a table: one row per sample, one column per feature, plus a label column. One we will reuse — five houses, $d = 3$ features, $N = 5$:

$i$$x^{(i)}_1$ — size (sq ft)$x^{(i)}_2$ — bedrooms$x^{(i)}_3$ — age (yrs)$y^{(i)}$ — price ($1000s)
11400312245
2210043410
3900240150
41650325280
5300058520

In the notation: $N = 5$, $d = 3$, $\X = \R^3$, $\Y = \R$. The third row is $\big(x^{(3)}, y^{(3)}\big)$ with $x^{(3)} = (900, 2, 40)$, $y^{(3)} = 150$, and $x^{(3)}_3 = 40$ — sample 3, feature 3, the age.

Training versus inference

Definition

Training is the process of using $\D$ to produce $h$. It happens once, offline, with the labels visible.

Inference is the process of applying an already-chosen $h$ to a new input $x^{(\text{new})}$ to predict its label. It happens many times, in deployment, with the true label unknown (or not yet known).

Keeping these apart is the discipline of the whole subject: training consumes labels, inference does not have them. Anything that touches $y^{(\text{new})}$ at inference time is cheating, and most embarrassing ML bugs are a version of that cheating (leakage).

Figure 1 — the training / inference pipeline
TRAINING — once, labels visible Training data 𝒟 N pairs (x⁽ⁱ⁾, y⁽ⁱ⁾) Learning algorithm pick h ∈ ℋ minimising R̂(h) model h h : 𝒳 → 𝒴 the same h is reused INFERENCE — many times, label unknown new input x⁽ⁿᵉʷ⁾ never seen in 𝒟 h apply, don't change ŷ = h(x⁽ⁿᵉʷ⁾) the prediction ℓ(ŷ, y⁽ⁿᵉʷ⁾) test error
What to notice: the dashed arrow. Training runs once and its output is a function; inference runs forever and never modifies that function. The red box on the right can only be evaluated when a true label eventually arrives — which is why we cannot optimise it directly, and why the rest of this page exists.
Key idea

The two questions the whole course answers: (Q1) how do we come up with $h$? — empirical risk minimization on this page, made concrete by decision trees, linear regression and logistic regression. (Q2) how do we measure its performance? — loss functions and risk, below. Q2 comes first in practice: you cannot search for a good $h$ until "good" is written down as a number.

Two kinds of task: classification and regression

The notes split ML tasks in two, entirely by looking at $\Y$ — not at $\X$, not at the algorithm.

Definition

Classification: $\Y$ is finite and its elements are unordered. The special case $|\Y| = 2$ is called binary classification.

Regression: $\Y$ is continuous and ordered.

Both adjectives do real work. Finite vs continuous decides whether "close" is a coherent idea: between two house prices there is another house price, between "cat" and "dog" there is nothing. Unordered vs ordered decides whether being wrong can be wrong by an amount: predicting 420 when the truth is 410 is a small error, while predicting "dog" for a cat is not 10% wrong, just wrong.

Classification
  • Spam / not spam. $\Y = \{0,1\}$, binary.
  • Handwritten digit recognition. $\Y = \{0,1,\dots,9\}$ — looks numeric, but "7" is a name, not a quantity, so it is 10-way classification.
  • Which of 3 iris species. $\Y = \{\text{setosa}, \text{versicolor}, \text{virginica}\}$.
  • Does this patient have the disease? $\Y = \{\text{healthy}, \text{ill}\}$.
Regression
  • House price from size, bedrooms, age. $\Y = \R$ (really $\R_{\geq 0}$).
  • Tomorrow's temperature in Pittsburgh. $\Y = \R$.
  • Remaining battery life in minutes.
  • Blood glucose level from a sensor trace.

A genuinely ambiguous case

Predict the star rating (1–5) a user will give a restaurant.

$\Y = \{1,2,3,4,5\}$ is finite (classification) but also ordered — predicting 4 when the truth is 5 is a better mistake than predicting 1 (regression). The notes' definitions genuinely disagree here; this is a third category, ordinal regression beyond syllabus, not covered. Decide by asking what the loss function should be, since that is what the choice actually controls:

Intuition

The test that never fails: is the average of two labels a meaningful label? The average of 245 and 410 is 327.5, a sensible house price — regression. The average of "cat" and "dog" is nothing — classification. The average of digit-label 3 and digit-label 9 is 6, a different digit rather than a blend — so digits are classification, despite the numerals.

Guided problem 1Classification or regression?

For each scenario, state $\X$ and $\Y$, say whether it is classification or regression, and justify from the definition (finite/unordered vs continuous/ordered). Three of these are traps.

  1. From a photo of a skin lesion, predict which of 7 diagnoses applies.
  2. From last month's usage, predict a household's electricity bill in dollars.
  3. From an address, predict the 5-digit ZIP code.
  4. From a patient's vitals, predict how many days they will stay in hospital.
  5. From an essay, predict the grade on a 0–100 scale.
  6. From a sensor, predict whether a machine will fail in the next hour.

Attempt all six before opening anything.

Step 1 — Apply the "is the average meaningful?" test to each

1. average of "melanoma" and "eczema" = nothing → classification.
2. average of $\$84.20$ and $\$97.10$ = $\$90.65$, a fine bill → regression.
3. average of ZIP 15213 and ZIP 90210 = 52711.5, which is not a place → classification (the trap).
4. average of 3 days and 4 days = 3.5 days, meaningful → regression-ish, but see Step 2.
5. average of 78 and 84 = 81, a fine grade → regression.
6. average of "fails" and "doesn't fail" = nothing → classification.

Step 2 — The traps, in detail

(3) ZIP codes. Numerals are not numbers. A ZIP code is a name that happens to be spelled with digits, exactly like a digit-recognition label. $\Y$ is finite (~41,000 codes) and unordered. It is classification — a gigantic 41,000-way classification, which is itself a hint that you have formulated the problem badly and should predict latitude/longitude (regression) or a coarse region instead.

(4) Length of stay. $\Y = \{0,1,2,\dots\}$ is discrete and countably infinite, so it is neither "finite unordered" nor strictly "continuous". It is count data. In this course you treat it as regression: it is ordered, magnitude of error matters, and squared error on a real-valued prediction behaves sensibly. (Outside this course you would reach for Poisson regression. beyond syllabus)

(5) Essay grade. Also boundary — 101 possible values, ordered. Regression, for the same reason as star ratings: you care how far off you are.

Answer & the takeaway

1 classification (7-way) · 2 regression · 3 classification (not regression!) · 4 regression (count) · 5 regression (ordinal, treated as regression) · 6 binary classification.

Takeaway: the question "classification or regression?" is never answered by looking at whether the labels are typed with digits. It is answered by asking whether $\Y$ carries a meaningful notion of distance. And the real reason you care is that the answer determines which loss function you are allowed to use — which is the next section.

A colleague is predicting which of 12 bus routes a commuter will take. They encode the routes as $1,\dots,12$ and fit a model with squared error loss. What is the main thing wrong with this?
Why: $\Y$ here is finite and unordered — route 12 is not "further away" from route 1 than route 2 is. Squared error silently invents a geometry on the label set. The model will happily predict $6.5$, which corresponds to no route at all, and will be pushed toward the numeric middle of the routes. Use zero-one loss (or a 12-way classifier with a proper classification loss) instead. Option C is wrong: squared error is fine for any continuous $\Y$, binary or not — the problem is the label set, not its size.

Loss functions: writing down what "wrong" costs

Q2 was: how do we measure performance? The answer is a loss function.

Definition

A loss function is a map $$ \ell : \Y \times \Y \to \R, \qquad \text{usually } \ell \geq 0, $$ which takes a predicted label and a true label and returns a single number saying how bad that pairing is. Lower is better, and $\ell = 0$ means a perfect prediction.

Read the type signature literally: $\Y \times \Y$ is "a pair of labels" and $\to \R$ is "out comes one real number" — not a vector, not a verdict. Everything messy about "is this model any good?" has to be crushed into a scalar, because optimisation algorithms can only minimise scalars.

Common mistake

The argument-order trap. Your two course documents disagree, and you must check every single time.

Both conventions are standard in the literature. Neither is wrong. For symmetric losses — zero-one, squared error, absolute error — it does not matter, because $\ell(a,b) = \ell(b,a)$. For asymmetric losses it matters enormously: swapping the arguments turns a 10-point penalty for missing a sick patient into a 10-point penalty for alarming a healthy one, which is a completely different medical product.

Rule for exams and for life: on every problem, before computing anything, find the sentence or the table header that fixes the convention. If it is a table, look at whether the rows are labelled $y$ or $\hat y$. If the problem does not say, state your assumption in your answer.

Classification loss: zero-one

For classification the only question is "right or wrong?", so:

$$ \ell(\hat y, y) \;=\; \1\{\hat y \neq y\} $$

where $\1\{\cdot\}$ is the indicator function:

$$ \1\{z\} = \begin{cases} 1 & \text{if } z \text{ is true} \\ 0 & \text{if } z \text{ is false.} \end{cases} $$

So the loss is $1$ when prediction and truth differ and $0$ when they match. The indicator is just a way of writing "if" inside an algebraic expression so it can be summed — it returns in majority vote and entropy.

Example

True labels $y = (\text{spam}, \text{ham}, \text{spam}, \text{spam}, \text{ham})$; predictions $\hat y = (\text{spam}, \text{spam}, \text{spam}, \text{ham}, \text{ham})$.

Per-sample zero-one losses: $0, 1, 0, 1, 0$. Sum $= 2$, average $= 2/5 = 0.4$. That average is called the classification error rate — and, as we will see in a moment, it is literally the empirical risk under zero-one loss. The two names are the same quantity.

Asymmetric classification loss

Zero-one loss says every mistake costs the same; in medicine that is plainly false. With $y = 1$ meaning ill and $y = 0$ meaning healthy, the two failure modes are a false positive (prediction ill, truth healthy: $\hat y = 1$, $y = 0$ — an unnecessary biopsy) and a false negative (prediction healthy, truth ill: $\hat y = 0$, $y = 1$ — the patient goes home and the tumour keeps growing). These are not equally bad, so they do not get equal loss. The notes' table, reproduced exactly — convention: rows are the truth $y$, columns the guess $\hat y$, i.e. $\ell(y, \hat y)$:

$\ell(y,\hat y)$$\hat y = 0$$\hat y = 1$
$y = 0$02
$y = 1$100

The four cells: $\ell(0,0) = 0$ and $\ell(1,1) = 0$ — correct answers are free; $\ell(y=0, \hat y=1) = 2$ — healthy called ill, a false positive; $\ell(y=1, \hat y=0) = 10$ — ill called healthy, a false negative. The diagonal is zero and the off-diagonal is asymmetric: a false negative is five times worse than a false positive.

Key idea

An asymmetric loss makes the trained model trigger-happy in the expensive direction. Missing an ill patient costs 10 and flagging a healthy one costs 2, so the model can afford up to five false alarms to avoid one miss and still come out ahead: training under this loss shifts the decision boundary toward $\hat y = 1$, producing a cautious, over-referring model. Same data, same features, same model family — four numbers in a table, and the deployed behaviour changes completely. The loss function is where your values enter the mathematics.

Quantitatively: under this loss you should predict "ill" whenever the expected cost of saying healthy exceeds the expected cost of saying ill. If $p$ is the probability the patient is ill, saying healthy costs $10p$ and saying ill costs $2(1-p)$. Predict ill when $10p \gt 2(1-p)$, i.e. $12p \gt 2$, i.e. $p \gt 1/6 \approx 0.167$. Under plain zero-one loss the same computation gives the threshold $p \gt 1/2$. The asymmetric loss has moved the operating threshold from 50% down to 17% — the model refers anyone with better than a one-in-six chance of illness.

Guided problem 2The choice of loss flips which model wins

A clinic has $N = 5$ patients. $y = 1$ means ill, $y = 0$ means healthy. Two candidate models, $h_A$ (eager to refer) and $h_B$ (conservative), give these predictions:

$i$$y^{(i)}$$h_A(x^{(i)})$$h_B(x^{(i)})$
1000
2010
3010
4110
5111

Compute the average loss of each model (a) under zero-one loss, and (b) under the medical table above. Then say which model you would deploy.

Step 1 — Mark where each model is wrong

$h_A$: correct on $i=1$ ($0{\to}0$), wrong on $i=2$ ($y=0,\hat y=1$, false positive), wrong on $i=3$ (false positive), correct on $i=4$, correct on $i=5$. So 2 mistakes, both false positives.

$h_B$: correct on $i=1,2,3$ (all $0{\to}0$), wrong on $i=4$ ($y=1,\hat y=0$, false negative), correct on $i=5$. So 1 mistake, a false negative.

Step 2 — Average zero-one loss

$\hat R_{01}(h_A) = \tfrac{1}{5}(0+1+1+0+0) = \tfrac{2}{5} = 0.40$.

$\hat R_{01}(h_B) = \tfrac{1}{5}(0+0+0+1+0) = \tfrac{1}{5} = 0.20$.

Under zero-one loss, $h_B$ wins — it has half the error rate.

Step 3 — Average asymmetric loss

Look up each mistake in the table. $h_A$'s two errors are false positives at cost 2 each:

$\hat R_{\text{med}}(h_A) = \tfrac{1}{5}(0 + 2 + 2 + 0 + 0) = \tfrac{4}{5} = 0.80$.

$h_B$'s single error is a false negative at cost 10:

$\hat R_{\text{med}}(h_B) = \tfrac{1}{5}(0 + 0 + 0 + 10 + 0) = \tfrac{10}{5} = 2.00$.

Under the medical loss, $h_A$ wins, and it is not close — $h_B$ is 2.5× worse.

Answer & the takeaway

Zero-one ranking: $h_B \succ h_A$ (0.20 vs 0.40). Medical ranking: $h_A \succ h_B$ (0.80 vs 2.00). The ranking flipped with no change to the data or the models.

You would deploy $h_A$, because in this application the loss table — not the accuracy — encodes what the clinic actually cares about. $h_B$ has the better accuracy and the worse outcome: it achieves its accuracy by refusing to refer anyone, and one of the people it refuses is genuinely ill.

Takeaway: "which model is better?" is a question with no answer until a loss function is named. When a paper, a vendor or a classmate says "our model is 94% accurate", the correct first question is: accurate under which loss, and is that the loss your problem has?

Regression loss: squared error

For regression the magnitude of the miss matters, so the standard choice is the squared error:

$$ \ell(\hat y, y) = (\hat y - y)^2. $$

The quantity $r = \hat y - y$ is the residual: how far off you were and in which direction. Squaring discards the direction (10 over is as bad as 10 under) and keeps the magnitude. Why square rather than take $|\hat y - y|$, which also discards the sign? Four reasons, three of them good:

  1. Differentiability. $\frac{d}{d\hat y}(\hat y - y)^2 = 2(\hat y - y)$ — defined everywhere and proportional to the error: big miss, big push. The absolute value has a kink at $0$ where the derivative jumps from $-1$ to $+1$ and is undefined exactly at the optimum, and every method in Chapter 9 follows derivatives.
  2. It penalises large errors disproportionately. Doubling the error quadruples the loss: being off by 10 costs 100, while ten errors of 1 cost 10 in total. So it prefers "wrong by a little, everywhere" to "right everywhere but catastrophic once".
  3. It connects to the mean. This is the mathematically deep reason. Suppose you must predict a single constant $c$ for all of $y^{(1)},\dots,y^{(N)}$. Minimising $\sum_i (c - y^{(i)})^2$: differentiate and set to zero, $$ \frac{d}{dc}\sum_{i=1}^N (c - y^{(i)})^2 = 2\sum_{i=1}^N (c - y^{(i)}) = 0 \;\Longrightarrow\; Nc = \sum_i y^{(i)} \;\Longrightarrow\; c = \frac{1}{N}\sum_i y^{(i)} = \bar y. $$ The minimiser of squared error is the mean. (Minimising absolute error instead gives the median.) Every closed-form result in linear regression — including the normal equation — exists because squared error is a quadratic whose derivative is linear, so setting it to zero gives a linear system you can solve exactly. Choose any other loss and you generally lose the closed form.
  4. The honest fourth reason: it is what everyone else does, which makes results comparable.
Common mistake

The downside of squaring: outliers. One mistyped house price of $\$45{,}000{,}000$ contributes a residual of $\sim 4.5\times10^7$, whose square is $\sim 2\times10^{15}$ — more than the total loss of every other point combined, so the fit bends toward the typo and serves the other 999 houses worse.

Because the minimiser of squared error is the mean, and the mean is not robust, squared-error regression is not robust. With heavy tails or data-entry errors, absolute error (which yields the median) or a Huber loss beyond syllabus is the better choice: you give up the closed form to get the robustness.

Figure 2 — the three losses as functions of the residual $r = \hat y - y$
0 3 6 9 loss ℓ −3 −2 −1 0 1 2 3 residual r = ŷ − y (prediction minus truth) squared (ŷ − y)² absolute |ŷ − y| zero–one 𝟙{ŷ ≠ y}
What to notice: (1) all three are $0$ only at $r=0$ and non-negative everywhere. (2) The squared curve is flat near $r=0$ — it barely cares about tiny errors — and then explodes; the absolute curve has a constant slope and a kink at the origin. (3) Zero-one is flat everywhere except one point: its derivative is $0$ almost everywhere and undefined at $0$, so gradient-based optimisation is completely blind to it. That single fact is why logistic regression has to replace zero-one loss with a smooth surrogate. (4) The three curves cross at $|r| = 1$: below it squaring is the gentlest of the three, above it the harshest.
Figure 3 — interactive: three losses on the same four predictions
Each row has its own vertical scale (max 9, 3 and 1 respectively), so compare shapes across rows, not heights. Things to try: (a) push one slider to its extreme and watch the squared bar dominate the whole row while the zero-one bar does not move at all — zero-one cannot tell "slightly wrong" from "catastrophically wrong"; (b) set one prediction exactly on its label and watch only that zero-one bar drop to 0; (c) make two points off by $0.5$ versus one point off by $1$ — identical absolute risk, but the squared risk prefers the two small errors ($0.125$ vs $0.25$). The number on the right of each row is the empirical risk $\hat R(h)$ under that loss.

Generalization, test error, and the i.i.d. assumption

You have a loss, so you can score $h$ on any labelled point. But which points? Not the training points — you already know their labels, so predicting them earns nothing. The notes are explicit: you care about performance on a new, previously unseen datapoint $x^{(\text{new})}$ ("test data"), and applying $h$ to it is inference. Given its true label $y^{(\text{new})}$, unknown to you, you want

$$ \ell\big(h(x^{(\text{new})}),\, y^{(\text{new})}\big) $$

to be small. This quantity is called the generalization error or test error. Generalization = performance on unseen data.

Analogy

A student who memorises the answer key to last year's exam has zero training error and has learned nothing. A student who understands the material does slightly worse on last year's paper and far better on this year's. Training error measures recall of the answer key; generalization error measures understanding.

The entire tension of machine learning — the bias/variance story, overfitting, regularisation — is this one gap between the two.

The difficulty: if $x^{(\text{new})}$ could be anything, generalization would be hopeless — nothing in a dataset of cats and dogs tells you what to do with a recording of a cello. We need an assumption tying the future to the past:

Definition

The i.i.d. assumption. All datapoints — training and test — are drawn independently from the same (identical), unknown distribution over $\X \times \Y$. Write that distribution $P$; we assume $(x^{(i)}, y^{(i)}) \sim P$ for every $i$, and $(x^{(\text{new})}, y^{(\text{new})}) \sim P$ too, drawn independently of all the rest.

The acronym spelled out, one letter at a time:

Key idea

We never assume we know $P$, only that it exists and does not change — the minimum needed to make the past informative about the future, and the load-bearing assumption under every generalization claim in this course. When a deployed system fails embarrassingly, check first whether i.i.d. quietly stopped holding.

When i.i.d. fails: distribution shift

Hospitals that deployed sepsis-prediction models trained on pre-COVID records found them degrading sharply and silently once COVID changed demographics, admission criteria and vital-sign patterns: the models were trained on $P_{\text{before}}$ and applied to $P_{\text{after}}$, and nothing in a model can notice that the world moved. This is distribution shift, a failure of the identically distributed half. What breaks precisely: your held-out number estimates $\E_{P_{\text{before}}}[\ell]$ while you now care about $\E_{P_{\text{after}}}[\ell]$ — an accurate answer to a question you stopped asking.

The independence half fails just as often and more sneakily: consecutive video frames, consecutive days of stock prices, several X-rays of one patient. The samples come from the right distribution but are correlated, so your effective sample size is far below $N$ — 10,000 frames from one 6-minute clip carry a few dozen samples' worth of information — and your risk estimate is dramatically overconfident.

Guided problem 3Does this setup violate i.i.d.?

For each setup, say which half of i.i.d. is violated (independent, identically distributed, both, or neither), what concretely goes wrong, and one thing you could do about it.

  1. Pneumonia detector. Trained on chest X-rays from Hospital A (one scanner model, mostly patients over 60). Deployed at Hospital B (different scanner, paediatric ward).
  2. Stock predictor. Training set is daily returns for 2015–2019 in chronological order; test set is daily returns for 2020.
  3. Face recogniser. $N = 50{,}000$ photos, but they come from 500 people, 100 photos each. The train/test split is made by shuffling all 50,000 photos randomly.
  4. Spam filter. Trained on last year's spam, deployed, and spammers immediately start rewording messages to get past it.
  5. Handwritten digits. 70,000 digits collected from a fixed pool of writers, split randomly into train and test, and both used only for this one experiment.
Step 1 — The question to ask each time

Two questions, in this order:

(a) Identically distributed? Is the thing generating the test points the same process as the thing that generated the training points? Different site, different time, different equipment, different population — any of these breaks it.

(b) Independent? If I tell you sample $i$, do you learn anything about sample $j$? Shared source (same patient, same writer, same person, adjacent in time) breaks it.

Step 2 — Work through 1 and 2

(1) Hospital A → B. Identically distributed fails, badly and on both coordinates: $P(x)$ changes (different scanner physics, different anatomy) and $P(y \mid x)$ may change too (different disease prevalence in children). Classic covariate shift plus label shift. Your held-out error at Hospital A is not an estimate of your error at Hospital B. Remedy: collect a labelled sample at B and re-measure; fine-tune or recalibrate on B's data; standardise the image preprocessing across scanners.

(2) Stock returns. Both fail. Independence fails because financial returns are serially correlated and volatility clusters (a turbulent Tuesday predicts a turbulent Wednesday). Identical distribution fails because 2020 markets were not 2015 markets. The chronological split is at least honest — it mimics deployment. Remedy: use rolling-origin (walk-forward) evaluation, never a random shuffle of time series, and expect the risk estimate to be optimistic anyway.

Step 3 — Work through 3, 4 and 5

(3) Faces. Independence fails. The 100 photos of person #37 are highly dependent. Because the split was made photo-wise, nearly every test photo has 99 near-siblings in the training set, so the model can succeed by memorising individuals rather than learning to recognise faces. Your reported accuracy will be wildly optimistic and will collapse on a person the model has never seen. Remedy: split by person (group split), so no identity appears on both sides. This is the most common evaluation bug in real projects.

(4) Spam. Identically distributed fails, and in the nastiest way: the distribution changes because you deployed. This is adversarial/feedback shift — $P$ is a function of your own model. Remedy: continuous retraining on fresh labelled mail, monitoring of the score distribution, and features that are expensive for an adversary to change (sending infrastructure) rather than cheap (word choice).

(5) Digits. Neither is badly violated — this is the intended use case. A caveat: writers are shared across the split, so strictly the samples are not independent, and a random split slightly overstates performance on a new writer. And if you reuse the test set for a hundred design decisions, you have effectively trained on it, and your estimate degrades. But as a single experiment with a fixed pool, i.i.d. is a reasonable idealisation.

Answer & the takeaway

1: identical fails. 2: both fail. 3: independent fails. 4: identical fails (adversarially). 5: essentially fine.

Takeaway: i.i.d. is not a technicality buried in the theory — it is the bridge between the number you measured and the number you care about. When it breaks, every guarantee on this page becomes decoration. Before you trust any reported accuracy, ask: where did the test points come from, and is that the same process that will generate tomorrow's inputs?

Risk: the thing we actually want to minimise

Given i.i.d., we can stop talking about one hypothetical new point and talk about the average over all possible new points. That average is the risk.

Definition

The risk of a hypothesis $h$ is its expected loss: $$ R(h) \;=\; \E_{(x,y)\sim P}\big[\,\ell\big(h(x),\, y\big)\,\big]. $$ Equivalently, in the pre-reading's random-variable notation with input r.v. $X$ and output r.v. $Y$: $R(h) = \E_{X,Y}\big[\ell\big(Y, h(X)\big)\big]$. Risk = expected loss.

Read the expectation carefully:

Intuition

$R(h)$ is the score $h$ would get on an infinitely long exam whose questions are drawn from the real world in the proportions the real world produces them. It is the number you want, and a number nobody has ever computed for a real problem.

Empirical risk: the thing we can actually compute

We cannot average over $P$, but we have $N$ samples drawn from it — so we average over those.

Definition

For a dataset $\D = \{(x^{(i)}, y^{(i)})\}_{i=1}^N$, the empirical risk of $h$ is $$ \hat R(h) \;=\; \frac{1}{N} \sum_{i=1}^{N} \ell\big(y^{(i)},\, h(x^{(i)})\big). $$ In words: run $h$ on every training input, score each prediction against its label, take the average. The hat on $\hat R$ means "estimated from data".

(That is the pre-reading's truth-first ordering; the lecture notes write $\frac1N\sum_i \ell\big(h(x^{(i)}), y^{(i)}\big)$ — identical for symmetric losses, but see the argument-order warning above.)

Key idea

Empirical risk is a Monte-Carlo estimate of the risk.

That sentence is the bridge between the computable and the desirable. A Monte-Carlo estimate approximates $\E_P[f]$ by drawing samples from $P$ and averaging $f$; here $f$ is the loss. Because the $(x^{(i)},y^{(i)})$ are i.i.d. from $P$, each term $\ell(y^{(i)}, h(x^{(i)}))$ is an unbiased draw of the quantity whose mean is $R(h)$: $$ \E\big[\hat R(h)\big] \;=\; \frac{1}{N}\sum_{i=1}^N \E\big[\ell(y^{(i)}, h(x^{(i)}))\big] \;=\; \frac{1}{N} \cdot N \cdot R(h) \;=\; R(h). $$ Each step: linearity of expectation; then each term has the same expectation $R(h)$ because the samples are identically distributed. So for a fixed, pre-chosen $h$, empirical risk is an unbiased estimator of true risk, and by the law of large numbers $\hat R(h) \to R(h)$ as $N \to \infty$ — with the usual $1/\sqrt{N}$ error, since (by independence) $\operatorname{Var}[\hat R(h)] = \operatorname{Var}[\ell]/N$.

Notice exactly where i.i.d. was used: identically distributed gave every term the same mean, independently gave the variance its $1/N$.

Figure 4 — empirical risk converging to true risk as $N$ grows
Four independent datasets, drawn from the same distribution; true risk $R(h)=1$.
What to notice: each coloured trace is the running empirical risk $\hat R(h)$ of one fixed model as its dataset grows from $N=1$ to $N=300$. At small $N$ the traces are wild and can be off by a factor of two in either direction — a model evaluated on 5 points tells you almost nothing. As $N$ grows they are squeezed into the shaded $\pm 2\sqrt{\operatorname{Var}[\ell]/N}$ band and converge on the dashed line $R(h)=1$. The band narrows like $1/\sqrt{N}$: to halve your uncertainty you need four times the data. Crucially the traces converge but never quite land — $\hat R$ is always an estimate.
Common mistake

"Empirical risk is unbiased, so training error estimates generalization error." No. That unbiasedness proof has a hidden condition: $h$ must be fixed before you look at $\D$. The moment you choose $h$ by minimising $\hat R$ over a family of candidates, the argument collapses.

Why, precisely: $\hat R(h)$ fluctuates around $R(h)$ with some noise. If you scan many candidate $h$'s and keep the one with the smallest $\hat R$, you preferentially select hypotheses whose noise happened to be negative — ones that got lucky on these particular $N$ points. The minimum of many noisy estimates is systematically below the minimum of their true values: $\E[\min_h \hat R(h)] \leq \min_h R(h)$. So the training error of the selected model is a biased — optimistically low — estimate of its generalization error. The bias grows with how many hypotheses you searched over and shrinks with $N$.

A pocket demonstration: take $h$ = a lookup table that memorises $\D$ and outputs anything for other inputs. $\hat R(h) = 0$ exactly. $R(h)$ is terrible. The gap between the two is overfitting, and it is the entire reason held-out test sets exist. Never report training error as performance.

You fit 200 different models, pick the one with the lowest error on your 1,000-point dataset, and report that error as your model's expected performance. What is the flaw?
Why: unbiasedness holds for a hypothesis chosen independently of the data. Choosing by minimisation is the opposite of independent: you are explicitly selecting on the noise. Option B is the common half-right answer — it correctly notes the variance but misses that the selection step converts symmetric noise into a one-sided bias. The fix is to score the selected model on data that played no part in selecting it.

Empirical risk minimization

Everything needed to answer Q1. We want to minimise $R(h)$ and cannot evaluate it; we can evaluate $\hat R(h)$; so, in the notes' words, minimize the average loss on the training data.

Definition

Empirical Risk Minimization (ERM). Choose $$ h^* \;=\; \argmin_{h \in \H} \;\hat R(h) \;=\; \argmin_{h \in \H}\; \frac{1}{N}\sum_{i=1}^{N} \ell\big(y^{(i)}, h(x^{(i)})\big), $$ where $\H$ is the hypothesis class: the set of hypothesis functions we are willing to consider.

Three pieces of this deserve individual attention.

What $\argmin$ means

$\min_h \hat R(h)$ is the smallest achievable value — a number. $\argmin_h \hat R(h)$ is the argument achieving it — a function, which is what ERM returns. With ties the $\argmin$ is a set and you pick one by a stated tie-breaking rule (common in decision trees).

What $\H$ is, and why you must restrict it

$\H$ is the menu you may order from:

That last one shows why the restriction is not a technicality. If $\H$ contains every function, ERM has an exact, useless solution: the lookup table returning $y^{(i)}$ on each training $x^{(i)}$ and garbage elsewhere achieves $\hat R = 0$. $\H$ is what forces the model to compress, and compression is what produces generalization. Too rich gives overfitting, too poor and no member of $\H$ is any good (underfitting) — the trade-off that is the spine of Part II.

From $\argmin_{h \in \H}$ to $\argmin_{\theta}$

Searching over a set of functions sounds impossible — a CPU does not loop over functions. The trick, as the pre-reading puts it: fix the structure of the hypothesis function, then search over parameter values. Fix $h(x; w, b) = wx + b$ and a member of $\H$ is determined by two numbers; collect them into $\theta = (w,b)$ and the search becomes

$$ \theta^* \;=\; \argmin_{\theta}\; \frac{1}{N}\sum_{i=1}^{N} \ell\big(y^{(i)},\, h(x^{(i)}; \theta)\big). $$

This is the most important change of viewpoint in the course: a search over an abstract space of functions becomes a search over $\R^2$, a surface you can picture, differentiate and walk downhill on. Parameterisation turns learning into optimisation. Read $\argmin_\theta$ as "$\argmin_{h\in\H}$ where $\H$ is pinned to one shape and only the dials are free."

Example

Take the two-point dataset $(x,y) = (1,2)$ and $(2,3)$, structure $h(x;w,b) = wx+b$, squared loss. Then $$\hat R(w,b) = \tfrac12\big[(w + b - 2)^2 + (2w + b - 3)^2\big].$$ Try $\theta = (1,1)$: predictions $2$ and $3$; losses $0$ and $0$; $\hat R = 0$. Try $\theta = (0, 2.5)$: predictions $2.5$ and $2.5$; losses $0.25$ and $0.25$; $\hat R = 0.25$. So $(1,1)$ beats $(0,2.5)$ — and this concrete "plug in $\theta$, get a number" loop is exactly what gradient descent automates.

Key idea

The notes leave two questions open, and they are the syllabus for the next four chapters. (1) From what class $\H$ should we draw $h$? → decision trees (Ch. 6), linear models (Ch. 8), feature engineering (Ch. 10), logistic regression (Ch. 11). (2) How do we compute the minimising $h$ efficiently? → the normal equation where a closed form exists, gradient descent and SGD (Ch. 9) where it does not.

Why does empirical risk minimization over the class of all functions $\X \to \Y$ fail, even though it drives $\hat R(h)$ to exactly $0$?
Why: the minimisation is perfectly solvable — that is the problem. ERM only ever constrains $h$ at the $N$ training points; a class rich enough to fit those points independently of each other leaves $h$ free everywhere else, and "everywhere else" is where you will actually use it. $\H$ must be restrictive enough that fitting the training points forces sensible behaviour in between. (B is false — infinite classes like all lines are fine. C is a real difficulty for a different reason, and applies equally to restricted classes.)

Holy cow, so much notation

A direct quote from the pre-reading, and the correct reaction. Every symbol on this page, in one table — come back to it.

SymbolRead aloud asMeaningExample
$\X$"script X", the input spaceThe set every input belongs to$\X = \R^3$ (size, beds, age); $\X=\{0,1\}^5$ for 5 yes/no attributes
$\Y$"script Y", the output/label spaceThe set every label belongs to$\Y = \R$ (price); $\Y = \{0,1\}$ (healthy/ill)
$\H$"script H", the hypothesis classThe set of functions we search over$\H = \{h(x)=wx+b : w,b \in \R\}$
$x^{(i)}$"x super i" — the $i$-th inputInput of sample $i$. Index, not power.$x^{(3)} = (900,\,2,\,40)$
$x^{(i)}_j$"x super i sub j"Feature $j$ of sample $i$$x^{(3)}_2 = 2$ bedrooms
$y^{(i)}$"y super i"True label of sample $i$$y^{(3)} = 150$
$\hat y$"y hat"A predicted label, $\hat y = h(x)$. The hat always means "estimated/predicted".$\hat y = 162$ when the truth was $150$
$N$"N"Sample size: how many training datapoints$N = 5$ houses
$d$"d"Number of features/attributes per input ($\X = \R^d$)$d = 3$; for images $d = 3{,}000{,}000$
$h$"h"The hypothesis / prediction function / model, $h : \X \to \Y$$h(x) = 0.17x_1 + 20$
$\theta$"theta"The parameters of $h$ once its structure is fixed$\theta = (w,b) = (0.17,\,20)$
$\ell$"ell", the loss function$\ell : \Y\times\Y \to \R$, cost of one prediction. Check the argument order.$\ell(\hat y,y) = (\hat y - y)^2 = 144$
$R(h)$"risk of h"$\E_{(x,y)\sim P}[\ell(h(x),y)]$ — expected loss. What we want. Uncomputable.$R(h) = 1.0$ in Figure 4
$\hat R(h)$"R hat of h", empirical risk$\frac1N\sum_i \ell(y^{(i)}, h(x^{(i)}))$ — average loss on $\D$. What we compute.$\hat R = 0.4$ error rate
$\D$"script D", the dataset$\{(x^{(i)},y^{(i)})\}_{i=1}^N$, the training datathe 5-row house table
$\1\{\cdot\}$"indicator of"$1$ if the statement inside is true, $0$ if false$\1\{3 \neq 5\} = 1$
$\argmin$"arg min"The argument that minimises, not the minimum value$\argmin_{c}\sum_i (c-y^{(i)})^2 = \bar y$
$P$"P"The unknown joint distribution on $\X\times\Y$ that all data is drawn fromnever known explicitly
Intuition

A trick for reading any ML paper: the hat means estimated from data ($\hat y$, $\hat R$, $\hat\theta$), the star means optimal ($h^*$, $\theta^*$), the bar means average ($\bar y$), a superscript in parentheses means which sample, and a subscript means which coordinate. Those five conventions cover about 90% of the notation you will ever see.

Unsupervised learning

Everything so far was supervised: every input came with a label, and the supervision is the labels. Labels are expensive — a radiologist's hour per medical image — while unlabelled data is nearly free. So what can you do with only $x^{(1)},\dots,x^{(N)} \in \X$ and no $y$?

Example

A $100\times100$ greyscale face photo is a point in $\R^{10{,}000}$, but faces do not fill that space — nearly every point in it is static noise. The faces lie on a thin sheet of maybe 10–50 effective dimensions (pose, lighting, identity, expression), and the 10 numbers naming a position on that sheet are far more useful than the original 10,000.

Self-supervised learning: the payoff

Key idea

Self-supervised learning: convert an unsupervised problem into a supervised one — by manufacturing the labels out of the data itself.

Take text from the internet: trillions of words, no labels, nobody annotated any of it. Now hide a word and let it be the label. From "the cat sat on the mat": $x = $ "the cat sat on the", $y = $ "mat". The label was already in the data — you just looked away from it and then checked yourself — so no annotator was involved and it scales to the whole internet.

After that it is ordinary supervised learning, and everything on this page applies verbatim. $\X$ = all finite token sequences. $\Y$ = the vocabulary, a finite unordered set of maybe 50,000 tokens, so this is 50,000-way classification with a classification loss (in practice a smooth surrogate for zero-one; see logistic regression). $\H$ = very large neural networks parameterised by $\theta$, and training is $\argmin_\theta \hat R(\theta)$ by stochastic gradient descent. What you get is a next-word predictor; feed each prediction back in as input and it writes. In the notes' words, this forms the basis of LLMs.

Intuition

Why should "guess the next word" produce anything like intelligence? Because doing it well requires solving the hidden sub-problems: "the capital of Australia is ___" needs a fact, "she lifted the heavy box and her back began to ___" needs physics, the last word of a murder mystery needs the plot. The label is trivially cheap to generate and arbitrarily hard to predict — the best possible property for a learning objective. But a next-word predictor optimises $\hat R$ on text people wrote: it fits the distribution of human text, not truth, and every caveat on this page — the bias of training error, distribution shift, the $\hat R$ vs $R$ gap — applies in full force.

The same trick works outside text: hide a patch of an image, predict the next video frame, predict one language's sentence from the other's. Whenever you can remove part of a datapoint and ask the model to restore it, free unlabelled data becomes a supervised problem with the full machinery of this chapter available.

In next-word-prediction self-supervised training, what are $\X$ and $\Y$, and what type of task is it?
Why: the whole point of "self-supervised" is that there is a $\Y$ — the hidden word — it just was not supplied by a human. $\Y$ is the token vocabulary: finite, and unordered (token 8,431 is not "between" tokens 8,430 and 8,432), which makes it classification by the definition in this chapter. C is the tempting answer: the raw data was unlabelled, but the construction manufactures labels, and after that it is completely ordinary supervised ERM. A confuses the model's output format (a probability vector) with the label space.

Recap and what comes next

The whole chapter in eight lines:

  1. Rules work when experts can state them. When they cannot — pixels, speech, language — learn from examples instead.
  2. Formalise: inputs $\X$, labels $\Y$, find $h : \X \to \Y$ from data $\D = \{(x^{(i)},y^{(i)})\}_{i=1}^N$.
  3. Training produces $h$; inference applies it. Keep them apart.
  4. $\Y$ finite and unordered ⇒ classification; $\Y$ continuous and ordered ⇒ regression.
  5. A loss $\ell : \Y\times\Y\to\R$ scores one prediction. Zero-one for classification, squared error for regression, asymmetric tables when the mistakes differ in cost. Check the argument order.
  6. Averaging the loss over the unknown data distribution gives the risk $R(h)$ — what you want, and cannot compute.
  7. Averaging it over your sample gives the empirical risk $\hat R(h)$ — a Monte-Carlo estimate of $R(h)$, unbiased for a fixed $h$, optimistically biased for an $h$ you selected using it.
  8. ERM: $h^* = \argmin_{h\in\H} \hat R(h)$, which becomes $\argmin_\theta$ once the structure of $h$ is fixed. Choosing $\H$ and computing the $\argmin$ are the next four chapters.

Next: decision trees — the first concrete $\H$, chosen because you can read the resulting model out loud. Then entropy and mutual information for choosing splits well, and then linear regression, where for the first time the $\argmin$ has an exact closed-form solution.