Models and Overfitting

A model flexible enough to fit anything predicts nothing. Polynomial wiggles, cross-validation, logistic regression, and the cold morning the Challenger launched

Models and Overfitting

A model with enough knobs can fit any data perfectly, and then predict the next observation terribly. The tension in all modelling is between fitting what you have seen and predicting what you have not. This lesson lets you overfit on purpose, shows the tool that catches it, and ends with a real dataset where the right chart and the right model mattered.

Wiggly Curves

Drag the degree from 0 to 15 and watch the training error fall all the way while the test error falls and then climbs. Press New noise several times at a high degree and again at degree 1, then play the five folds of cross-validation.

Hidden truth
0.055
training error at this degree
0.919
test error (60 unseen points)
85.160
cross-validated error
3
degree cross-validation picks
3
degree with the lowest test error
Too flexible. The training error is 0.055, below the noise variance, so the curve is fitting the noise. On the test points the error is 0.919. Press New noise a few times and watch the curve thrash about: that is variance.

Teal discs: the training points. Drag one to move it, or tap an empty spot to add one. Hollow circles: test points from the same world, which the fit never sees. Dashed white: the hidden truth. Amber: the fitted polynomial, and in the chart the cross-validated error, which is computed from the training points alone. The white ring in the chart marks the lowest test error and the amber triangle the degree cross-validation picks. During cross-validation each colour is one fold; the greyed fold is held out and the rose bars are its errors. Faint amber curves are fits to earlier noise draws. Tap the chart to choose a degree.

Go deeper:Bias, Variance and Cross-Validation

A polynomial of degree d has d + 1 coefficients to adjust, and every polynomial of degree d is also one of degree d + 1 with the last coefficient set to zero. So the best fit of the higher degree can never be worse on the training points: training error falls with every knob added, and reaches zero when there are as many coefficients as points. For that reason it cannot be used to choose the model. It always votes for the most flexible one.

What matters is the error on a new observation. For squared error at a given x, its average over fresh training sets and fresh noise splits into three parts: expected prediction error = bias² + variance + noise. Bias is how far the average fitted curve sits from the truth, and it is large for a model too stiff to take the right shape. Variance is how much the fitted curve moves from one training set to the next, and it grows with flexibility. The noise term is the variance of the observation itself, and no model removes it. The U in the test-error curve is bias falling while variance rises. More data shrinks the variance of every model, so the bottom of the U moves towards more flexible ones.

Cross-validation estimates prediction error without spending any data on a separate test set. Split the data into k folds; hold each fold out in turn, fit to the rest, and predict the held-out points; average the squared errors. The modern formulation is due to Mervyn Stone (1974) and Seymour Geisser (1975). The amber curve in the chart uses only the training points, yet it tracks the test curve, and its minimum is the degree to choose. A test set must stay out of every choice. Once it has been used to pick a degree it has become training data, and its error is no longer an honest estimate.

One practical matter: the fits here are computed in a basis of Chebyshev polynomials, which are orthogonal on the interval, and solved by an orthogonal (QR) factorisation. The same polynomial written in raw powers 1, x, x², …, x15 has columns so nearly parallel that a degree-15 least-squares fit loses most of its digits to rounding. The basis changes the arithmetic, not the fitted curve.

Junk Predictors

Add junk predictors one at a time and watch the R² gauge click upwards every time, then reveal how the model does on fresh data. Switch to the second world, where nothing is real, and let the computer choose.

World
The tray: tap a predictor to add it to the model of exam marks, and tap again to take it out
8 of 39
predictors in the model
0.619
R² on the 40 students
0.521
adjusted R²
135.4
AIC (lowest so far at 2 predictors)
152.3
BIC (lowest so far at 2 predictors)
hidden
R² on 2,000 fresh students
R² is 0.619 with 8 predictors, and it has not fallen at any step. No junk predictor looks significant at the moment. The interval for hours of revision is ±0.37; with only the two real predictors it would be ±0.34.

Everything here is simulated, and the names are jokes: each column is a set of 40 random numbers, and in the first world the exam mark is 1.0 × hours of revision + 0.6 × hours of sleep + noise, all in standardised units. Teal: R² on the sample, with one tooth on the gauge for every model so far. Violet: adjusted R². White: R² measured on 2,000 fresh cases from the same world, which falls below zero when the model predicts worse than the average would. In the lower chart teal intervals are the real predictors, with a dashed white tick at the true value; grey intervals are junk; rose intervals are junk that excludes zero, starred * for p < 0.05, ** for p < 0.01 and *** for p < 0.001.

Go deeper:R², Its Penalised Cousins, and Stepwise Selection

R² = 1 − RSS/TSS is the share of the variation in the response that the fitted model accounts for, where RSS is the residual sum of squares and TSS the total sum of squares about the mean. Adding a predictor can only lower RSS or leave it alone, since the old model is the new one with a coefficient of zero. So R² never decreases, whatever is added. With an intercept and n − 1 predictors there are as many coefficients as observations, and any data at all can be fitted exactly.

Several criteria charge a price for each parameter. Adjusted R² replaces the two sums of squares with variance estimates, 1 − (RSS/(n − p − 1))/(TSS/(n − 1)) for p predictors, and goes down when a predictor lowers RSS by less than one would expect from noise. Hirotugu Akaike’s information criterion (1973–74), AIC = 2k − 2 ln L for a model with k parameters and maximised likelihood L, estimates relative out-of-sample fit; lower is better. Gideon Schwarz’s BIC (1978) is k ln n − 2 ln L, a heavier penalty once n exceeds 7. Both are large-sample approximations. In the demo, with only 40 observations, they favour small models at first and then break down as the number of predictors approaches n, which is why the fresh data, and not any formula, is called the judge.

Stepwise selection automates the adding of predictors, and its output looks like an ordinary regression table. It is not one. Each p-value in the table is computed as if that predictor had been chosen in advance, when it was in fact the best of thirty. The same data chose the model and then tested it, so the usual p-values and intervals are no longer valid (see also: When Tests Mislead). With thirty useless candidates tested at 5%, at least one gets in about 79% of the time, since 1 − 0.9530 ≈ 0.79.

Cross-validation gives an honest verdict only if the whole procedure is repeated inside each fold: the search is run again on the training folds, and the model it finds is scored on the fold it never saw. In simulations of the second world this kept no predictors about four times in five. It is still an estimate and is sometimes fooled. The other standard remedy is regularisation, such as ridge regression and the lasso, which shrinks coefficients towards zero instead of choosing among them (see also the Machine Learning module).

A Cold Morning

Step through the four views from left to right, then drag the temperature marker from 70 °F down to 31 °F. Run the bootstrap, and tap or drag flights to see how much the conclusion depends on any one of them.

Show
15.04
intercept a (s.e. 7.38)
−0.232
slope b per °F (s.e. 0.108)
× 1.26
odds of distress for each degree colder
p = 0.032
Wald test of b = 0
p = 0.005
likelihood-ratio test of b = 0
> 99.9%
fitted chance of distress at 31 °F
At 31 °F the fitted probability of O-ring distress is 0.9996. Run the bootstrap to see how far the curve could move with a different 23 flights. This is an extrapolation, 22 degrees colder than any flight in the data, and the model’s shape is an assumption there.

Real data: the 23 shuttle flights before Challenger whose boosters were recovered (Dalal, Fowlkes and Hoadley, 1989). Rose discs: flights on which at least one O-ring showed thermal distress. Teal discs: flights with none. Flights that share a temperature are stacked. Amber: the fitted model, with a shaded band between the 2.5th and 97.5th percentiles of the bootstrap curves. White: the temperature marker, which you can drag. The grey region is colder than any flight in the data. The curve is P(distress) = 1/(1 + e−(a + b·t)) with t the temperature in °F. Tap a flight to flip its outcome or drag it sideways to change its temperature.

Go deeper:Challenger and Logistic Regression

On 28 January 1986 the space shuttle Challenger was launched at about 31 °F, far colder than any earlier flight. It broke apart 73 seconds after launch, killing its crew of seven. The Rogers Commission (1986) found that an O-ring seal in a solid rocket booster had failed in the cold, and it criticised the decision process, including the analysis of the temperature data. The statistical re-analysis used here is by Siddhartha Dalal, Edward Fowlkes and Bruce Hoadley (Journal of the American Statistical Association, 1989), and Edward Tufte’s account made the chart that was not drawn famous. Of the 23 earlier flights, 7 showed O-ring distress and 16 did not. All 16 undamaged flights were launched at 66 °F or warmer, and all 4 flights below 65 °F were damaged.

A yes/no outcome needs a model whose predictions stay between 0 and 1. Logistic regression makes the log-odds a straight line in the predictor: ln(p/(1 − p)) = a + b·t, which is the same as p = 1/(1 + e−(a + b·t)). The logistic function goes back to Pierre-François Verhulst’s work on population growth in the nineteenth century; its use for binary outcomes owes much to Joseph Berkson and to David Cox (1958). There is no formula for the best a and b. They are found by maximising the likelihood, here by iteratively reweighted least squares: Newton’s method, in which every step is a weighted least-squares fit. For these data it settles in a handful of steps at a ≈ 15.04 and b ≈ −0.232 per °F.

Coefficients are differences in log-odds, so eb is an odds ratio. Here each degree colder multiplies the odds of distress by about e0.232 ≈ 1.26. The fitted probability is about 0.23 at 70 °F, about 0.94 at 53 °F, the coldest earlier launch, and above 0.99 at 31 °F. The Wald test divides b by its standard error (0.108) and gives p ≈ 0.03; the likelihood-ratio test compares the fitted model with one that ignores temperature and gives p ≈ 0.005. The two tests agree only approximately in a sample this small, and the likelihood-ratio test is usually the more trustworthy of the pair.

The caveats are real. Twenty-three flights is a small sample, and the bootstrap band shows how loosely they pin the curve down. The launch temperature of 31 °F is 22 degrees outside the data, where the S-shape is an assumption and not something the flights can confirm. The yes/no outcome “any distress” is one of several ways the incidents have been coded. And the fitted curve describes an association across flights. What the analysis can fairly say is that the evidence in hand pointed towards more risk in the cold, not less, and that a chart of all 23 flights would have shown it.

Key Takeaways

  • Training error always falls as a model gets more flexible, so it cannot choose the model.
  • Prediction error is bias² + variance + noise; cross-validation estimates it by holding data out.
  • R² never falls when a predictor is added, and a search over many predictors finds “significant” ones in pure noise.
  • Logistic regression models a yes/no outcome through its log-odds; plot all the data, including the cases where nothing happened.

Spot a mistake or have an idea?

Search