Skip to content

How to Avoid Overfitting With a Held-Out Test Set

Overfitting is what happens when a model follows the errors, or noise, in its training data too closely, so it fits that data well and does worse on data it has not seen. James, Witten, Hastie, and Tibshirani describe it this way when they note that a more flexible model needs more parameters and "can lead to a phenomenon known as overfitting the data, which essentially means they follow the errors, or noise, too closely." What you care about is the test error, measured on observations the model never trained on, and not the training error.

Try it by hand. Six training points sit near the line y = x: at x = 0, 1, 2, 3, 4, 5 the observed y values are 0.3, 0.8, 2.4, 2.9, 4.4, 4.9. Fit a straight line by least squares and you get y = 0.167 + 0.98x, with a training mean squared error of 0.064. Now fit a degree-5 polynomial, which has six free coefficients, so it can pass through all six points exactly. Its training error is 0. The flexible model wins on the training data every time.

Test them on five fresh points where the truth is exactly y = x, at x = 0.5, 1.5, 2.5, 3.5, and 4.5. The line predicts 0.66, 1.64, 2.62, 3.60, and 4.58, and its test mean squared error is 0.014. The polynomial predicts −0.12, 1.80, 2.66, 3.46, and 5.29, and its test mean squared error is 0.226, about 16 times larger. It swung up and down to hit every noisy point, and between the points it is wrong. These numbers are invented, and the arithmetic was done exactly.

So how do you avoid it? Hold data back. The Elements of Statistical Learning describes the data-rich approach: split the data into a training set to fit models, a validation set to estimate prediction error for choosing among them, and a test set to assess the final chosen model. Its warning is the part people skip: "Ideally, the test set should be kept in a 'vault,' and be brought out only at the end of the data analysis." If you use the test set repeatedly and keep the model with the smallest test error, "the test set error of the final chosen model will underestimate the true test error, sometimes substantially."

The trap: checking the final test set again and again while tuning, as if looking were free. Every look that changes a decision makes that set part of your training. Tune on the validation set and open the test set once.

Prof Rod's rule: the test set is for the final answer only. If you peeked, say so, and treat the number as optimistic.

James, Witten, Hastie, and Tibshirani, An Introduction to Statistical Learning, 2nd ed., Section 2.1 (p. 22) and Section 2.2 (p. 30); Hastie, Tibshirani, and Friedman, The Elements of Statistical Learning, 2nd ed., Section 7.2 (p. 222)