Show contents
Chapter 4 of 7 · 20 min
Evaluate a model
By the end of this chapter, you'll be able to
- Recognise overfitting by comparing training error and test error
- Choose a model's complexity with a validation set
- Build a confusion matrix
- Compute and interpret precision and recall
Overfitting
A model that is too simple misses the trend: this is underfitting. A model that is too complex also learns the noise of its examples, by heart: this is overfitting. It fits the training data perfectly and makes big mistakes elsewhere.
Let's test polynomials of increasing degree on data that actually follows a straight line, with noise:
import numpy as np
rng = np.random.default_rng(4)
x_train = np.sort(rng.uniform(0, 10, 10))
y_train = 2 + 0.5 * x_train + rng.normal(0, 0.6, 10)
x_test = rng.uniform(0, 10, 40)
y_test = 2 + 0.5 * x_test + rng.normal(0, 0.6, 40)
for degree in (1, 3, 9):
coefs = np.polyfit(x_train, y_train, degree)
mse_train = ((np.polyval(coefs, x_train) - y_train) ** 2).mean()
mse_test = ((np.polyval(coefs, x_test) - y_test) ** 2).mean()
print(f"degree {degree}: training MSE = {mse_train:.3f} test MSE = {mse_test:.3f}")
degree 1: training MSE = 0.497 test MSE = 0.507
degree 3: training MSE = 0.492 test MSE = 0.521
degree 9: training MSE = 0.000 test MSE = 7048.040
np.polyval(coefs, x) computes the polynomial at the points x. The degree-9 polynomial goes exactly through the 10 training points (zero error), but between those points it makes absurd loops: its test error is thousands of times larger. More complexity is not better: the right model is the one that generalises.
We measure the chosen model on the test set only once: this is the honest estimate of its quality.
Text description of the animation
- We shuffle the examples, then split them into three sets that do not overlap.
- Each candidate model learns its parameters on the training set.
- We compare the candidates on the validation set and keep the best.
- We measure the chosen model on the test set only once: this is the honest estimate of its quality.
Choosing the degree by looking at the test error would be cheating: the test set would be used to tune the model, and would no longer be an independent measure. So a third set, the validation set, is kept to compare the candidates. When data is scarce, cross-validation rotates this role across several parts of the data.
Beyond accuracy: the confusion matrix
For a two-class classification, we call positive the class we want to detect (here, “diseased”). Each prediction falls into one of the four cells of the confusion matrix:
| predicted diseased | predicted healthy | |
|---|---|---|
| really diseased | true positive (TP) | false negative (FN) |
| really healthy | false positive (FP) | true negative (TN) |
Two measures follow:
- precision = TP / (TP + FP): among the plants flagged as diseased, how many really are?
- recall = TP / (TP + FN): among the plants that are really diseased, how many were detected?
import numpy as np
truth = np.array([1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0])
predicted = np.array([1, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0])
tp = int(((predicted == 1) & (truth == 1)).sum())
fp = int(((predicted == 1) & (truth == 0)).sum())
fn = int(((predicted == 0) & (truth == 1)).sum())
tn = int(((predicted == 0) & (truth == 0)).sum())
print("TP FP FN TN:", tp, fp, fn, tn)
print("accuracy:", (predicted == truth).mean())
print("precision:", tp / (tp + fp))
print("recall:", tp / (tp + fn))
TP FP FN TN: 3 2 1 14
accuracy: 0.85
precision: 0.6
recall: 0.75
1 = diseased, 0 = healthy. The model detects 3 of the 4 diseased plants (recall of 0.75) and raises 2 false alarms (precision of 0.6). Depending on the use, you favour one or the other: for screening, missing a sick plant (false negative) often costs more than a false alarm, which will be checked afterwards.
Mini-lab: looking for the right degreePython 3.13
Output
Click “Run”: Python will load in your browser (about 10 MB the first time).Your code runs in your browser, isolated from the page. · Ctrl/⌘ + Enter to run · Esc then Tab to leave the editor
Your turn
Worked exercise
Worked exercise: the spam filter
A filter classifies 12 messages (1 = spam, 0 = normal). Truths: [1, 1, 1, 0, 0, 0, 0, 0, 1, 0, 0, 1]. Predictions: [1, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 0]. Compute accuracy, precision and recall, rounded to 2 decimal places. Which defect would bother a user most?
Hint 1
&, as in the chapter.Hint 2
Show the solution and common mistakes
import numpy as np
truth = np.array([1, 1, 1, 0, 0, 0, 0, 0, 1, 0, 0, 1])
predicted = np.array([1, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 0])
tp = int(((predicted == 1) & (truth == 1)).sum())
fp = int(((predicted == 1) & (truth == 0)).sum())
fn = int(((predicted == 0) & (truth == 1)).sum())
print("accuracy:", round(float((predicted == truth).mean()), 2))
print("precision:", round(tp / (tp + fp), 2))
print("recall:", round(tp / (tp + fn), 2))
accuracy: 0.75
precision: 0.75
recall: 0.6
The filter lets 2 spam messages out of 5 through (recall of 0.6) and wrongly classifies 1 normal message (precision of 0.75). For a user, an important message lost in the spam folder (false positive) is often worse than one more spam in the inbox: you then aim for a high precision, even at the cost of slightly lower recall.
Common mistakes:
- Mixing up precision and recall: precision looks at the flags (the “predicted” column), recall looks at the real cases (the “really” row).
- Choosing the best model by the test set, then announcing its test score: that score is then too optimistic. The choice is made on validation.
Summary
- 1Overfitting: a very low training error and a high test error.
- 2A model's complexity is chosen on a validation set, and the test set is kept for the final verdict.
- 3The confusion matrix counts true and false positives and negatives.
- 4Precision = TP / (TP + FP), recall = TP / (TP + FN); the use case says which to favour.
- 5When a class is rare, accuracy is misleading.
Your progress is saved on this device. Create a free account to keep your progress on all your devices.