10

Generalizing and evaluating

How do you know whether a model really works?

9 minExecutive path

Generalizing and evaluating

With voice. You can pause and jump to any step.

Lesson complete

Subtitles

A model that gets all its training examples right can still fail on new cases. Measuring well means measuring with data the model has never seen.

Voice

No voice: the lesson advances on its own with subtitles.

The voice for this lesson is being recorded: for now it advances on its own with subtitles.

0:00 / 0:00

What you will achieve

  • Tell underfitting from overfitting and detect them by comparing training error with validation error.
  • Explain what the training, validation, and test sets are for, and what data leakage is.
  • Compute and interpret precision, recall, and the confusion matrix, including the effect of the base rate.

Key ideas

  1. Lowering training error is not enough: what matters is error on data the model has not seen.
  2. Underfitting = the model is too simple; overfitting = it learns the noise. A large gap between training and validation error is the signal.
  3. Train to learn, validate to choose, test to report (only once). If the exam leaks into training, that is data leakage.
  4. Overfitting is curbed with more data, simpler models, regularization, and early stopping.
  5. Accuracy misleads with imbalanced classes: look at precision, recall, and the confusion matrix, and remember the base rate rules.

What many people believe

Common belief “The model is 99% accurate in tests, so it works very well.”

What is true It depends on which data it was measured on and on the base rate. On data the model already saw, the number says nothing about new cases; and with rare events, 99% can be useless.

Check yourself

Four questions. No grade, no account: they just show whether the idea stuck.

ConceptA model has very low training error and high validation error. What does it indicate?
ConceptWhat is the test set for?
CalculationA disease affects 1% of the population. A test has 90% sensitivity and 90% specificity. Among those who test positive, what fraction is truly sick?
ApplicationA vendor boasts “98% accuracy” in fraud detection, where fraud is 1% of transactions. What do you do?

Under the hoodFor those who want the math and the code. You do not need it to follow the course.

Bias, variance, and noise

For a model f^\hat f trained on a random set, the expected error at a new point decomposes into

E[(y−f^(x))2]=(E[f^(x)]−f(x))2⏟bias2+Var(f^(x))⏟variance+σ2⏟irreducible noise.\mathbb{E}\big[(y-\hat f(x))^2\big] = \underbrace{\big(\mathbb{E}[\hat f(x)]-f(x)\big)^2}_{\text{bias}^2} + \underbrace{\mathrm{Var}\big(\hat f(x)\big)}_{\text{variance}} + \underbrace{\sigma^2}_{\text{irreducible noise}}.

This is the standard form for squared error (Hastie, Tibshirani, and Friedman, eq. 7.9). Underfitting is high bias (a model that is too rigid); overfitting is high variance (the model changes a lot with each sample). In the lesson the noise is σ=0.2\sigma = 0.2: on average, no model can go below that error on new data (on one particular 80-point sample it can land a little above or below), and the best degree (4) reaches ≈0.22\approx 0.22 on the scene's validation set.

This was checked by simulating 4,000 training sets with the same data recipe (verify-data.ts): the sum σ2+bias2+variance\sigma^2+\text{bias}^2+\text{variance} matches the simulated error at new points. With degree 1: bias² ≈ 0.066 and variance ≈ 0.007 (the error is bias). With degree 4: 0.001 and 0.017. With degree 10: bias² ≈ 0 and variance ≈ 1.6, mostly toward the ends of the interval (the error is variance). With degree 10 and λ=0.03\lambda = 0.03: 0.005 and 0.018; regularization trades variance for a little bias.

Ridge regularization

Polynomial fitting with a penalty λ\lambda on the weights minimizes ∥y−Xw∥2+λ∥w∥2\lVert y - Xw\rVert^2 + \lambda \lVert w\rVert^2, with closed-form solution

w^=(X⊤X+λI)−1X⊤y.\hat w = (X^\top X + \lambda I)^{-1} X^\top y.

With λ=0\lambda = 0 you recover the free fit; as λ\lambda grows the weights shrink and the curve smooths out (in the scene, the norm of the degree-10 weights drops from ≈ 327 at λ=0\lambda = 0 to ≈ 0.19 at λ=10\lambda = 10). Two caveats. The constant term is not penalized (as in the scene and in scikit-learn; Hastie et al., §3.4.1), and inputs should be normalized first (the scene maps x∈[0,1]x\in[0,1] to [−1,1][-1,1]). And with λ\lambda too large the model underfits again: at degree 10, the scene's validation error falls until λ≈0.02\lambda \approx 0.02 (≈ 0.24) and then rises (≈ 0.44 at λ=10\lambda = 10, worse than the line).

Early stopping in gradient descent acts similarly to regularization: stopping earlier limits how large the weights can grow. For a linear model with squared error and plain gradient descent it is equivalent, under a quadratic approximation, to L2L^2 regularization (Goodfellow, Bengio, and Courville, §7.8). Other defenses: more data (real or augmented, §7.4) and, in neural networks, dropout: randomly switching off units during training (Srivastava et al., 2014).

Classification metrics

With true positives TPTP, false positives FPFP, false negatives FNFN, and true negatives TNTN:

accuracy=TP+TNTP+FP+FN+TN,precision=TPTP+FP,recall=TPTP+FN,F1=2 P RP+R.\text{accuracy}=\frac{TP+TN}{TP+FP+FN+TN},\quad \text{precision}=\frac{TP}{TP+FP},\quad \text{recall}=\frac{TP}{TP+FN},\quad F_1=\frac{2\,P\,R}{P+R}.

If nobody is flagged (TP+FP=0TP+FP=0) precision is 0/00/0: by convention (the scene’s) it is taken as 1, so a detector that always says “healthy” has perfect precision and recall 0, which is why you have to look at both (Goodfellow et al., §11.1). F1F_1 is the harmonic mean of precision and recall.

The threshold and the costs

If a false negative costs cFNc_{FN} and a false positive costs cFPc_{FP} (hits cost nothing), the lowest-expected-cost decision is to flag “positive” when

P(sick∣score)≥cFPcFP+cFN(Elkan, 2001).P(\text{sick}\mid \text{score}) \ge \frac{c_{FP}}{c_{FP}+c_{FN}}\qquad\text{(Elkan, 2001)}.

With equal costs the probability cutoff is 0.5; if missing a case costs 10 times more, it drops to 1/11≈0.091/11\approx 0.09. In the scene (two bell curves and 10% sick) that gives the optimal score thresholds 2.23 (equal costs), 1.46 (missing a case costs 10), and 3.00 (a false alarm costs 10).

The base rate (Bayes’ theorem)

With prevalence pp, sensitivity ss (= recall), and specificity cc, the probability of being sick given a positive result is

P(sick∣+)=s ps p+(1−c)(1−p).P(\text{sick}\mid +)=\frac{s\,p}{s\,p+(1-c)(1-p)}.

With p=0.01p=0.01 and s=c=0.95s=c=0.95: 0.00950.0095+0.0495≈0.16\dfrac{0.0095}{0.0095+0.0495}\approx 0.16, the “one in six” of the lesson. With s=c=0.95s=c=0.95 there are more false alarms than hits as long as the prevalence is below 5%.

Presenting the calculation in frequencies (“out of 2,000 people, 20 sick, 19 detected…”) instead of probabilities helps reasoning: Gigerenzer and Hoffrage (1995) show that Bayesian algorithms are computationally simpler in that format and that, with it, people without statistical training followed Bayesian algorithms in up to 50% of their inferences. It is the format the lesson uses.

In code

import numpy as np
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import PolynomialFeatures
from sklearn.linear_model import Ridge

f = lambda x: 0.6 * np.sin(2 * np.pi * x) + 0.2          # the true signal
rng = np.random.default_rng(0)
x_tr = ((np.arange(12) + 0.5) / 12)[:, None]              # 12 measurements spread over [0, 1]
y_tr = f(x_tr[:, 0]) + 0.2 * rng.normal(size=12)
x_va = rng.uniform(0, 1, 80)[:, None]                     # 80 new measurements
y_va = f(x_va[:, 0]) + 0.2 * rng.normal(size=80)

for degree in (1, 4, 10):
    for lam in (1e-9, 3e-2):                              # 1e-9 stands in for λ = 0
        m = make_pipeline(PolynomialFeatures(degree, include_bias=False), Ridge(alpha=lam)).fit(2 * x_tr - 1, y_tr)
        rmse = lambda a, b: float(np.sqrt(np.mean((m.predict(2 * a - 1) - b) ** 2)))
        print(degree, lam, round(rmse(x_tr, y_tr), 3), round(rmse(x_va, y_va), 3))   # training and validation

# With that seed: degree 1 → 0.302 and 0.339 (underfitting); degree 4 → 0.093 and 0.221 (best validation);
# degree 10 → 0.006 and 0.251 with λ ≈ 0 (overfitting) and 0.103 and 0.237 with λ = 0.03.
# These are new data from the same recipe as the scene: they do not repeat its exact numbers.

def ppv(prev, sens, spec):          # positive predictive value
    tp, fp = prev * sens, (1 - prev) * (1 - spec)
    return tp / (tp + fp)

print(round(ppv(0.01, 0.95, 0.95), 3))   # 0.161

What comes next

For images, a fully connected network does not scale. Lesson 11 shows the idea of convolutions. Lesson 34 returns to evaluation for generative AI systems, where measuring well is harder.

Decision lens

What this idea means if your job is to decide, not to code.

  • Always ask for performance to be reported on data the model has not seen, and for the team to explain how it avoided data leakage.
  • A single accuracy number is not enough: ask for precision and recall, and the confusion matrix with the real cost of each type of error.
  • With rare events (fraud, failures, disease) the base rate rules: work out how many false alarms your operation can absorb before approving a system.
  • The decision threshold is a business lever: adjust it to the cost of a false negative versus a false positive and revisit it when the environment changes.

Terms in this lesson

Full transcript
CommentsThis lesson’s public conversation: questions, facts to check, ideas.

Comments live in GitHub Discussions, in the course’s public repository; writing one requires a GitHub account. They load from giscus.app when you open this section. The course reviewers read them, and if a change is accepted, it is applied in both languages. Open the thread on GitHub

Sources