Overfitting and Evaluation
How overfitting happens, how to split data so a model is tested honestly, and what accuracy, precision and recall each tell you about a classifier.
On this page
Overfitting is what happens when a model learns the noise and coincidences in its training data along with the real pattern, so it scores well on examples it has seen and badly on new ones. Evaluation is the practice of measuring a model on data it did not learn from, so that you find this out before your users do.
How overfitting happens
A model fits its training data by adjusting its parameters to reduce error on those examples. If the model is flexible enough, it can reduce that error to almost zero by fitting the random quirks of the particular examples it was given, as well as the pattern that holds in general. Those quirks do not repeat in new data, so the fitted details hurt predictions instead of helping them.
In What Is Machine Learning, the rule "late if at least 6 km" got 6 of 7 deliveries right, and the one miss was a 10 km trip that arrived on time. A fussier rule, "late if 6 to 9 km, or 11 km and over", gets all 7 right. That rule makes no sense, because it says 10 km is on time while 9 km and 11 km are late, and it only exists to cover one unusual day. It fits the training data better and will predict new deliveries worse.
Underfitting is the opposite problem. The model is too simple to capture the pattern, such as predicting "on time" for every delivery, and it does badly on both the training data and new data. The difference between the two is easy to read from the scores. An underfit model has a poor training score. An overfit model has a good training score and a clearly worse score on held-out data.
Ways to reduce overfitting
Getting more training data is the most reliable fix, because quirks that appear in a few examples are averaged out over many. When you cannot get more data, use a simpler model, such as a tree with fewer levels or a network with fewer parameters, so there is less capacity to memorize.
Regularization keeps the flexible model but adds a penalty on large parameter values to the quantity being minimized, which pushes the model toward smoother and simpler fits. Early stopping applies to models trained in many rounds. You watch the error on validation data during training and stop when it starts to rise, even though the training error is still falling. Each of these has a setting, such as the size of the penalty or the number of rounds, and you choose it by comparing validation scores, as described in the next section.
Splitting data into training, validation and test sets
Before training, you divide your labelled examples into separate groups, and each group has a different job.
- The training set, often around 70 to 80% of the data, is what the model learns from.
- The validation set is used to compare choices you make about the model, such as which features to use, how flexible the model is, or which learning rate to set.
- The test set is kept aside until the end. You score the final model on it once, and that score is your estimate of real-world performance.
The reason for a separate test set is that every time you look at a validation score and change something, your choices adapt a little to that validation data. If you try twenty settings and keep the best one, its validation score is slightly flattering, because you picked it for being high. The test set played no part in any of those choices, so its score is not inflated in this way.
When you do not have enough data to spare a validation set, use cross-validation. You split the training data into a number of parts, for example 5, and train 5 times, each time holding out a different part for scoring. The average of the 5 scores is a steadier estimate than a single split, at the cost of training the model 5 times.
Accuracy and the confusion matrix
Accuracy is the share of predictions that were right. It is simple, and it is misleading whenever one class is much more common than the other. Suppose a fraud detector checks 10 card payments and 3 of them are fraud. A lazy model that always answers "fine" is right for the 7 genuine payments, so it scores 70% while catching no fraud at all. Real fraud is much rarer than 3 in 10, so the same lazy model can score 99.9%.
To see what a classifier does for each class, you sort every prediction into one of four groups, which together form a confusion matrix. A true positive is a fraud that was flagged. A false negative is a fraud that was not flagged, which is a miss. A false positive is a genuine payment that was flagged, which is a false alarm. A true negative is a genuine payment that was not flagged.
- actual0Fi1ok2ok3F4ok5ok6ok7F8ok9okflagged0yes1no2yes3no4no5no6no7yes8no9no
flagged not flagged fraud 1 0 fine 0 0 1Payment 0 is fraud and was flagged, so it is a true positive.
- actual0F1oki2ok3F4ok5ok6ok7F8ok9okflagged0yes1no2yes3no4no5no6no7yes8no9no
flagged not flagged fraud 1 0 fine 0 1 2Payment 1 is genuine and was not flagged, so it is a true negative.
- actual0F1ok2oki3F4ok5ok6ok7F8ok9okflagged0yes1no2yes3no4no5no6no7yes8no9no
flagged not flagged fraud 1 0 fine 1 1 3Payment 2 is genuine but was flagged, so it is a false positive. The customer gets an unnecessary call from the bank.
- actual0F1ok2ok3Fi4ok5ok6ok7F8ok9okflagged0yes1no2yes3no4no5no6no7yes8no9no
flagged not flagged fraud 1 1 fine 1 1 4Payment 3 is fraud but was let through, so it is a false negative. This is the case that loses money.
- actual0F1ok2ok3F4ok5ok6oki7F8ok9okflagged0yes1no2yes3no4no5no6no7yes8no9no
flagged not flagged fraud 1 1 fine 1 4 5Payments 4 to 6 are genuine and were not flagged, which adds three more true negatives.
- actual0F1ok2ok3F4ok5ok6ok7Fi8ok9okflagged0yes1no2yes3no4no5no6no7yes8no9no
flagged not flagged fraud 2 1 fine 1 4 6Payment 7 is fraud and was flagged, so it is a second true positive.
- actual0F1ok2ok3F4ok5ok6ok7F8ok9okiflagged0yes1no2yes3no4no5no6no7yes8no9no
flagged not flagged fraud 2 1 fine 1 6 7Payments 8 and 9 are genuine and were not flagged. All 10 payments are now counted in the matrix.
flagged not flagged fraud 2 1 fine 1 6 - accuracy
- 8/10
8Accuracy counts the diagonal, which is the correct predictions: 2 + 6 = 8 out of 10, or 80%.
flagged not flagged fraud 2 1 fine 1 6 - accuracy
- 8/10
- precision
- 2/3
- recall
- 2/3
9Precision is the share of flagged payments that were fraud, which is 2 of 3. Recall is the share of frauds that were flagged, which is also 2 of 3.
flagged not flagged fraud 0 3 fine 0 7 - accuracy
- 7/10
- recall
- 0/3
10The lazy model that never flags anything has 70% accuracy, only 10 points lower, but its recall is 0 of 3. Accuracy alone hid that.
Precision and recall
Precision answers the question of how often the model is right when it raises a flag. It is the true positives divided by everything flagged, so low precision means many false alarms. Recall answers the question of how many of the real cases the model found. It is the true positives divided by all real positives, so low recall means many misses.
The two pull against each other. Most classifiers output a score and flag everything above a threshold, as described in Regression and Classification. Raising the threshold flags fewer items, so the ones that remain are more likely to be correct, which raises precision, but more real cases slip under the threshold, which lowers recall. Lowering the threshold does the reverse.
Which side to favour depends on what each kind of mistake costs. A cancer screening test should have high recall, because a missed case is far worse than an extra follow-up appointment. A system that blocks accounts automatically should have high precision, because every false positive locks out a legitimate customer. When you must report a single number, F1 is the harmonic mean of precision and recall, which is low if either one is low. It is only a sensible summary when you value the two equally.
Stratified splits for rare classes
When a class is rare, a random split can leave the test set with very few positive examples, or none, so the recall you measure is mostly luck. A stratified split divides each class separately, so the training, validation and test sets all keep the same share of positives as the full data. Use it whenever the positive class is a few percent of the data or less, and use the stratified form of cross-validation for the same reason.
Threshold-free comparison with the ROC curve
To compare two models before choosing a threshold, you can plot recall against the false positive rate for every possible threshold. This is the ROC curve, and the area under it (AUC) is the probability that the model scores a random positive example above a random negative one. AUC says nothing about the precision you will get at the threshold you ship, and with a very rare positive class it can look good while precision is poor, so a precision-recall curve is more informative there.
Test data that differs from real data
A good test score only predicts real performance if the test data looks like the data the model will see in use. If the live data changes over time, for example because customer behaviour shifts, the score you measured at launch slowly stops being true. For that reason, deployed models are re-scored on fresh labelled samples from time to time.
// actual and predicted are lists of 1 (fraud) and 0 (fine).
function evaluate(actual, predicted) {
let tp = 0, fp = 0, fn = 0, tn = 0;
for (let i = 0; i < actual.length; i++) {
if (predicted[i] === 1 && actual[i] === 1) tp++;
else if (predicted[i] === 1) fp++; // flagged a fine payment
else if (actual[i] === 1) fn++; // missed a fraud
else tn++;
}
return {
accuracy: (tp + tn) / actual.length,
precision: tp + fp ? tp / (tp + fp) : 0, // of the flags, how many were right
recall: tp + fn ? tp / (tp + fn) : 0, // of the frauds, how many we caught
};
}
evaluate([1, 0, 0, 1, 0, 0, 0, 1, 0, 0],
[1, 0, 1, 0, 0, 0, 0, 1, 0, 0]);
// { accuracy: 0.8, precision: 0.666..., recall: 0.666... }def evaluate(actual, predicted):
"""actual and predicted are lists of 1 (fraud) and 0 (fine)."""
tp = fp = fn = tn = 0
for a, p in zip(actual, predicted):
if p == 1 and a == 1:
tp += 1
elif p == 1:
fp += 1 # flagged a fine payment
elif a == 1:
fn += 1 # missed a fraud
else:
tn += 1
return {
"accuracy": (tp + tn) / len(actual),
"precision": tp / (tp + fp) if tp + fp else 0,
"recall": tp / (tp + fn) if tp + fn else 0,
}
evaluate([1, 0, 0, 1, 0, 0, 0, 1, 0, 0],
[1, 0, 1, 0, 0, 0, 0, 1, 0, 0])
# {'accuracy': 0.8, 'precision': 0.666..., 'recall': 0.666...}Data leakage and other ways a score becomes wrong
What this changes in practice
Decide how you will evaluate before you start training, and fix the test set first. Choose the metric from the cost of mistakes: if the positive class is rare, look at precision and recall, not accuracy. Compare the training score with the validation score every time. A large gap means overfitting, and the response is more data, a simpler model or regularization. Low scores on both mean the model needs more capacity or better features.
The same habit applies when you evaluate a language model on your own task, for example with a set of prompts and expected answers. If you tune the prompt until it passes that set, the set has become your validation data, so keep a separate group of cases that you only run at the end.
A team reports on a model that predicts whether a customer will cancel next month. List what makes you doubt the result, and what you would ask for instead.
Show a sample answer
- The score was measured on training data. Ask for a score on a held-out test set, ideally the most recent months, since the model predicts the future.
- Accuracy is the wrong metric when positives are rare. With 4% cancelling, predicting "stays" for everyone scores 96%, which is exactly the number reported. Ask for precision and recall on cancellations.
- The strongest feature may be leaking. "Days since last login", measured on the day the data was pulled, is very large for customers who have already cancelled. Ask for each feature to be measured as of the date the prediction would have been made.
Check yourself
A model scores 99% on its training data and 71% on the test set. What is the most likely problem?
A disease affects 1 in 200 people. What accuracy does a test that always says "healthy" have?
A spam filter has high precision and low recall. What do users notice?
You tune a model's settings by repeatedly checking the test score and keeping the best one. What is wrong with the final test score?
What to practise next
To code the confusion matrix and these scores yourself, try Bruised Apple Detector. Decision Trees and Ensembles covers models that learn a chain of yes-or-no questions, and shows how combining many trees reduces overfitting.