Generalizing and evaluating
How do you know whether a model really works?
Lesson complete
If you like:
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.
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.
Review modeComment on this stepI finished the lesson
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
- Lowering training error is not enough: what matters is error on data the model has not seen.
- Underfitting = the model is too simple; overfitting = it learns the noise. A large gap between training and validation error is the signal.
- Train to learn, validate to choose, test to report (only once). If the exam leaks into training, that is data leakage.
- Overfitting is curbed with more data, simpler models, regularization, and early stopping.
- 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.
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 trained on a random set, the expected error at a new point decomposes into
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 : 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 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 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.005 and 0.018; regularization trades variance for a little bias.
Ridge regularization
Polynomial fitting with a penalty on the weights minimizes , with closed-form solution
With you recover the free fit; as grows the weights shrink and the curve smooths out (in the scene, the norm of the degree-10 weights drops from ≈ 327 at to ≈ 0.19 at ). 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 to ). And with too large the model underfits again: at degree 10, the scene's validation error falls until (≈ 0.24) and then rises (≈ 0.44 at , 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 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 , false positives , false negatives , and true negatives :
If nobody is flagged () precision is : 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). is the harmonic mean of precision and recall.
The threshold and the costs
If a false negative costs and a false positive costs (hits cost nothing), the lowest-expected-cost decision is to flag “positive” when
With equal costs the probability cutoff is 0.5; if missing a case costs 10 times more, it drops to . 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 , sensitivity (= recall), and specificity , the probability of being sick given a positive result is
With and : , the “one in six” of the lesson. With 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
- Overfitting When a model learns the noise in its training data and therefore fails on new data. It shows as a large gap between training and validation error.
- Underfitting When a model is too simple to capture the signal: it fails even on the training data.
- Validation set Data the model does not use to fit itself, used to choose between models or hyperparameters.
- Test set Held-out data used once at the end to report the expected performance on new cases.
- Data leakage Information from the evaluation data that slips into training, inflating the measured result.
- Regularization Any change to learning meant to reduce the error on new data, even if it does not lower the training error. The simplest penalizes model complexity (for example, large weights); early stopping and dropout are other forms.
- Precision Of everything the model flagged as positive, the fraction that really was: TP / (TP + FP).
- Recall Of all real positives, the fraction the model found: TP / (TP + FN).
- Confusion matrix A table with the hits and mistakes of each kind: true and false positives, true and false negatives.
- Base rate The actual frequency of an event in the population (for example, 1% of transactions being fraud). It conditions how many false alarms a detector generates.
Full transcript
Sources
- Hastie, T., Tibshirani, R., Friedman, J. (2009). The Elements of Statistical Learning (2.ª ed.), cap. 3 (§3.4.1, regresión ridge) y cap. 7 (§7.1–7.3: reparto en entrenamiento, validación y prueba; sesgo y varianza)
- Goodfellow, I., Bengio, Y., Courville, A. (2016). Deep Learning, cap. 5 (§5.2 capacidad, sobreajuste y subajuste; §5.3 conjuntos de validación)
- Goodfellow, I., Bengio, Y., Courville, A. (2016). Deep Learning, cap. 7 (§7.1.1 decaimiento de pesos, §7.4 aumento de datos, §7.8 parada temprana, §7.12 dropout)
- Goodfellow, I., Bengio, Y., Courville, A. (2016). Deep Learning, cap. 11 (§11.1 métricas de rendimiento: precisión, recall, F)
- Kapoor, S., Narayanan, A. (2023). Leakage and the reproducibility crisis in machine-learning-based science (Patterns 4(9), 100804)
- Srivastava, N., Hinton, G., Krizhevsky, A., Sutskever, I., Salakhutdinov, R. (2014). Dropout: A Simple Way to Prevent Neural Networks from Overfitting (JMLR 15, 1929–1958)
- Elkan, C. (2001). The Foundations of Cost-Sensitive Learning (IJCAI 2001)
- Gigerenzer, G., Hoffrage, U. (1995). How to improve Bayesian reasoning without instruction: Frequency formats (Psychological Review 102(4), 684–704)
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