Skip to content
BIASED

What machine learning is

Objects, features and targets; a model as a function from a family; loss, risk and empirical risk; why training error lies; the best possible prediction; the kinds of tasks and the plan of the course.

A rule from examples

Imagine a model learning to distinguish photos of cats from photos of dogs. We show it examples with known answers. After training, it recognizes every one of those photos correctly.

Is that enough for a good model? It may have simply memorized familiar examples. What matters is whether it can identify an animal in a new photo that was not used for training.

Applying a learned rule to new examples is called generalization. To test it, we need separate data that was not used for training. This data should resemble the model's future tasks.

The first question checks this idea. Then we introduce objects, features and errors. The mathematical parts build on probability, linear algebra and basic Python; see the course map for a suggested order.

Objects, features, targets

The history is a table. Each row is an object: a flat, a loan application, an email. Each column is a feature, something known about the object at the moment the prediction is needed. One more column holds the target, the answer we want to predict. For house prices the features might be the area, the district, the floor and the year of construction, and the target is the price.

In symbols, object ii is a feature vector xi∈Rdx_i \in \mathbb R^d with target yiy_i, and the training sample is (xi,yi)i=1n(x_i, y_i)_{i=1}^n. Stacking the rows gives the object–feature matrix X∈Rn×dX \in \mathbb R^{n \times d} and the vector of targets y∈Rny \in \mathbb R^n.

The pairs are assumed to be independent draws from one unknown distribution PP over pairs (x,y)(x, y). It produced the table, and it will produce the objects the rule meets later. Nothing in this course works without this assumption, and much of what goes wrong in practice breaks it.

A model is a function ff that maps features to a prediction y^=f(x)\hat y = f(x). It is chosen from a family F\mathcal F: all linear functions, all trees of depth 3, all networks of one shape. Supervised learning takes the table and returns a trained model f^∈F\hat f \in \mathcal F that predicts the target of an object that was not in the table.

Loss, risk and empirical risk

To call a model good we need a number. A loss L(y,y^)≥0L(y, \hat y) \ge 0 is the cost of predicting y^\hat y when the truth is yy. A common one is the squared error L(y,y^)=(y−y^)2L(y, \hat y) = (y - \hat y)^2.

What we care about is the loss on the next object. That is the risk, the expected loss of the topic Expectation and variance:

R(f)=E L(y,f(x)),(x,y)∼P.R(f) = \mathbb E\, L\big(y, f(x)\big), \qquad (x, y) \sim P .

PP is unknown, so the risk cannot be computed. The table gives its sample version, the empirical risk:

R^(f)=1n∑i=1nL(yi,f(xi)).\hat R(f) = \frac1n \sum_{i=1}^n L\big(y_i, f(x_i)\big) .

Most training procedures, from least squares to gradient boosting, minimize it over the family: f^=arg⁡min⁡f∈FR^(f)\hat f = \arg\min_{f \in \mathcal F} \hat R(f). This is empirical risk minimization.

Why is that sensible? The topic The law of large numbers showed that for a model fixed in advance, R^(f)\hat R(f) is a sample mean of i.i.d. losses with mean R(f)R(f). It is unbiased and converges to R(f)R(f). If the loss on one object has standard deviation σL\sigma_L, the standard error of R^(f)\hat R(f) is σL/n\sigma_L / \sqrt n, and The central limit theorem turns it into an error bar.

The simplest model ignores the features and predicts one number cc. Four flats cost 3, 5, 4 and 8 million. Under squared loss the best constant is the mean, c=5c = 5, as in Expectation and variance. Its empirical risk is 14(4+0+1+9)=3.5\frac14(4 + 0 + 1 + 9) = 3.5.

Why training error lies

Is 3.5 the risk of predicting 5? No. The constant 5 was not fixed in advance: it was chosen because it fits these four prices. The law of large numbers argument needs a model that does not depend on the sample.

Let the prices have mean μ\mu and variance σ2\sigma^2, and let the fitted constant be the sample mean yˉ\bar y. Its training error is the average squared deviation from yˉ\bar y. The topic Estimators: bias and variance found its mean in the block Why n − 1:

E R^(yˉ)=n−1n σ2.\mathbb E\, \hat R(\bar y) = \frac{n-1}{n}\,\sigma^2 .

A new price yy is independent of the sample and has the same mean, and Var⁡(yˉ)=σ2/n\operatorname{Var}(\bar y) = \sigma^2 / n. The two variances add, so the risk, averaged over training samples, is

E R(yˉ)=E (y−yˉ)2=σ2+σ2n=n+1n σ2.\mathbb E\, R(\bar y) = \mathbb E\,(y - \bar y)^2 = \sigma^2 + \frac{\sigma^2}{n} = \frac{n+1}{n}\,\sigma^2 .

With n=4n = 4 the training error averages 0.75 σ20.75\,\sigma^2 and the risk 1.25 σ21.25\,\sigma^2. A simulation agrees:

import numpy as np
 
rng = np.random.default_rng(0)
n, sims = 4, 200_000
y = rng.normal(size=(sims, n))           # 200,000 training sets of 4 targets, sigma^2 = 1
c = y.mean(axis=1)                       # the fitted constant of each set
train = ((y - c[:, None]) ** 2).mean(axis=1)
y_new = rng.normal(size=sims)            # one fresh object per set
test = (y_new - c) ** 2
print(round(train.mean(), 3), round(test.mean(), 3))
0.751 1.252

A model with one parameter already looks better on its own data than it is, because the parameter was fitted to those data. A model with thousands of parameters fits far more of its sample, and its training error can be off by as much as the risk itself.

The best possible prediction

Which function would we choose if we knew PP? The topic Conditional expectation answered for squared loss. The regression function m(x)=E[y∣x]m(x) = \mathbb E[y \mid x] is the best predictor, and any other ff pays E (m(x)−f(x))2\mathbb E\,(m(x) - f(x))^2 on top of it. What mm itself leaves, EVar⁡(y∣x)\mathbb E \operatorname{Var}(y \mid x), is the irreducible error: the noise the features do not explain. The block Other losses, other targets showed that the loss picks the summary: the mean for squared error, the median for absolute error, the whole conditional distribution for cross-entropy.

In classification with the 0–1 loss, which charges 1 for every wrong class, the best rule predicts the most probable class. This is the Bayes classifier. Its risk is the Bayes error:

R∗=E[1−max⁡kP(y=k∣x)].R^* = \mathbb E\Big[1 - \max_k P(y = k \mid x)\Big] .

No classifier that sees the same features does better.

Write R∗R^* for the smallest possible risk under any chosen loss, and fF∗f^*_{\mathcal F} for the best member of the family. A trained model falls short of R∗R^* in two ways:

R(f^)−R∗=R(f^)−R(fF∗)⏟estimation error+R(fF∗)−R∗⏟approximation error.R(\hat f) - R^* = \underbrace{R(\hat f) - R(f^*_{\mathcal F})}_{\text{estimation error}} + \underbrace{R(f^*_{\mathcal F}) - R^*}_{\text{approximation error}} .

A family that is too simple cannot get close to mm. A family that is too rich for nn examples cannot be pinned down by them. Every method of this course picks a point on this trade-off, and the topic Bias–variance decomposition makes it exact for squared loss.

Kinds of tasks

The kind of target decides the kind of task.

Task Target Examples Typical loss or metric
Regression a number price, demand, delivery time squared or absolute error
Binary classification one of two classes default, churn, spam cross-entropy; precision, recall, ROC-AUC
Multiclass, multilabel one of KK classes, or a set of labels a handwritten digit, tags of an article softmax cross-entropy
Ranking an order of items for a query search results, recommendations pairwise and listwise losses, NDCG
Clustering none customer segments within-cluster distance

The first four are supervised: every training object comes with its target. Ranking stands apart because its loss depends on several objects at once. A list is good if the relevant documents come first, whatever their scores. Unsupervised tasks have no target at all. Besides clustering they include density estimation, anomaly detection and dimensionality reduction.

The course keeps returning to a few examples: house prices for regression, credit default and churn for binary classification, a spam filter, two interleaved half-moons for curved boundaries, handwritten digits for many classes and for networks, and a matrix of user ratings at the very end.

Fitting is easy, generalizing is hard

The richest family contains every function, and in it a perfect fit always exists. The memorizer returns yiy_i when asked about xix_i and some default value elsewhere. Its empirical risk is zero. With continuous features a new object almost never coincides with a training one, so the memorizer answers every new question with its default. It has learned nothing.

A rich family overfits in a milder way. Fit polynomials of growing degree by least squares to 12 equally spaced points of sin⁡2πx\sin 2\pi x on [0,1][0, 1] with noise variance σ2=0.09\sigma^2 = 0.09. This is the experiment of the block Bias and variance of a model in Estimators: bias and variance. The table gives exact expected values over the noise; new data means a fresh xx, uniform on [0,1][0, 1], with fresh noise.

Degree 0 3 5 9 10 11
Training error 0.541 0.067 0.045 0.015 0.008 0
Error on new data 0.598 0.121 0.128 0.208 0.421 3.16

The training error falls with every added coefficient and reaches zero at degree 11, where the curve passes through all 12 points. The error on new data falls only while the model is too simple for the sine. It is smallest at degree 3 and then climbs.

From degree 5 on, the polynomial can follow the sine almost exactly, and the training error is just the noise the fit failed to absorb. With pp = degree + 1 coefficients it equals σ2(n−p)/n\sigma^2 (n - p) / n: each coefficient absorbs one direction of the noise, σ2/n=0.0075\sigma^2 / n = 0.0075 per coefficient. That absorbed noise is what the model gets wrong on new data.

Key idea. Training error measures how well a model fits the signal and the noise of its own sample. Only data that played no part in choosing the model estimate its risk. Even that check has a price: picking the best of KK models on one validation set costs ln⁡K\ln K in the bound of the block The best of K models in Inequalities and concentration.

The course map and what comes next

Each topic of the course either fixes a limitation of the method before it or changes the task. The seven modules:

  • The learning problem. This topic, then Data, features and leakage and Validation and overfitting: what to feed a model and how to measure its risk honestly. Nearest neighbours is the first model: similar inputs get similar outputs, until in many dimensions nothing is similar.
  • Linear regression. A vote of neighbours has no global structure, so Least squares fits one linear rule. Where a closed form is too costly or does not exist, Gradient descent and Stochastic and adaptive optimizers take over. With many features the fit chases noise, and Regularization pulls it back.
  • Linear classification. The target becomes a class: surrogate losses, logistic regression with honest probabilities, metrics for unequal errors, the widest margin of the SVM, kernels for curved boundaries, more than two classes.
  • Trees and ensembles. A line cannot express interactions, a tree can, but a tree is unstable. The bias–variance decomposition explains why, bagging averages the instability away, and gradient boosting fixes the bias that averaging cannot.
  • Neural networks. Linear models and trees need features designed by hand. A network learns them, backpropagation gives its gradients, and a set of techniques makes deep networks train.
  • Learning without labels. No target at all: clustering, mixtures and EM, dimensionality reduction, anomaly detection.
  • Beyond classification. The answer is an order: learning to rank and recommender systems.

Three limitations hold for all of it. Every guarantee is about objects from the same PP; a new market or a crisis changes PP, and the validated risk no longer applies. A model minimizes the loss it is given; with 1% fraud, a model that never predicts fraud scores 99% accuracy. And prediction is not causation: a model of P(y∣x)P(y \mid x) says what yy tends to be when xx is observed, not what yy becomes when xx is changed.

This topic treated every object as a ready vector of numbers and every row as an independent draw from the distribution the model will meet. Real tables arrive with categories, missing values, dates and free text. And the easiest way to break the second assumption is to let information about the target slip into the features. The next topic, Data, features and leakage, turns raw columns into features and shows how leakage makes a useless model look excellent.

Connections to the foundations

One question runs through this course: how does a program learn a rule from examples, and how do we know the rule will work on data it has not seen?

A bank decides whom to lend to, a shop how much stock to order, a search engine which ten pages to show first. No formula derived from first principles gives these answers. Each decision comes with a history instead: loans that were or were not repaid, past sales, past clicks. Machine learning turns such a history into a rule that predicts the outcome for a new case.

Most of this work runs on tables: prices, credit, churn, demand. Its workhorses are linear models, decision trees and gradient boosting. Neural networks are built from the same parts: linear maps, losses, gradient descent and regularization.

Fitting a rule to the history is the easy part. The hard part is generalization. A rule that is perfect on the examples can be useless on the next case, and a careless check can make a useless rule look perfect.

That is why this course comes after two others. The course Probability Theory gave the language for "the next case": data are random draws, quality is an expected loss, a sample average estimates it with an error that shrinks like 1/n1/\sqrt n, and the best possible answer is a conditional expectation. The course Mathematics for ML gave the machinery for "finding the rule": vectors and matrices for the data, gradients and convexity for minimizing a loss over many parameters, the SVD and duality for the methods built on them. This topic sets up the problem in that language and lays out the course.

Check your understanding

The same questions as in Pulse. Answers are shared between modes.

Full notes

Answers are saved on the server and tied to this browser until you sign in.