Data, Models and Loss

Supervised learning has exactly three ingredients. Learn to spot them in any problem and half the battle is won.

  1. Data: examples \(\{(x_1,y_1), \dots, (x_n,y_n)\}\).
  2. A model family (hypothesis space) \(\mathcal{H}\): the shapes of function you're willing to consider.
  3. A loss function \(L(\hat y, y)\): how much you're penalized for predicting \(\hat y\) when the truth is \(y\).

Learning = pick the \(h \in \mathcal{H}\) that makes the average loss on the data small. Let's look at each ingredient.

Ingredient 1: data, and the assumption that makes learning possible

Why should the past say anything about the future? Only because we assume they come from the same process. Formally:

The i.i.d. assumption. Every example (training and future) is drawn independently from the same, fixed but unknown probability distribution \(P(x, y)\).

Each part of this assumption matters:

  • Same distribution: if Bolt is trained on summer data and deployed in the monsoon, all bets are off. This is called distribution shift, and it is the #1 reason real models fail.
  • Independent: if the 20 training deliveries were all from one rainy evening, they're not independent, and the model learns "evenings are slow" when really it's "that evening was slow."
  • Unknown: if we knew \(P(x,y)\) we wouldn't need data. We'd compute the best prediction directly. Data is our only window into \(P\).

A useful way to think about the data-generating process for regression:

$$ y = f(x) + \varepsilon, \qquad \mathbb{E}[\varepsilon] = 0,\ \ \operatorname{Var}(\varepsilon) = \sigma^2 $$

Here \(f\) is the true underlying pattern (the "signal") and \(\varepsilon\) is noise: everything that affects delivery time that our features don't capture (lift queues, a chatty security guard). No model can predict \(\varepsilon\), so \(\sigma^2\) is a floor on achievable error. It is called the irreducible error, and it will reappear in the bias–variance decomposition.

Ingredient 2: the model family

For Bolt's delivery times, a natural family is polynomials of degree \(d\):

$$ h_w(x) = w_0 + w_1 x + w_2 x^2 + \dots + w_d x^d = \sum_{j=0}^{d} w_j x^j $$

The degree \(d\) is a hyperparameter: it controls how flexible (how "complex") the family is. \(d=0\) is a flat line, \(d=1\) a straight line, \(d=3\) can bend twice, and \(d=14\) can wiggle through 15 points exactly.

Intuition: "linear" regression with curves?

A polynomial is curved in \(x\) but linear in the weights \(w\). If we build a feature vector \(\phi(x) = (1, x, x^2, \dots, x^d)\), the model is just \(h(x) = w^\top \phi(x)\), a dot product. That's why "polynomial regression" is solved with exactly the same linear-regression machinery. This trick, make features nonlinear and keep the model linear in its weights, is used everywhere in ML.

Ingredient 3: the loss

For regression, the standard choice is squared error, \(L(\hat y, y) = (\hat y - y)^2\). Averaged over the data it gives the mean squared error:

$$ \text{MSE}(w) = \frac{1}{n}\sum_{i=1}^{n} \big(h_w(x_i) - y_i\big)^2 $$

Why squared, and not absolute error \(|\hat y - y|\)?

  • It is smooth, so calculus works and gives a closed-form solution (below).
  • It punishes big mistakes much more than small ones. A 10-minute error costs 100, but two 5-minute errors cost only 50.
  • Its minimizer is the mean: the constant \(c\) that minimizes \(\sum (c - y_i)^2\) is \(\bar y\). So squared loss makes the model predict the average outcome for each \(x\), which is exactly \(f(x)\) under our noise model. Absolute loss gives the median, which is more robust to outliers.

For classification you'll meet 0–1 loss (1 if wrong, 0 if right, so its average is the error rate) and, for trees, measures based on entropy (Chapter 6).

Training = minimizing the loss: least squares from scratch

Stack the features of all \(n\) examples into a design matrix \(X\) (one row per example) and the targets into a vector \(y\). For a straight line, row \(i\) of \(X\) is \((1, x_i)\). Then the vector of predictions is \(Xw\), and

$$ \text{MSE}(w) = \tfrac{1}{n}\,\lVert Xw - y\rVert^2 = \tfrac1n (Xw - y)^\top (Xw - y). $$

This is a bowl-shaped (convex) function of \(w\). Its minimum is where the gradient is zero:

$$ \nabla_w \text{MSE} = \tfrac{2}{n} X^\top (Xw - y) = 0 \quad\Longrightarrow\quad \boxed{\,X^\top X\, w = X^\top y\,} $$

These are the normal equations. Solve them and you have the best line. No iteration needed.

Exam corner: fitting a line by hand

For \(h(x) = w_0 + w_1 x\), the normal equations reduce to the formulas you may remember from statistics:

$$ w_1 = \frac{\sum_i (x_i - \bar x)(y_i - \bar y)}{\sum_i (x_i - \bar x)^2}, \qquad w_0 = \bar y - w_1 \bar x. $$

Mini example. Points \((1,2), (2,3), (3,7)\). Then \(\bar x = 2,\ \bar y = 4\). Numerator \(= (-1)(-2) + 0\cdot(-1) + (1)(3) = 5\). Denominator \(= 1 + 0 + 1 = 2\). So \(w_1 = 2.5\), \(w_0 = 4 - 2.5\cdot 2 = -1\), and the line is \(\hat y = -1 + 2.5x\). Training MSE \(= \frac13[(1.5-2)^2 + (4-3)^2 + (6.5-7)^2] = \frac13(0.25+1+0.25) = 0.5\).

Let's do it in Python

We'll simulate Bolt's world, so we know the true \(f\) and can check our work. Bolt itself never sees true_time. It only sees the noisy samples.

import numpy as np

rng = np.random.default_rng(42)

def true_time(d):
    """The 'real' (unknown to Bolt) average delivery time in minutes for distance d km."""
    return 6 + 4 * d + 3 * np.sin(1.4 * d)

def make_deliveries(n):
    d = rng.uniform(0, 5, n)                      # distances in km
    t = true_time(d) + rng.normal(0, 2.0, n)      # noisy observed minutes (sigma = 2)
    return d, t

d_train, t_train = make_deliveries(20)
d_test,  t_test  = make_deliveries(1000)          # "the future"

# Fit a straight line t = w0 + w1*d by least squares (normal equations)
X = np.column_stack([np.ones_like(d_train), d_train])   # design matrix, shape (20, 2)
w = np.linalg.solve(X.T @ X, X.T @ t_train)
print("w0 = %.2f min, w1 = %.2f min/km" % (w[0], w[1]))

def mse(pred, y):
    return np.mean((pred - y) ** 2)

print("train MSE:", round(mse(X @ w, t_train), 2))
X_test = np.column_stack([np.ones_like(d_test), d_test])
print("test  MSE:", round(mse(X_test @ w, t_test), 2))
w0 = 8.55 min, w1 = 3.03 min/km
train MSE: 5.35
test  MSE: 7.43

Read these numbers carefully, because they already tell the whole story of the chapter:

  • The noise has \(\sigma = 2\), so the irreducible error is \(\sigma^2 = 4\). No model can average below about 4 on new data.
  • Our line's test MSE is 7.43, well above 4. The line is too rigid to follow the sine-shaped bend in \(f\). That extra error is bias (§2.3).
  • The training MSE (5.35) is lower than the test MSE (7.43). Training error is an optimistic estimate of future error, because the weights were chosen to fit these particular points. Never forget this.
Lab skills
  • Use np.linalg.lstsq(X, y) or np.linalg.solve(X.T@X, X.T@y). Never compute np.linalg.inv(X.T@X) explicitly: it is slower and numerically unstable.
  • For polynomials of high degree, rescale \(x\) to about [−1, 1] first. \(5^{12} \approx 2.4\times 10^8\), and mixing such huge columns with a column of ones makes \(X^\top X\) nearly singular.
  • In scikit-learn, PolynomialFeatures(degree) + LinearRegression() does the same thing. Writing it yourself once is the best way to understand it.

Empirical risk vs. true risk

Here is the formal version of what we just saw. What we want to minimize is the true risk (expected loss on the whole distribution):

$$ R(h) = \mathbb{E}_{(x,y)\sim P}\big[L(h(x), y)\big] $$

But \(P\) is unknown, so we minimize the empirical risk (average loss on the training set) instead:

$$ \hat R(h) = \frac1n \sum_{i=1}^n L(h(x_i), y_i) $$

This strategy is called empirical risk minimization (ERM). For any fixed \(h\), \(\hat R(h)\) is an unbiased estimate of \(R(h)\) by the law of large numbers. But the \(h\) we pick is chosen to make \(\hat R\) small, so for that \(h\), \(\hat R\) is biased downward. The bigger and more flexible \(\mathcal{H}\) is, the more room there is to find an \(h\) that looks great on the sample by luck, and the bigger the gap \(R(\hat h) - \hat R(\hat h)\). That gap is the generalization gap, and the next section shows it growing before your eyes.

Connections

"Choose \(w\) to minimize a function" is an optimization (search) problem. Here we got lucky: MSE is convex, so calculus solves it in one shot. In Chapter 3 the objective will be bumpy or have no gradient at all (e.g. an error you can only query from a server), and we'll need hill climbing and genetic algorithms. The §3.4 lab uses a GA to choose exactly these polynomial weights.