A spam filter, a house-price estimator, a tool that reads handwritten digits and the next-word step of a chatbot look like different things. Underneath they follow one template: collect examples where the right answer is known, build a model that has adjustable numbers, score its mistakes with a loss, and search for numbers that make the loss small. Then comes the part that matters: the model must work on examples it has never seen.
This lesson sets that template out with names and small numbers, so that every later lesson in Part 3 (and the neural networks after it) has a place to hang its ideas. You met the pieces in P0.2 (the learning loop) and P0.3 (kinds of learning). Here they are made exact.
One example: an input and an answer
Take one house. We describe it by a few measured numbers, such as the area, the number of bedrooms and the age. Those numbers are the features, and the list of them is the feature vector (a vector with entries, P1.B1). The thing we want to predict, the price, is the label . Some books say target or response, and an input with its label is an example (or sample, or instance).
Here are five houses. The prices (in thousands) are invented.
| area () | bedrooms | age (years) | price (k) |
|---|---|---|---|
| 120 | 3 | 15 | 310 |
| 85 | 2 | 40 | 190 |
| 150 | 4 | 5 | 400 |
| 60 | 1 | 30 | 120 |
| 95 | 3 | 10 | 240 |
The first example is with label . Here . A subscript names the example, and in the feature vector is feature of example .
Features must be numbers, because a model does arithmetic on them. Text, colours and categories are first turned into numbers (P3.A11 covers how; P2.5 did it for the Titanic passengers).
Two kinds of label
The kind of label sorts the problem, as P0.3 said:
- Regression: the label is a real number, and being close counts. A price, a temperature, a delivery time.
- Classification: the label is one of a fixed set of categories, and a wrong category is simply wrong. For two categories (binary) the labels are often written 0 and 1. For categories (multi-class) they are written . These numbers are only names: class 2 is not “twice” class 1, so a model must not do arithmetic on them as if it were a quantity.
A label can also be a vector (predict price and rent together), or a long sequence such as a sentence. A language model predicts one token at a time, so each step is a classification over the vocabulary (P10.B2).
The data set: a table, written two ways
A data set of labelled examples is
In code it is stored as two arrays. Stack the feature vectors as rows of a feature matrix and the labels in a vector (the row-per-example convention of P1.B5):
Here has shape , which is , and has shape . The same shapes appear in P2.5. There, the Titanic table of 1309 passengers ended as an of shape and a of shape with for a survivor (500 of the 1309) and otherwise. That is a classification problem with and .
The assumption behind the table: i.i.d.
We assume the rows and the future are the same kind of thing: every pair is drawn independently from one fixed but unknown distribution . This is independent and identically distributed, or i.i.d. (P1.D5). Two details matter.
- The distribution is over pairs. Two identical houses can sell for different prices, so is drawn from , and part of its variation is noise that no model can predict from these features.
- The assumption is a modelling choice, often only approximately true. It fails when examples depend on each other (many rows from one patient, days in a time series), with duplicates, and when the world changes after training. Then a test score can look better than the real performance (P3.A4, P12.5).
The model and the hypothesis class
A model is a function that turns features into a prediction . The vector holds its parameters, the adjustable numbers. For a line on one feature, and . For the house data a linear model is , so has numbers.
The hypothesis class is the set of all functions you can get by changing the parameters: . For “a line” it is every line. Choosing the class is the first big decision, and it limits what can be learned: if the true relation is a curve, the best line is still a line. Training can only pick the best member of , not something outside it.
Parameters are learned from data. Hyperparameters are the settings you choose before training, such as the learning rate (P0.2), the degree of a polynomial or the number of layers; they are not learned by gradient descent on the training loss, and they are chosen with validation data (P3.A4). For a classifier, usually outputs a score or a probability, and a rule turns it into a label (P3.A7).
The loss for one example
To train, we need a number that says how bad one prediction is. The loss is zero for a perfect prediction and larger for worse ones. Common choices:
- Squared error for regression, . It never cancels between over- and under-predictions and punishes big misses more. Absolute error punishes them less.
- 0-1 loss for classification: if the predicted class is right and if it is wrong. Its average is the error rate.
- Cross-entropy, which scores the probability the model gave to the correct class (P3.A7).
The 0-1 loss is what we would like to be small, but it is a poor thing to train with. If the model outputs a smooth score, a tiny change in the parameters either changes no prediction at all (so the loss does not move and the slope is zero) or flips one prediction (a sudden jump). Gradient descent (P1.F3) cannot follow that. Smooth losses such as cross-entropy are used for training, and the error rate is used for reporting (P3.A9). So a loss is a tool for the search, and a metric is the number you finally care about; they can differ.
The average loss, or the empirical risk
The loss scores one example. To score a model on the whole data set, average it:
This is called the empirical risk or the training loss (“empirical” means “measured on the data we have”). Here is a worked example from P0.2: the data and the line with , .
| error | squared | |||
|---|---|---|---|---|
| 1 | 2 | 1 | 1 | |
| 2 | 3 | 2 | 1 | |
| 3 | 7 | 3 | 16 |
The empirical risk is . The best line for these points is , , with empirical risk (P3.A2 shows how to find it). The loss on a single example is a number for that example; the empirical risk is one number for the model.
The true risk, and why it cannot be computed
What we want is the average loss on future examples from the same distribution, an expectation (P1.D4):
the true risk or expected risk. We do not know , so we cannot compute it. We can estimate it by averaging the loss over a sample, which is what Monte Carlo does (P1.D9).
There is one catch, and it is the heart of this lesson. A Monte Carlo average is an unbiased estimate only when the sample is independent of the thing measured. The training examples were used to choose , so the model was tuned to them, and the empirical risk is usually smaller than the true risk, sometimes much smaller. A fair estimate needs examples the model has not seen: a test set (P3.A4).
Training, and inference
Training (or fitting) means choosing the parameters that minimize the empirical risk:
This is an optimization problem in the sense of P1.F1: the parameters are the unknowns, the empirical risk is the objective, and is the argmin. The method is called empirical risk minimization (ERM). For a line with squared error there is a formula for ; for most models we search step by step with gradient descent (P1.F3, P0.2). A regularized version adds a penalty on the parameters and is the subject of P3.A6.
Inference (or prediction) is what happens after training. The parameters stay fixed, a new input arrives with no label, and the model returns . With the line above, gives . Training is usually the slow, occasional step; inference is the step that runs every time the model is used.
Generalization: the training loss is not the goal
A model generalizes if it does well on new examples, not only on the ones it was trained on. The difference
(true risk minus training loss) tells how much the training loss flatters the model. Training only sees the training loss, never .
A model that memorizes shows why. Consider a “lookup” model that predicts, for a new input, the label of the nearest training example. On the training set it is perfect: every training input is its own nearest neighbour, so its training loss is exactly . On new data it copies the noise in the neighbour’s label. In a simulation where plus noise of variance , with training points, averaged over 200 repeats (code below):
- the line has training loss and true risk ;
- the lookup model has training loss and true risk .
The model that is best on the training set is worse in the world. Noise variance is the best any model could do, so a true risk close to is as good as it gets. Two failures are named from this: underfitting (the hypothesis class is too simple, so even the training loss is high) and overfitting (the model fits quirks of the sample, so training loss is low and true risk high). P3.A3 shows them on one data set, P3.A5 explains the trade-off, P3.A4 gives the way to measure it, and P3.A6 gives one way to control it.
Go deeper A number for the optimism of the training loss
For a line (2 parameters) fitted by least squares to points with independent noise of variance , when the true relation really is a line, the average training loss is , while the average loss on new labels at the same inputs is . With and these are and . A simulation of 20000 repeats gives and . In general, with parameters the factors are : the more parameters per example, the bigger the optimism. These are exact only for this fixed-input, correctly specified linear case; the lesson from them (more freedom, more flattery) carries over in general.
Go deeper Why a gap can be bounded: a simple guarantee
Suppose the loss is between 0 and 1, the class is a finite list of functions chosen before seeing the data, and the examples are i.i.d. Then, with probability at least , every in the list has (Hoeffding’s inequality plus a union bound). For , and the right side is . The bound grows with the logarithm of the number of candidates and shrinks like : more candidates, or fewer examples, allow a larger gap. Real model classes are infinite and the bound is usually loose, so treat it as an explanation of the direction, not a prediction of the size.
No free lunch: why a model needs assumptions
Can we build one learner that is best for every problem? The no-free-lunch result says no, in a precise sense. Take a small example: inputs are the 8 patterns of three bits, you have seen the labels of 4 of them, and you must predict the other 4. Suppose each of the ways to label the unseen inputs is equally likely. Whatever rule you choose for the unseen inputs, “always 0”, “always 1”, or anything clever, its average accuracy over those 16 labellings is exactly . The data you saw say nothing about the rest unless you assume that unseen inputs are related to seen ones.
Wolpert (1996) proved a general version for classification-style (0-1) error: averaged uniformly over all possible target functions, with error measured on inputs outside the training set, every learning algorithm has the same expected error. The careful reading is:
- It does not say all algorithms are equally good on real problems. Real labels are not uniformly random: nearby inputs tend to have similar labels, patterns repeat, effects are usually simple. An algorithm that bets on such structure does better on real problems.
- It does say that every learner carries a bet. The hypothesis class, a preference for smooth or simple functions, a distance measure, all are assumptions about the world, called the inductive bias. A bet that fits the problem helps; one that does not hurts. That is why there are many algorithms in Part 3, and why you compare them on your data (P3.A4) instead of trusting a favourite.
The pipeline around the model
A model is one step of a longer process. The usual order has seven stages, and the loop back is part of the work, because the evaluation or the world may send you back.
Notice the order: the split comes before the features. A step such as “fill a missing age with the median” learns a number from data; if it is computed using the test rows, information from the test set has leaked into training (P3.A11). So the held-out data are put aside first, and every fitted step is learned on training rows only (P2.5 showed this for the median age).
Intuition
Think of a student with a pile of past exam papers and their answers. The student can learn the method or memorize the answers. Their score on the past papers is the training loss. The real exam is a fresh draw from the same examiner: that is the true risk. A student who memorized scores perfectly on the pile and badly on the exam, and the only honest way to tell is a practice paper the student has not seen (the test set). The analogy breaks in one place: a model has no “understanding” to fall back on. What it learns is whatever fits the examples within its hypothesis class.
Math
Data , , , for regression (class labels for classification).
Model with ; loss .
Empirical risk ; true risk .
Training ; gap .
For a fixed chosen without looking at the sample, . For chosen on the sample this equality fails, and is typically below .
Code
The same recipe in scikit-learn. This block is not runnable here, because scikit-learn is not available in the browser; the output shown is from a real run on the machine used for this lesson (scikit-learn 1.8). The Try it cells below use only NumPy.
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_squared_error
rng = np.random.default_rng(0)
X = rng.uniform(0, 5, size=(100, 1)) # N=100, d=1
y = 2 * X[:, 0] + 1 + rng.normal(0, 1, 100) # noisy labels
X_tr, X_te, y_tr, y_te = train_test_split(
X, y, test_size=0.2, random_state=0) # split
model = LinearRegression().fit(X_tr, y_tr) # train
print(X_tr.shape, X_te.shape)
print("w =", model.coef_.round(3),
" b =", round(float(model.intercept_), 3))
print("training loss:",
round(mean_squared_error(y_tr, model.predict(X_tr)), 3))
print("test loss :",
round(mean_squared_error(y_te, model.predict(X_te)), 3))
print("prediction at x = 4:", model.predict([[4.0]]).round(3))(80, 1) (20, 1)
w = [1.967] b = 1.071
training loss: 1.021
test loss : 0.636
prediction at x = 4: [8.937]Here the test loss happens to be lower than the training loss. That is possible: 20 test points are a small sample with its own noise. One test number is an estimate with error (P3.A4).
Try it
Cell 1: the worked example in code. The model, the empirical risk and the best line for the three points. It prints for , then the best line , with loss , a constant-only model with loss , and the prediction at . A richer hypothesis class gives a lower training loss.
Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).
Cell 2: training loss against true risk. Here we know the world, so we can draw a huge fresh sample (20000 points) to stand in for the true risk (Monte Carlo, P1.D9). Change n to 40 or the noise to 2, and watch the gap.
Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).
It prints about and for the line, and and for the lookup model.
Cell 3: no free lunch, by counting. All 16 ways to label the four unseen inputs, against four different rules.
Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).
All four print . The 50% holds only because every labelling was allowed. A learner that does better than that on a real problem is relying on an assumption about how seen and unseen inputs are related.
Check your understanding
A data set has emails, each described by numeric features, with a label of 1 for spam and 0 otherwise. What are the shapes of and ?
The convention is one row per example and one column per feature, so is , and there is one label per example, so has length . The reversed shapes put features in rows. Appending the label to would let the model read the answer as an input. A label vector of length 50 would give one label per feature, not per email.
After training, the loss on the training set is and the loss on a held-out test set is . What is the best reading?
The test examples were not used to choose the parameters, so their average loss is a fair estimate of the true risk, and it is far above the training loss. The training loss is not the true risk, since the model was tuned to those examples. A zero loss on the training set says nothing about new data, and there is nothing left to improve on the training set when the loss is already zero.
Why is the error rate (the average 0-1 loss) a poor thing to minimize directly with gradient descent, for a model that outputs a smooth score?
The 0-1 loss is a step function of the score: it stays constant until one prediction flips, and then jumps. Gradient descent needs a slope that points toward better parameters, and a flat loss gives none. The error rate is computed easily on any data and is never negative. The two losses are on different scales and neither is guaranteed to be larger in general.
A hospital model is trained on 5 photographs from each of 100 patients. The 500 photographs are split into train and test sets at random, photo by photo. Which problem does this create?
Several photos of one patient are correlated, so the examples are not independent draws. A test photo then has near-twins in the training set, and the model can score well by recognizing the patient, not the condition. A split by patient avoids this. The number of photos is enough to split. A random split of independent examples gives a fair estimate, not a pessimistic one. The kind of label does not change.
Which statement about the no-free-lunch idea is correct?
The result is an average over every conceivable problem. Real problems have structure, which is why algorithms that bet on it do better, so the statement that all algorithms are equal on real data is a misreading. It does not say that learning is impossible, only that it depends on assumptions. Data help when the assumptions are suitable, and the result says nothing against that.
Exercises
- For the points and the model , find the mean squared error and the mean absolute error.
Show answer
The predictions are and the errors . Mean squared error is and mean absolute error is . One miss of size 2 counts four times in the squared error but only twice in the absolute error. - A classifier predicts for six emails whose labels are . What is the 0-1 loss for each email and the empirical risk?
Show answer
The losses are , and the average is : an error rate of one third. - How many numbers are in the Titanic feature matrix of , and how many parameters does a linear model with a bias have on it?
Show answer
numbers. A linear model has one weight per feature plus a bias: parameters, far fewer than 9163. - For the data , the hypothesis class “constant functions” has the best member . What is its empirical risk, and why is it above the of the best line?
Show answer
The errors are , and the average of the squares is . Constants are a subset of lines (a line with ), so the best line cannot be worse. Here it is much better because clearly rises with . - A bank has 10000 past loans with their features and whether each was repaid. It wants to predict repayment for new applicants. Name , , the kind of problem, and a suitable training loss.
Show answer
: the applicant’s features (income, amount, history, and so on); : repaid or not (0 or 1). It is binary classification, trained with cross-entropy (P3.A7). Reporting would use a metric that fits the costs (P3.A9). - A house-price model was trained on 2022 sales and is accurate on a 2022 test set, but is badly off in 2026. Which assumption failed, and which pipeline stage should have caught it?
Show answer
The data were no longer identically distributed (prices and buyers changed). Monitoring should have caught it, by tracking the error as true prices arrived, and the answer is to collect new data and retrain (P12.5). - Four inputs have labels you have not seen, and every one of the 16 label patterns is equally likely. A rule predicts . What is its expected accuracy?
Show answer
Each input is right with probability whatever the rule says, so the expected accuracy is , the same as for any other rule.
Next: P3.A2 fits a line in full (the closed form and gradient descent), P3.A3 shows underfitting and overfitting on a polynomial, P3.A4 sets up train, validation and test sets properly, P3.A9 covers the metrics for evaluation, and P3.A11 returns to features and leakage.