Unit 9, lesson 70

Validation, Overfitting and Honest Prediction

How to judge predictions on data not used to fit them, with training and test data, loss functions and cross-validation, and how overfitting, data leakage and distribution shift can make a score misleading.

  • Video 70
  • Logistic Regression and Validation

A curve fitted to five points can pass through every one of them, so its error on those points is zero. Does that mean it will predict the next case well? The answer has to come from cases that played no part in building the model, scored in a way that matches the cost of a wrong prediction. This lesson settles which data may be used for fitting, choosing and judging a model, how cross-validation reuses limited data, and which shortcuts make a score look better than the model really is.

Key terms

Training data and test data

Definition In a prediction problem, training data are the observations used to build the model. Their outcomes and predictor values determine the fitted coefficients and anything else learned in fitting, such as imputation values or scaling constants. Test data are observations set aside before any of these decisions and used to assess the final procedure. Neither their outcomes nor summaries of their predictor values play any part in fitting, preprocessing or model choice. When a model has to be chosen, the choice uses validation data or cross-validation within the development data, which is everything except the test set. A split assigns each observation, or each linked group of observations, to one role before any outcome is used to choose a model, and it must match the prediction task. To predict for new people, all records of a person go to the same side. To forecast a later period, the test period comes after the training period. A random split of individual rows suits cases that behave like independent draws from the population of interest. Once test results have influenced the choice of model, those cases have served as validation data, and an untouched final assessment needs fresh test data.

In plain words The training data are the study material and the test data are an exam set aside before studying begins. The exam is fair only if its questions resemble the ones that will come later and nobody used them while studying. A test score describes performance on cases like the test cases, so say which population and period they represent.

Example The running example has five training points with predictor values x=0,1,2,3,4x = 0, 1, 2, 3, 4 and outcomes y=1,2,1,4,5y = 1, 2, 1, 4, 5, and four test points set aside before fitting, at x=0.5,1.5,2.5,3.5x = 0.5, 1.5, 2.5, 3.5 with outcomes 1.5,2.5,3.5,4.51.5, 2.5, 3.5, 4.5. The data are constructed for illustration, and the overfitting card compares two models on them. For a different situation, suppose a study records 8 weekly visits for each of 50 participants and the model will be used on new participants. A random split of the 400 rows into 320 for training and 80 for testing would almost certainly put visits of most participants on both sides, so the test score would partly measure how well the model recognizes people it has already seen. Assigning whole participants, for example 40 to training and 10 to testing, matches the task.

Loss function

Definition A loss function assigns to an observed outcome yy and a prediction y^\hat{y} a number L(y,y^)≥0L(y, \hat{y}) \ge 0 that measures the cost of the miss. A set of mm predictions is scored by its average loss over the evaluated cases. With prediction error ei=yi−y^ie_i = y_i - \hat{y}_i, the common scores for a numerical outcome are

MSE⁡=1m∑i=1mei2,RMSE⁡=MSE⁡,MAE⁡=1m∑i=1m∣ei∣.\begin{gathered} \operatorname{MSE} = \frac{1}{m} \sum_{i=1}^{m} e_i^2, \\[0.4em] \operatorname{RMSE} = \sqrt{\operatorname{MSE}}, \\[0.4em] \operatorname{MAE} = \frac{1}{m} \sum_{i=1}^{m} \lvert e_i \rvert . \end{gathered}

The RMSE and the MAE are in the units of the outcome, and the MSE is in squared units. For a binary outcome coded yi=0y_i = 0 or 11 and a forecast probability pip_i of the event yi=1y_i = 1, the Brier score is the average of (pi−yi)2(p_i - y_i)^2. The divisor is mm, the number of evaluated predictions, because the score is an average loss and not an estimate of an error variance. This average over cases is also different from the mean squared error of an estimator, which is an expectation. Competing models should be scored with the same loss on the same evaluation cases, next to a simple baseline such as predicting the training mean.

In plain words The loss decides what counts as a bad miss. Squared error charges a miss of 2 four times as much as a miss of 1, while absolute error charges it twice as much, so large misses count relatively more under MSE than under MAE. Choose the loss that matches the cost of mistakes in the application, and report its units and the cases it was computed on.

Example The least-squares line for the five training points is y^=0.6+x\hat{y} = 0.6 + x. Its predictions 0.6,1.6,2.6,3.6,4.60.6, 1.6, 2.6, 3.6, 4.6 leave errors 0.4,0.4,−1.6,0.4,0.40.4, 0.4, -1.6, 0.4, 0.4, whose squares add to 3.23.2. The training MSE is 3.2/5=0.643.2/5 = 0.64 and the training RMSE is 0.80.8 in the units of yy. Dividing by n−2=3n - 2 = 3 instead gives 3.2/3≈1.073.2/3 \approx 1.07, the squared residual standard deviation used for inference about the slope, which answers a different question. For probabilities, take outcomes 0,0,1,10, 0, 1, 1 with forecasts 0.1,0.4,0.6,0.90.1, 0.4, 0.6, 0.9. The squared errors are 0.01,0.16,0.16,0.010.01, 0.16, 0.16, 0.01, so the Brier score is 0.34/4=0.0850.34/4 = 0.085, against 0.250.25 for the baseline that forecasts 0.50.5 every time. All four cases are classified correctly at the threshold 0.50.5, yet the Brier score still separates the forecast 0.90.9 for an event, with loss 0.010.01, from the forecast 0.60.6, with loss 0.160.16.

Overfitting

Definition A fitting or model-selection procedure overfits when it adapts to features of the training sample that do not hold in the population where predictions will be made, such as chance patterns in the noise, so that it predicts new cases worse than a less flexible procedure would. Training error alone is not enough to detect it. For least squares, adding a predictor never increases the training residual sum of squares, and the least-squares polynomial of degree n−1n - 1 passes exactly through nn points with distinct xx values. So the fit with the smallest training error tends to look better on the training data than it will on new data. In a single split the held-out error can still come out larger or smaller than the training error, since it depends on which cases land in each set.

In plain words A flexible model can follow every wiggle of the training sample, including wiggles that are just noise. That noise does not repeat in new data, so the closest fit to past data can predict new data worse. This does not mean simpler always wins. When the true relationship is curved, a straight line misses the curve, which is called underfitting, and a more flexible model can predict better. How much flexibility helps depends on the relationship, the noise and the amount of data.

Example For the five training points, the quartic

y^=1+7x−9.5x2+4x3−0.5x4\begin{aligned} \hat{y} &= 1 + 7x - 9.5x^2 \\[0.4em] &\quad + 4x^3 - 0.5x^4 \end{aligned}

passes through every point, so its training MSE is 00, against 0.640.64 for the line y^=0.6+x\hat{y} = 0.6 + x. On the four test points the order reverses.

Test xxOutcome yyLineQuartic
0.50.51.51.51.11.12.593752.59375
1.51.52.52.52.12.11.093751.09375
2.52.53.53.53.13.12.093752.09375
3.53.54.54.54.14.15.593755.59375

Every error of the line is 0.40.4, so its test MSE is 0.160.16. The quartic’s errors are −1.09375-1.09375, 1.406251.40625, 1.406251.40625 and −1.09375-1.09375, and its test MSE is 1625/1024≈1.5871625/1024 \approx 1.587, almost ten times as large. The line’s test MSE is even smaller than its training MSE, so a single split need not show test error above training error. The data are constructed, which makes this an illustration of overfitting and not a proof that lines beat polynomials.

Cross-validation

Definition In kk-fold cross-validation, the nn development observations are divided into k≥2k \ge 2 disjoint folds. For each j=1,…,kj = 1, \dots, k, the whole procedure, including preprocessing and any data-driven variable selection or tuning it contains, is fitted to the other k−1k - 1 folds and used to predict the cases in fold jj. If fold jj has mjm_j cases with average loss Lˉj\bar{L}_j, the cross-validation estimate is the average loss over all held-out predictions,

CV⁡=1n∑j=1kmjLˉj,\operatorname{CV} = \frac{1}{n} \sum_{j=1}^{k} m_j \bar{L}_j ,

which equals the plain mean of the fold scores when the folds have equal size. Leave-one-out cross-validation is the case k=nk = n. Folds follow the same rules as a test split, so linked records stay in one fold. Time-ordered data need forward splits in place of this rotation, with each validation period coming after all the data used to fit its model. The estimate describes the procedure trained on about (k−1)/k(k - 1)/k of the data, not one fixed fitted model. If cross-validation is used to choose among models, the winner’s score tends to be optimistic, so the chosen model is assessed on an untouched test set, or the whole selection procedure is assessed with nested cross-validation. The fold scores share training data and are not independent, so their standard deviation divided by k\sqrt{k} is not automatically a valid standard error.

In plain words In kk-fold cross-validation every observation takes one turn as new data for a model that never saw it. Averaging those honest errors uses all the development data for checking, while no case ever checks a model it helped build. Rotating the roles reduces the luck of a single split, but it does not replace an untouched test set or nested cross-validation when the cross-validated score was itself used to pick the winner.

Example Take the baseline model that predicts the mean of its training outcomes, and the outcomes 22, 44 and 99. With leave-one-out cross-validation, leaving out 22 gives the prediction (4+9)/2=6.5(4 + 9)/2 = 6.5 and the error −4.5-4.5, leaving out 44 gives 5.55.5 and the error −1.5-1.5, and leaving out 99 gives 33 and the error 66. The cross-validated MSE is

20.25+2.25+363=19.5,\frac{20.25 + 2.25 + 36}{3} = 19.5 ,

while the training MSE, with all three cases predicted by their own mean 55, is only 26/3≈8.6726/3 \approx 8.67. With unequal folds the weights matter. Folds of sizes 44, 44 and 22 with MSEs 11, 44 and 11 give (4+16+2)/10=2.2(4 + 16 + 2)/10 = 2.2, not the plain average 22.

Data leakage

Definition Data leakage occurs when information that would not be available at the time and place of a real prediction influences the fitting, preprocessing or selection of a model, or the cases used to evaluate it. Common routes are predictors recorded after the outcome or derived from it, duplicate or linked records on both sides of a split, information from the future in time-ordered data, preprocessing such as imputation, scaling or variable selection learned from validation or test cases, and repeated changes to the model after looking at test results. Leakage typically makes the reported error smaller than the error the procedure will achieve in use. Every quantity learned from data belongs inside the training portion of each split or fold, and it is then applied unchanged to the held-out cases.

In plain words The evaluation has to imitate the moment of prediction. Anything the model could not know at that moment, including test outcomes, summaries of test cases and facts recorded later, has to stay out of every step the score is meant to judge. Check each predictor by asking when it is recorded, not only how well it predicts.

Example A predictor has training values 22, 44 and one missing value, and a held-out person has the value 100100. The declared procedure fills a gap with the training mean, which is (2+4)/2=3(2 + 4)/2 = 3. An analyst who instead averages every observed value, including the held-out one, fills the gap with

2+4+1003=1063≈35.33.\begin{aligned} \frac{2 + 4 + 100}{3} &= \frac{106}{3} \\[0.4em] &\approx 35.33 . \end{aligned}

The held-out case now shapes the training data, so the evaluation no longer tests the declared procedure. In a second case, a model meant to predict at discharge whether a patient returns to the hospital within 30 days uses the number of clinic visits in those 30 days. That count is unknown at discharge, so a high test score describes predictions that cannot be made at the moment the model is meant for.

Distribution shift

Definition Distribution shift occurs when the joint distribution of predictors and outcome in the setting where a model is used differs from the distribution that produced its training and test data. The predictor distribution can change, the frequency of the outcome can change, or the relationship between the outcome and the predictors can change. A test score is evidence about the population, period and measurement process that the test cases represent, and under a shift it need not carry over. Predicting at predictor values outside the range of the training and test data is extrapolation, which no held-out score from inside that range checks.

In plain words A test set from last year’s clinic shows how the model did on last year’s patients. A new clinic, a new measuring device, a new policy or the passing of time can change who arrives and how outcomes relate to predictors. Check performance in the new setting, overall and for relevant groups, and check again when the setting changes. Good predictive performance, even when it holds up, is not a causal explanation.

Example Probability forecasts are calibrated in a population when, among the cases that receive the forecast pp, the proportion with the event equals pp. If every case in a group receives the forecast pp and a fraction ff of them have the event, the group’s average Brier score is

f(1−p)2+(1−f)p2.f(1 - p)^2 + (1 - f)p^2 .

Suppose a model gives a group of cases the forecast 0.100.10, and in the original test data 1010 percent of that group had the event. The forecast is calibrated there, and the score is 0.1⋅0.81+0.9⋅0.01=0.090.1 \cdot 0.81 + 0.9 \cdot 0.01 = 0.09. At a new site, 3030 percent of comparable cases have the event, so the forecast 0.100.10 is too low, and the same formula gives 0.3⋅0.81+0.7⋅0.01=0.250.3 \cdot 0.81 + 0.7 \cdot 0.01 = 0.25. A forecast of 0.300.30 would score 0.210.21 at the new site, but finding that value takes information about outcomes at the new site.

Check yourself

  1. A model predicts delivery times in minutes. On four test deliveries the outcomes are 30, 42, 36 and 52, and the model predicts 34, 40, 36 and 46. A baseline predicts the training mean of 38 minutes for every delivery. Find the test MSE, RMSE and MAE of both, and say which predicts better on these cases.
Show the answer

The model’s errors are −4-4, 22, 00 and 66, with squares 1616, 44, 00 and 3636. Its MSE is 56/4=1456/4 = 14 square minutes, its RMSE is 14≈3.74\sqrt{14} \approx 3.74 minutes and its MAE is 12/4=312/4 = 3 minutes.

The baseline’s errors are −8-8, 44, −2-2 and 1414, with squares 6464, 1616, 44 and 196196. Its MSE is 280/4=70280/4 = 70 square minutes, its RMSE is 70≈8.37\sqrt{70} \approx 8.37 minutes and its MAE is 28/4=728/4 = 7 minutes.

The model has the smaller loss under all three scores on these cases. Four test cases are very few, so the size of the advantage is uncertain.

  1. A team has 300 records and 2,000 candidate predictors. It fills missing values with column means computed from all 300 records, keeps the 20 predictors most correlated with the outcome in all 300 records, and then runs 5-fold cross-validation of a regression on those 20 predictors. Which steps leak, and how should the workflow be repaired?
Show the answer

Both preprocessing steps leak, because each validation fold helped compute quantities that are then used to predict that same fold. The predictor selection is the more serious problem, since it uses the validation outcomes. Even if all 2,000 predictors were unrelated to the outcome, the 20 chosen ones would be those with the strongest chance correlations in the full data, validation folds included, so cross-validation could report predictive skill that does not exist.

The repair is to run the whole procedure inside each fold. Compute the column means and the correlations from the four training folds only, fit the regression to those folds using the 20 predictors selected there, fill the gaps in the held-out fold with the same means and score it. The selected predictors may differ between folds, which is expected, because cross-validation evaluates the procedure. The final model reruns the same procedure on all the development data.

  1. A study records an outcome at each of 8 weekly visits for 50 participants. How should the data be split if the model will predict outcomes for people who were never in the study? How should they be split if it will predict each current participant’s outcome at the next visit from earlier visits?
Show the answer

For new people, split by participant. Put all visits of a participant on the same side, for example 40 participants for training and 10 for testing, and use folds of whole participants for any cross-validation. A random split of the 400 rows would let the model learn traits of a person from some visits and be scored on other visits of the same person, which is usually easier than predicting a stranger.

For the next visit of current participants, split by time. Fit on earlier weeks and evaluate on later weeks, for example training on weeks 1 to 6 and testing on weeks 7 and 8, and build every predictor only from information recorded before the visit being predicted. The same participants may appear on both sides here, because the task is about people the model already knows. What must stay out of training is information from the period being predicted.

How this lesson connects