Skip to main content

22  Model Validation

“The Scientist must set in order. Science is built up with facts, as a house is with stones. But a collection of facts is no more a science than a heap of stones is a house.” - Henri Poincare

A model can fit the data used to build it very well and still predict new data badly. This chapter covers ways to estimate how a model will do on observations it has not seen: holding out a test set, cross-validation, and a few variations on both. It also covers the ways these estimates go wrong, which in practice is where most of the trouble is.

22.1 Overview of Model Validation

Fitting a model to one dataset can turn up real patterns, but it can also turn up patterns that exist only in that dataset. Validation is how we tell the two apart. The patterns are useful only if they hold up beyond the sample we happened to collect.

NoteValidation estimates future performance

Model fitting asks, “How well does this model describe the data we used?”

Model validation asks, “How well might this model work on new data?”

The two questions can have very different answers. A model can fit the training data closely and do poorly on new observations.

There are three things we usually want validation to tell us.

  1. How accurate the predictions are. We measure the model’s error on data it did not see during fitting. If that error is small, the model has probably picked up a relationship that is there in the population and has not just memorized the training set.

  2. Whether the model is overfit. An overfit model is tailored too closely to the training data. It has learned the noise along with the signal, so it does worse on future data than its training fit suggests.

  3. Whether the model is underfit. An underfit model is too simple to capture the main structure in the data. It does poorly on the training data and on the validation data.

The two basic tools are a train-test split and resampling.

  • A train-test split divides the data into a training set, used to fit the model, and a testing set, used only to assess it.

  • Cross-validation divides the data into several folds, so that each observation is held out once and used for assessment. We first used cross-validation in Chapter 19 to choose the penalty.

22.1.1 Training error is too optimistic

Before getting into the methods, it helps to see why we need them at all. The residuals from a fitted model are smaller, on average, than the errors we would see on new data, because the least squares estimates were chosen to make those particular residuals small. The more parameters the model has, the bigger this gap gets.

Example 22.1  

ExampleTraining error and test error as the model grows

We simulate 35 training points from a curved relationship, \(y = \sin(2\pi x) + \varepsilon\) with \(\sigma = 0.25\), and fit polynomials of degree 1 through 12. We also simulate a large test set of 2,000 points from the same process, so the test error is close to the error we would see on future data.

library(tidyverse)
library(tidymodels)

tidymodels_prefer()

set.seed(3302)

simulate_sine <- function(n, sd = 0.25) {
  tibble(
    x = runif(n),
    y = sin(2 * pi * x) + rnorm(n, sd = sd)
  )
}

sine_train <- simulate_sine(35)
sine_test <- simulate_sine(2000)

degree_errors <- tibble(degree = 1:12) |>
  mutate(
    fit = map(degree, \(d) lm(y ~ poly(x, d), data = sine_train)),
    training = map_dbl(fit, \(f) rmse_vec(sine_train$y, fitted(f))),
    test = map_dbl(fit, \(f) rmse_vec(sine_test$y, predict(f, newdata = sine_test)))
  ) |>
  select(degree, training, test)

degree_errors
# A tibble: 12 × 3
   degree training  test
    <int>    <dbl> <dbl>
 1      1    0.453 0.516
 2      2    0.453 0.515
 3      3    0.231 0.267
 4      4    0.229 0.269
 5      5    0.229 0.270
 6      6    0.229 0.268
 7      7    0.228 0.288
 8      8    0.228 0.308
 9      9    0.228 0.274
10     10    0.227 0.354
11     11    0.212 0.893
12     12    0.212 0.974
degree_errors |>
  pivot_longer(c(training, test), names_to = "data", values_to = "rmse") |>
  ggplot(aes(x = degree, y = rmse, color = data)) +
  geom_line(linewidth = 1) +
  geom_point(size = 2) +
  geom_hline(yintercept = 0.25, linetype = "dashed", color = "gray40") +
  scale_x_continuous(breaks = 1:12) +
  scale_color_manual(values = c(test = "#D55E00", training = "#0072B2")) +
  labs(
    x = "Polynomial degree",
    y = "RMSE",
    color = NULL,
    title = "Training RMSE keeps falling; test RMSE does not",
    subtitle = "Dashed line = the noise standard deviation (0.25)"
  ) +
  theme_minimal()

The training RMSE goes down every time we add a term, and from degree 3 on it is below 0.25, the standard deviation of the noise. No model can predict new data better than the noise allows, so a training RMSE below 0.25 means the model is fitting some of the noise. The test RMSE drops sharply at degree 3, stays roughly flat through degree 6, and then climbs, reaching almost 1 at degree 12, about four times the training RMSE for that model. If we chose the degree by training RMSE we would always pick the biggest model.

22.1.2 Measuring prediction error

We usually look at more than one metric. Suppose the held-out set has \(m\) observations with responses \(y_i\) and predictions \(\hat{y}_i\). The three metrics we use most are

\[ \text{RMSE} = \sqrt{\frac{1}{m}\sum_{i=1}^{m} (y_i - \hat{y}_i)^2}, \qquad \text{MAE} = \frac{1}{m}\sum_{i=1}^{m} |y_i - \hat{y}_i|, \]

and a held-out version of \(R^2\).

NoteDifferent metrics answer different questions
Metric Interpretation Direction
RMSE Typical prediction error in response units, with large errors penalized more heavily. Smaller is better
MAE Average absolute prediction error in response units. Smaller is better
\(R^2\) Proportion of variation in the held-out responses explained by the predictions. Larger is better

RMSE and MAE are in the units of the response, which makes them easier to explain than \(R^2\). “Our predictions are typically off by about 2 mpg” means something to almost anyone.

RMSE squares the errors before averaging, so one large miss can move it a lot. MAE treats every unit of error the same. When RMSE is much larger than MAE, a few observations are being predicted badly.

Example 22.2  

ExampleOne bad prediction

Here are two sets of 20 prediction errors. In the first, every error is \(\pm 1\). The second is the same except that one error is 10.

set.seed(11)

errors_even <- sample(c(-1, 1), 20, replace = TRUE)
errors_one_bad <- errors_even
errors_one_bad[20] <- 10

tibble(
  errors = c("All errors are +/- 1", "One error of 10"),
  rmse = c(sqrt(mean(errors_even^2)), sqrt(mean(errors_one_bad^2))),
  mae = c(mean(abs(errors_even)), mean(abs(errors_one_bad)))
)
# A tibble: 2 × 3
  errors                rmse   mae
  <chr>                <dbl> <dbl>
1 All errors are +/- 1  1     1   
2 One error of 10       2.44  1.45

The one bad error raises the MAE from 1 to 1.45 and the RMSE from 1 to about 2.44. Neither number is wrong. RMSE is the right metric if large errors are much worse than small ones (an underestimated load on a bridge, say). MAE is the better summary if every unit of error costs about the same. Reporting both and looking at the gap between them tells you whether a few cases dominate.

22.1.3 Two versions of \(R^2\)

There is a trap in held-out \(R^2\). On the training data, the two common definitions,

\[ R^2_{\text{trad}} = 1 - \frac{\sum (y_i - \hat{y}_i)^2}{\sum (y_i - \bar{y})^2} \qquad \text{and} \qquad R^2_{\text{cor}} = \left[\text{cor}(y, \hat{y})\right]^2, \]

give the same number for a least squares fit with an intercept. On new data they do not. The squared correlation only measures whether the predictions move with the responses. It ignores whether the predictions are shifted or stretched. The traditional version measures how close the predictions are to the responses and compares that with simply predicting the mean \(\bar{y}\) of the held-out responses. It can be negative, which happens when the model predicts worse than that mean.

In yardstick, rsq() is the squared correlation and rsq_trad() is the traditional version. The metrics() function reports rsq().

Example 22.3  

ExampleHigh correlation, poor predictions

Suppose a model was fit on data from one time period and is now applied to a period where the response runs about 8 units higher. The predictions still track the responses, but they are all too low.

set.seed(2203)

shifted <- tibble(
  truth = rnorm(40, mean = 58, sd = 5),
  estimate = truth - 8 + rnorm(40, sd = 1.5)
)

shifted_metrics <- metric_set(rsq, rsq_trad, rmse, mae)

shifted |>
  shifted_metrics(truth = truth, estimate = estimate)
# A tibble: 4 × 3
  .metric  .estimator .estimate
  <chr>    <chr>          <dbl>
1 rsq      standard       0.942
2 rsq_trad standard      -1.80 
3 rmse     standard       8.19 
4 mae      standard       8.10 
shifted |>
  ggplot(aes(x = truth, y = estimate)) +
  geom_point(alpha = 0.7) +
  geom_abline(slope = 1, intercept = 0, linetype = "dashed") +
  coord_obs_pred() +
  labs(
    x = "Observed response",
    y = "Predicted response",
    title = "The points follow a line, but not the line y = x",
    subtitle = "Dashed line = perfect prediction"
  ) +
  theme_minimal()

The squared correlation is above 0.9. The traditional \(R^2\) is strongly negative, and the RMSE of about 8 tells us the predictions are off by about 8 units. If we had reported only rsq, we would have called this a very good model. A predicted-versus-observed plot with the \(y = x\) line drawn in shows the problem right away, so make that plot whenever you validate a model.

Validation does not prove that a model will work in the future. It gives evidence, gathered in a disciplined way, about whether the model is likely to work on data like the data we have.

22.2 Train-Test Split

The simplest validation method is the train-test split. The data are divided into two subsets:

  • the training set, used to estimate the model, and
  • the testing set, held back and used only to evaluate the fitted model.

The testing set stands in for the new data the model will eventually see.

22.2.1 Why use a train-test split?

If we fit the model to the entire dataset, we can still calculate fitted values and residuals, but as Example 22.1 showed, those residuals understate the error on new data. Holding out a testing set separates fitting from evaluation, so the test error is not biased by the fit.

Common splits are 80/20 and 70/30, with the larger part used for training. There is a tradeoff. A bigger training set gives a better model; a bigger testing set gives a more precise estimate of that model’s error. With large datasets either choice works. With small datasets neither part is very big, and a single split can be misleading (see Example 22.5).

WarningDo not tune on the test set

Use the testing set only at the end, after all the model-building decisions have been made. If we keep changing the model because of how it does on the test set, the test set has become part of the modeling process.

The test-set performance estimate is then too optimistic. This is a form of data leakage, which we return to later in the chapter.

22.2.2 Training, validation, and testing sets

For a simple analysis we often use only a training set and a testing set. When we need to choose between models or tune a setting, it helps to give the data three separate jobs:

Data role Main purpose When it is used
Training set Estimate model parameters. During model fitting.
Validation set Compare candidate models or tune settings. During model selection.
Testing set Estimate final predictive performance. Once, after the model has been chosen.

The testing set does not guide any model-building decision. If we are comparing several candidate models, we compare them with a validation set or with cross-validation on the training data. The testing set is saved for the model we end up choosing.

ExampleExample: Model selection belongs in validation, not testing

Suppose we are choosing among three models:

  • a simple model with one predictor,
  • a model with several predictors, and
  • a model with several predictors plus interactions.

We fit each model to the training data. We use the validation data, or cross-validation on the training data, to decide which model looks best. Only after that choice is made do we evaluate the chosen model on the testing set.

Think of the testing set as a sealed envelope. We open it at the end, once, to get an honest estimate of performance. If we open it, do not like what we see, and go back to change the model, the envelope is no longer sealed.

Example 22.4  

ExampleTrain-test split for the `mtcars` data

We illustrate a train-test split with the mtcars data. Recall from Example 16.2 that log transformations of disp, hp, and wt helped with the linearity assumption.

We split the data, build a recipe, fit a linear regression workflow on the training set, and look at the fitted model.

set.seed(34)

mtcars_split <- initial_split(mtcars, prop = 0.8)
mtcars_train <- training(mtcars_split)
mtcars_test <- testing(mtcars_split)

mtcars_split
<Training/Testing/Total>
<25/7/32>
mtcars_recipe <- recipe(mpg ~ disp + hp + wt, data = mtcars_train) |>
  step_mutate(
    log_disp = log(disp),
    log_hp = log(hp),
    log_wt = log(wt)
  ) |>
  step_rm(disp, hp, wt)

mtcars_model <- linear_reg() |>
  set_engine("lm")

mtcars_workflow <- workflow() |>
  add_recipe(mtcars_recipe) |>
  add_model(mtcars_model)

mtcars_fit <- mtcars_workflow |>
  fit(data = mtcars_train)

mtcars_fit |>
  tidy()
# A tibble: 4 × 5
  term        estimate std.error statistic  p.value
  <chr>          <dbl>     <dbl>     <dbl>    <dbl>
1 (Intercept)    64.1       6.10     10.5  8.04e-10
2 log_disp       -3.31      2.56     -1.29 2.11e- 1
3 log_hp         -3.57      1.94     -1.84 7.96e- 2
4 log_wt         -7.97      3.21     -2.48 2.17e- 2
mtcars_fit |>
  glance()
# A tibble: 1 × 12
  r.squared adj.r.squared sigma statistic  p.value    df logLik   AIC   BIC
      <dbl>         <dbl> <dbl>     <dbl>    <dbl> <dbl>  <dbl> <dbl> <dbl>
1     0.897         0.883  2.22      61.2 1.49e-10     3  -53.3  117.  123.
# ℹ 3 more variables: deviance <dbl>, df.residual <int>, nobs <int>

Now we predict the testing set and calculate the validation metrics. We compute both versions of \(R^2\), along with RMSE and MAE.

validation_metrics <- metric_set(rmse, mae, rsq, rsq_trad)

mtcars_test_predictions <- predict(mtcars_fit, new_data = mtcars_test) |>
  bind_cols(mtcars_test)

mtcars_test_predictions |>
  validation_metrics(truth = mpg, estimate = .pred)
# A tibble: 4 × 3
  .metric  .estimator .estimate
  <chr>    <chr>          <dbl>
1 rmse     standard       1.89 
2 mae      standard       1.72 
3 rsq      standard       0.858
4 rsq_trad standard       0.728

These metrics describe performance on cars that were not used to estimate the coefficients. Notice how few cars that is: the testing set has only 7 observations. Every number in that table is based on 7 prediction errors.

A plot of predicted against observed values for the testing set shows where the errors come from.

mtcars_test_predictions |>
  rownames_to_column("car") |>
  ggplot(aes(x = mpg, y = .pred)) +
  geom_abline(slope = 1, intercept = 0, linetype = "dashed") +
  geom_point(size = 2) +
  geom_text(aes(label = car), size = 3, vjust = -0.8) +
  coord_obs_pred() +
  labs(
    x = "Observed mpg",
    y = "Predicted mpg",
    title = "Test-set predictions for the mtcars model"
  ) +
  theme_minimal()

With this few points, one car can move the test RMSE a good deal, and the plot shows which car that would be.

22.2.3 Interpreting the results

Lower RMSE and MAE and higher \(R^2\) indicate better predictive performance, but read them with the size of the testing set in mind. One split of a small dataset gives a noisy estimate. A model can look better or worse simply because of which observations happened to land in the testing set. The next example shows how much.

Example 22.5  

ExampleHow much does one split vary?

We repeat the 80/20 split of mtcars 500 times at random, refit the same workflow on each training set, and compute the test RMSE each time. Repeating random splits like this is called Monte Carlo cross-validation, and rsample does it with mc_cv().

set.seed(34)

mtcars_mc_splits <- mc_cv(mtcars, prop = 0.8, times = 500)

mtcars_mc_results <- fit_resamples(
  mtcars_workflow,
  resamples = mtcars_mc_splits,
  metrics = metric_set(rmse)
)

mtcars_mc_rmse <- mtcars_mc_results |>
  collect_metrics(summarize = FALSE)

mtcars_mc_rmse |>
  summarize(
    minimum = min(.estimate),
    q10 = quantile(.estimate, 0.10),
    median = median(.estimate),
    q90 = quantile(.estimate, 0.90),
    maximum = max(.estimate)
  )
# A tibble: 1 × 5
  minimum   q10 median   q90 maximum
    <dbl> <dbl>  <dbl> <dbl>   <dbl>
1   0.987  1.50   2.22  2.86    3.80
single_split_rmse <- mtcars_test_predictions |>
  rmse(truth = mpg, estimate = .pred) |>
  pull(.estimate)

mtcars_mc_rmse |>
  ggplot(aes(x = .estimate)) +
  geom_histogram(bins = 30, fill = "gray70", color = "white") +
  geom_vline(xintercept = single_split_rmse, color = "#D55E00", linewidth = 1) +
  labs(
    x = "Test RMSE (mpg)",
    y = "Number of splits",
    title = "Test RMSE from 500 random 80/20 splits of mtcars",
    subtitle = "Orange line = the split used in the previous example"
  ) +
  theme_minimal()

The same model, fit the same way, gives test RMSEs from about 1 mpg to almost 4 mpg depending on the split, and the middle 80% of them run from about 1.5 to 2.9. The split we happened to use in Example 22.4 is near the middle, but we had no way of knowing that from the one split. With only 32 cars, a single split cannot tell us the model’s error to better than a rough range. This is the main reason to use cross-validation on small datasets: averaging over many held-out sets gives a much less noisy estimate than any one of them.

22.2.4 Stratified splits

A plain random split can, by chance, put too many observations from one group in the training set and too few in the testing set. A stratified split avoids that. The data are split separately within each group (each stratum), so the group proportions are about the same in the training and testing sets.

In regression, stratifying is worth doing when a categorical variable is strongly related to the response or when some groups are small.

Example 22.6  

ExampleStratified train-test split by cylinder

The cyl variable records the number of cylinders. We convert it to a factor and stratify the split on it.

mtcars_stratified <- mtcars |>
  mutate(cyl = factor(cyl))

set.seed(34)

mtcars_stratified_split <- initial_split(
  mtcars_stratified,
  prop = 0.8,
  strata = cyl
)

mtcars_stratified_train <- training(mtcars_stratified_split)
mtcars_stratified_test <- testing(mtcars_stratified_split)

bind_rows(
  mtcars_stratified_train |>
    count(cyl) |>
    mutate(split = "Training"),
  mtcars_stratified_test |>
    count(cyl) |>
    mutate(split = "Testing")
) |>
  group_by(split) |>
  mutate(proportion = n / sum(n)) |>
  ungroup()
# A tibble: 6 × 4
  cyl       n split    proportion
  <fct> <int> <chr>         <dbl>
1 4         8 Training      0.333
2 6         5 Training      0.208
3 8        11 Training      0.458
4 4         3 Testing       0.375
5 6         2 Testing       0.25 
6 8         3 Testing       0.375

The proportions do not match exactly, because you cannot put 20% of 7 cars in a testing set, but they are close.

We can also stratify on a numeric variable, including the response. In that case initial_split() cuts the variable into bins at its quartiles and stratifies on the bins. This keeps a few unusually high or low responses from all ending up on one side of the split.

set.seed(34)

mtcars_mpg_split <- initial_split(mtcars, prop = 0.8, strata = mpg)

bind_rows(
  training(mtcars_mpg_split) |> mutate(split = "Training"),
  testing(mtcars_mpg_split) |> mutate(split = "Testing")
) |>
  ggplot(aes(x = mpg, fill = split)) +
  geom_density(alpha = 0.5) +
  scale_fill_manual(values = c(Testing = "#D55E00", Training = "#0072B2")) +
  labs(
    x = "mpg",
    y = "Density",
    fill = NULL,
    title = "Distribution of mpg in a split stratified on mpg"
  ) +
  theme_minimal()

rsample will not make strata that are too small. If a stratum would hold less than 10% of the data (set by the pool argument), it is merged with a neighboring stratum, and you will get a warning when stratification is not possible at all.

22.2.5 Factor levels that appear only in the testing set

A rare category causes a specific failure. If a level of a factor predictor is not in the training set, the model has no coefficient for it and cannot make a prediction for any test observation with that level.

Example 22.7  

ExampleA new level in the testing set

In mtcars, carb (number of carburetors) takes the values 1, 2, 3, 4, 6, and 8, and only one car has 8. Suppose we treat carb as a factor and that car ends up in the testing set.

mtcars_carb <- mtcars |>
  mutate(carb = factor(carb))

mtcars_carb |>
  count(carb)
  carb  n
1    1  7
2    2 10
3    3  3
4    4 10
5    6  1
6    8  1
carb_train <- mtcars_carb |>
  filter(carb != "8")

carb_test <- mtcars_carb |>
  filter(carb == "8")

carb_fit <- lm(mpg ~ wt + carb, data = carb_train)

tryCatch(
  predict(carb_fit, newdata = carb_test),
  error = \(e) conditionMessage(e)
)
[1] "factor carb has new level 8"

lm() drops levels that do not occur in the data it was given, so the fitted model knows nothing about carb = 8, and predict() stops with an error. With a random split this happens or does not happen depending on the seed, which makes it confusing to debug.

There are a few ways to handle it. We can combine rare levels into a larger group before modeling, for example with fct_lump_min(), which lumps every level with fewer than min observations into “Other”. We can use step_other() in a recipe, which does the same thing using only the training data. Or, if the numeric values have meaning, we can keep carb numeric.

mtcars_carb |>
  mutate(carb = fct_lump_min(carb, min = 3, other_level = "6 or 8")) |>
  count(carb)
    carb  n
1      1  7
2      2 10
3      3  3
4      4 10
5 6 or 8  2

Lumping levels by how often they occur does not use the response, so doing it before the split does not leak information about how well the model predicts.

22.3 Cross-Validation

Cross-validation gives a steadier estimate of performance than a single split. Instead of one testing set, it divides the data into several subsets called folds.

For each fold:

  1. A model is trained on all the other folds.
  2. The model is evaluated on the held-out fold.
  3. The process repeats until every fold has been the held-out fold once.

The most common form is k-fold cross-validation, usually with \(k = 5\) or \(k = 10\).

22.3.1 Steps for k-fold cross-validation

  1. Split the data into \(k\) subsets, or folds, of about equal size.
  2. Train the model on \(k - 1\) folds.
  3. Evaluate the model on the remaining fold.
  4. Repeat \(k\) times, holding out a different fold each time.
  5. Average the \(k\) validation metrics to estimate model performance.

Every observation is predicted exactly once, by a model that did not see it. The average in step 5 is also reported with a standard error, the standard deviation of the \(k\) fold metrics divided by \(\sqrt{k}\). That standard error is rough, because the folds share most of their training data and so are not independent, but it is still a useful indication of how precise the average is.

Example 22.8  

ExampleFive-fold cross-validation for the `mtcars` model

Using the workflow from Example 22.4, we estimate performance with five-fold cross-validation on all 32 cars.

set.seed(34)

mtcars_folds <- vfold_cv(mtcars, v = 5)

mtcars_folds
#  5-fold cross-validation 
# A tibble: 5 × 2
  splits         id   
  <list>         <chr>
1 <split [25/7]> Fold1
2 <split [25/7]> Fold2
3 <split [26/6]> Fold3
4 <split [26/6]> Fold4
5 <split [26/6]> Fold5
mtcars_cv_results <- fit_resamples(
  mtcars_workflow,
  resamples = mtcars_folds,
  metrics = metric_set(rmse, mae, rsq)
)

mtcars_cv_results |>
  collect_metrics()
# A tibble: 3 × 6
  .metric .estimator  mean     n std_err .config        
  <chr>   <chr>      <dbl> <int>   <dbl> <chr>          
1 mae     standard   1.75      5  0.174  pre0_mod0_post0
2 rmse    standard   2.11      5  0.167  pre0_mod0_post0
3 rsq     standard   0.836     5  0.0531 pre0_mod0_post0

The summary gives the average across the five folds. We can also look at each fold’s results to see how much they vary.

mtcars_cv_results |>
  collect_metrics(summarize = FALSE)
# A tibble: 15 × 5
   id    .metric .estimator .estimate .config        
   <chr> <chr>   <chr>          <dbl> <chr>          
 1 Fold1 rmse    standard       1.95  pre0_mod0_post0
 2 Fold1 mae     standard       1.38  pre0_mod0_post0
 3 Fold1 rsq     standard       0.922 pre0_mod0_post0
 4 Fold2 rmse    standard       1.95  pre0_mod0_post0
 5 Fold2 mae     standard       1.59  pre0_mod0_post0
 6 Fold2 rsq     standard       0.882 pre0_mod0_post0
 7 Fold3 rmse    standard       2.29  pre0_mod0_post0
 8 Fold3 mae     standard       2.04  pre0_mod0_post0
 9 Fold3 rsq     standard       0.629 pre0_mod0_post0
10 Fold4 rmse    standard       2.66  pre0_mod0_post0
11 Fold4 mae     standard       2.27  pre0_mod0_post0
12 Fold4 rsq     standard       0.898 pre0_mod0_post0
13 Fold5 rmse    standard       1.69  pre0_mod0_post0
14 Fold5 mae     standard       1.45  pre0_mod0_post0
15 Fold5 rsq     standard       0.849 pre0_mod0_post0

When the fold-level metrics vary a lot, the performance estimate depends heavily on the particular split. Here each fold holds only six or seven cars, so the fold-level \(R^2\) values in particular jump around. An \(R^2\) computed from six points is not a very stable number.

Here we ran cross-validation on all of mtcars because we were not keeping a testing set. If a testing set has been set aside, cross-validation should use only the training data (see Example 22.11).

22.3.2 Choosing \(k\)

The choice of \(k\) is a tradeoff. With small \(k\), each model is trained on a smaller part of the data, so it is a little worse than the model we would fit to all the data, and the cross-validation error tends to overstate the final model’s error. With large \(k\), the training sets are nearly the whole dataset, so that bias is small, but the \(k\) fitted models are almost identical and the estimate can be more variable. It also takes \(k\) model fits. Values of 5 and 10 are a reasonable compromise in most regression problems.

With small datasets, watch the size of each fold as well. Ten-fold cross-validation of 32 cars leaves three or four cars per fold, and per-fold \(R^2\) is close to meaningless with three points. RMSE and MAE averaged across folds hold up better than \(R^2\) with small folds.

22.3.3 Repeated cross-validation

Ordinary k-fold cross-validation still depends on one random assignment of observations to folds. Repeated cross-validation runs the k-fold procedure several times with a different random assignment each time and averages over all of them.

It is most helpful when the dataset is small or when the fold-level metrics vary noticeably.

Example 22.9  

ExampleRepeated cross-validation for the `mtcars` model

We repeat five-fold cross-validation ten times, which gives 50 validation assessments.

set.seed(34)

mtcars_repeated_folds <- vfold_cv(mtcars, v = 5, repeats = 10)

mtcars_repeated_cv_results <- fit_resamples(
  mtcars_workflow,
  resamples = mtcars_repeated_folds,
  metrics = metric_set(rmse, rsq)
)

mtcars_repeated_cv_results |>
  collect_metrics()
# A tibble: 2 × 6
  .metric .estimator  mean     n std_err .config        
  <chr>   <chr>      <dbl> <int>   <dbl> <chr>          
1 rmse    standard   2.16     50  0.0837 pre0_mod0_post0
2 rsq     standard   0.880    50  0.0143 pre0_mod0_post0

We can also summarize the spread of the fold-level estimates.

mtcars_repeated_fold_metrics <- mtcars_repeated_cv_results |>
  collect_metrics(summarize = FALSE)

mtcars_repeated_fold_metrics |>
  group_by(.metric) |>
  summarize(
    n_resamples = n(),
    minimum = min(.estimate, na.rm = TRUE),
    median = median(.estimate, na.rm = TRUE),
    maximum = max(.estimate, na.rm = TRUE),
    .groups = "drop"
  )
# A tibble: 2 × 5
  .metric n_resamples minimum median maximum
  <chr>         <int>   <dbl>  <dbl>   <dbl>
1 rmse             50   1.21   2.05    3.76 
2 rsq              50   0.458  0.909   0.986

The plot below shows the five fold RMSEs from each repeat, along with the average for that repeat. The averages vary much less than the individual folds do, which is the point of averaging.

mtcars_repeat_rmse <- mtcars_repeated_fold_metrics |>
  filter(.metric == "rmse")

mtcars_repeat_means <- mtcars_repeat_rmse |>
  group_by(id) |>
  summarize(.estimate = mean(.estimate), .groups = "drop")

mtcars_repeat_rmse |>
  ggplot(aes(x = id, y = .estimate)) +
  geom_point(alpha = 0.5) +
  geom_point(
    data = mtcars_repeat_means,
    color = "#D55E00",
    shape = 18,
    size = 4
  ) +
  labs(
    x = "Repeat",
    y = "RMSE (mpg)",
    title = "Fold-level RMSE across ten repeats of five-fold CV",
    subtitle = "Gray = individual folds; orange = average within each repeat"
  ) +
  theme_minimal() +
  theme(axis.text.x = element_text(angle = 45, hjust = 1))

Repeating cross-validation does not create new information. The data are the same 32 cars. It makes the estimate depend less on one particular random assignment to folds.

22.3.4 Leave-one-out cross-validation (LOOCV)

Leave-one-out cross-validation is k-fold cross-validation with \(k = n\). Each observation is left out once, and the model is fit to the other \(n - 1\).

LOOCV uses nearly all the data for each fit, which is attractive when \(n\) is small, and there is no randomness in how the folds are formed. In general it means fitting the model \(n\) times. For least squares regression, though, we do not have to refit at all. The leave-one-out residual for observation \(i\) is

\[ y_i - \hat{y}_{(i)} = \frac{e_i}{1 - h_{ii}}, \]

where \(e_i\) is the ordinary residual and \(h_{ii}\) is the leverage. Squaring these and adding them up gives the PRESS statistic from our discussion of model selection criteria, so \(\sqrt{\text{PRESS}/n}\) is the LOOCV RMSE.

Example 22.10  

ExampleLOOCV for the `mtcars` model, two ways

We compute the leave-one-out residuals for the mtcars model by refitting 32 times and by the leverage formula.

mtcars_lm <- lm(mpg ~ log(disp) + log(hp) + log(wt), data = mtcars)

loo_refit <- map_dbl(
  seq_len(nrow(mtcars)),
  \(i) {
    fit_without_i <- lm(formula(mtcars_lm), data = mtcars[-i, ])
    mtcars$mpg[i] - predict(fit_without_i, newdata = mtcars[i, ])
  }
)

loo_shortcut <- residuals(mtcars_lm) / (1 - hatvalues(mtcars_lm))

all.equal(unname(loo_refit), unname(loo_shortcut))
[1] TRUE
tibble(
  training_rmse = sqrt(mean(residuals(mtcars_lm)^2)),
  loocv_rmse = sqrt(mean(loo_shortcut^2))
)
# A tibble: 1 × 2
  training_rmse loocv_rmse
          <dbl>      <dbl>
1          1.97       2.25

The two methods agree, and the LOOCV RMSE is larger than the training RMSE, as it should be. The plot compares each car’s ordinary residual with its leave-one-out residual.

loo_comparison <- tibble(
  car = rownames(mtcars),
  ordinary = residuals(mtcars_lm),
  leave_one_out = loo_shortcut,
  leverage = hatvalues(mtcars_lm)
)

loo_comparison |>
  ggplot(aes(x = ordinary, y = leave_one_out)) +
  geom_abline(slope = 1, intercept = 0, linetype = "dashed") +
  geom_point(aes(size = leverage), alpha = 0.6) +
  geom_text(
    data = slice_max(loo_comparison, leverage, n = 3),
    aes(label = car),
    size = 3,
    hjust = 1.1,
    check_overlap = TRUE
  ) +
  labs(
    x = "Ordinary residual",
    y = "Leave-one-out residual",
    size = "Leverage",
    title = "Leave-one-out residuals grow with leverage"
  ) +
  theme_minimal()

Every point is farther from zero than its ordinary residual, by the factor \(1/(1 - h_{ii})\). For low-leverage cars that factor is close to 1 and the points sit near the dashed line. The largest leverage here is 0.32, for the Lotus Europa, so its leave-one-out residual is about 1.47 times its ordinary residual. When a high-leverage car is in the data, it pulls the fitted surface toward itself, so its ordinary residual looks smaller than its real prediction error. When it is left out, the model has to predict it from the other cars.

No car in mtcars has extreme leverage for this model, so the effect is moderate. In a dataset where one point has leverage near 1, its leave-one-out residual can be many times its ordinary residual and can dominate the LOOCV error by itself. This is the same quantity the influence diagnostics in the outliers chapter look at.

fit_resamples() does not accept loo_cv() objects, in part because metrics like \(R^2\) cannot be computed from a held-out set of one observation. For linear regression the leverage formula above is the easy route. For other models, 10-fold cross-validation is usually close enough.

22.3.5 Comparing candidate models with cross-validation

Cross-validation is most often used to choose between models. Each candidate is fit and assessed on the same folds, so the comparison is not affected by some models getting easier folds than others.

Example 22.11  

ExampleChoosing among three `mtcars` models

We compare three models, using cross-validation on the training set from Example 22.4:

  • wt_only: mpg on wt,
  • logs: mpg on the logs of disp, hp, and wt (the model we have been using),
  • all: mpg on all ten other variables.

workflow_set() combines each recipe with the linear regression model, and workflow_map() runs fit_resamples() on each one with the same folds.

wt_only_recipe <- recipe(mpg ~ wt, data = mtcars_train)
all_recipe <- recipe(mpg ~ ., data = mtcars_train)

mtcars_candidates <- workflow_set(
  preproc = list(
    wt_only = wt_only_recipe,
    logs = mtcars_recipe,
    all = all_recipe
  ),
  models = list(lm = mtcars_model)
)

set.seed(34)

mtcars_train_folds <- vfold_cv(mtcars_train, v = 5, repeats = 10)

mtcars_candidate_results <- mtcars_candidates |>
  workflow_map(
    "fit_resamples",
    resamples = mtcars_train_folds,
    metrics = metric_set(rmse, rsq)
  )

mtcars_candidate_results |>
  rank_results(rank_metric = "rmse") |>
  select(wflow_id, .metric, mean, std_err, n)
# A tibble: 6 × 5
  wflow_id   .metric  mean std_err     n
  <chr>      <chr>   <dbl>   <dbl> <int>
1 logs_lm    rmse    2.39   0.0809    50
2 logs_lm    rsq     0.867  0.0242    50
3 wt_only_lm rmse    3.43   0.123     50
4 wt_only_lm rsq     0.743  0.0318    50
5 all_lm     rmse    4.20   0.218     50
6 all_lm     rsq     0.710  0.0248    50

We also compute each model’s training RMSE (the RMSE of its own residuals on the full training set) to plot next to the cross-validation estimate.

candidate_training_rmse <- tibble(
  wflow_id = c("wt_only_lm", "logs_lm", "all_lm"),
  recipe = list(wt_only_recipe, mtcars_recipe, all_recipe)
) |>
  mutate(
    training_rmse = map_dbl(
      recipe,
      \(r) workflow(r, mtcars_model) |>
        fit(mtcars_train) |>
        augment(mtcars_train) |>
        rmse(truth = mpg, estimate = .pred) |>
        pull(.estimate)
    )
  ) |>
  select(wflow_id, training_rmse)

mtcars_candidate_results |>
  collect_metrics() |>
  filter(.metric == "rmse") |>
  left_join(candidate_training_rmse, by = "wflow_id") |>
  mutate(wflow_id = fct_reorder(wflow_id, mean)) |>
  ggplot(aes(y = wflow_id)) +
  geom_errorbar(
    aes(xmin = mean - std_err, xmax = mean + std_err),
    width = 0.2
  ) +
  geom_point(aes(x = mean, color = "Cross-validation"), size = 3) +
  geom_point(aes(x = training_rmse, color = "Training"), size = 3, shape = 17) +
  scale_color_manual(values = c("Cross-validation" = "#D55E00", Training = "#0072B2")) +
  labs(
    x = "RMSE (mpg)",
    y = NULL,
    color = NULL,
    title = "Training RMSE and cross-validated RMSE for three models",
    subtitle = "Bars = one standard error of the CV estimate"
  ) +
  theme_minimal()

The model with all ten predictors has the lowest training RMSE, which is guaranteed, since it contains the other two. Its cross-validated RMSE is the worst of the three, worse even than the model with wt alone, and the gap between its training and CV error is by far the largest. With 25 training cars and 11 coefficients, it has a lot of room to fit noise. The logs model has the lowest CV error.

A common rule for picking among models whose CV errors are close is the one-standard-error rule: find the model with the lowest mean CV error, then choose the simplest model whose mean is within one standard error of it. The idea is that differences smaller than the standard error are not reliably real, and among models we cannot tell apart, the simpler one is easier to interpret and tends to be more stable. Here neither of the other models is within one standard error of the logs model, so the rule picks logs.

Once we have chosen a model, we fit it to the whole training set and evaluate it on the testing set, once. last_fit() does both steps.

mtcars_final <- last_fit(
  mtcars_workflow,
  split = mtcars_split,
  metrics = metric_set(rmse, rsq)
)

mtcars_final |>
  collect_metrics()
# A tibble: 2 × 4
  .metric .estimator .estimate .config        
  <chr>   <chr>          <dbl> <chr>          
1 rmse    standard       1.89  pre0_mod0_post0
2 rsq     standard       0.858 pre0_mod0_post0

These match the testing-set numbers in Example 22.4, because it is the same model and the same split. The difference is in what we did before opening the envelope: the model was chosen using only the training data.

22.4 Data Leakage

Data leakage is any route by which information from the held-out data gets into the fitting process. Leakage almost always makes the validation results look better than the model really is, sometimes by a lot. It is easy to cause and hard to notice, because the code runs without errors and the results look good.

The rule that prevents it: every step that learns anything from the data has to be done inside the resampling loop, using only that iteration’s training data. That includes choosing predictors, estimating transformations, centering and scaling, imputing missing values, and choosing tuning parameters.

Example 22.12  

ExampleScreening predictors before cross-validation

This example is adapted from a well-known demonstration in Hastie, Tibshirani, and Friedman1. We generate 50 observations of a response and 500 predictors, all independent standard normal noise. No predictor has anything to do with the response, so no model can predict it better than the mean does.

The analysis we are going to get wrong:

  1. Find the 10 predictors with the largest absolute correlation with y.
  2. Fit a regression of y on those 10 predictors.
  3. Estimate the prediction error with five-fold cross-validation.

The mistake is doing step 1 once, with all the data, before cross-validation. The correct version repeats step 1 inside every fold, using only that fold’s training data.

set.seed(2201)

n_noise <- 50
p_noise <- 500

noise_data <- matrix(
  rnorm(n_noise * p_noise),
  nrow = n_noise,
  dimnames = list(NULL, paste0("x", 1:p_noise))
) |>
  as_tibble() |>
  mutate(y = rnorm(n_noise))

top_predictors <- function(data, k = 10) {
  correlations <- cor(select(data, -y), data$y)[, 1]
  names(sort(abs(correlations), decreasing = TRUE))[1:k]
}

screened_on_all_data <- top_predictors(noise_data)

noise_folds <- vfold_cv(noise_data, v = 5, repeats = 10)

noise_cv <- noise_folds |>
  mutate(
    errors = map(splits, \(split) {
      train <- analysis(split)
      test <- assessment(split)

      fit_outside <- lm(reformulate(screened_on_all_data, "y"), data = train)
      fit_inside <- lm(reformulate(top_predictors(train), "y"), data = train)

      tibble(
        screening = c("Before CV (leaky)", "Inside each fold (correct)"),
        rmse = c(
          rmse_vec(test$y, predict(fit_outside, newdata = test)),
          rmse_vec(test$y, predict(fit_inside, newdata = test))
        ),
        rsq_trad = c(
          rsq_trad_vec(test$y, predict(fit_outside, newdata = test)),
          rsq_trad_vec(test$y, predict(fit_inside, newdata = test))
        )
      )
    })
  ) |>
  select(id, id2, errors) |>
  unnest(errors)

noise_cv |>
  group_by(screening) |>
  summarize(
    mean_rmse = mean(rmse),
    mean_rsq_trad = mean(rsq_trad),
    .groups = "drop"
  )
# A tibble: 2 × 3
  screening                  mean_rmse mean_rsq_trad
  <chr>                          <dbl>         <dbl>
1 Before CV (leaky)              0.675         0.303
2 Inside each fold (correct)     1.05         -0.510
noise_cv |>
  ggplot(aes(x = screening, y = rmse)) +
  geom_boxplot(fill = "gray85", outlier.shape = NA) +
  geom_jitter(width = 0.15, alpha = 0.4) +
  geom_hline(yintercept = 1, linetype = "dashed", color = "#D55E00") +
  labs(
    x = NULL,
    y = "Held-out RMSE",
    title = "Cross-validated error when the response is pure noise",
    subtitle = "Dashed line = error of predicting with the true mean (sd = 1)"
  ) +
  theme_minimal()

When the screening is done before cross-validation, the model appears to predict pure noise better than the true mean does, with a positive held-out \(R^2\). That is impossible. The screening step looked at every observation, including the ones that would later be held out, and picked predictors that happen to correlate with y in exactly those observations. When the screening is redone inside each fold, the error is above 1, the held-out \(R^2\) is negative, and we get the right answer: these predictors are useless.

The leaky version in this example is not an exotic mistake. Any time we look at the full dataset to decide which predictors, transformations, or interactions to include, and then validate the result on part of that same data, we have done a milder version of it. The stepwise and best subsets procedures from earlier chapters are selection steps too, and a validation estimate is honest only if the selection was repeated within each fold or done without the held-out data.

22.4.1 Preprocessing and recipes

Recipes help here. When a workflow containing a recipe is passed to fit_resamples(), the recipe is re-estimated on each fold’s training data. A step_normalize() computes the mean and standard deviation from the training part of the fold only, and then applies those values to the held-out part. If we instead scaled the whole dataset first and then cross-validated, each fold’s held-out data would have influenced the scaling. For centering and scaling the effect is usually small. For steps that use the response, such as screening predictors by their correlation with it, the effect can be as large as in Example 22.12.

22.4.2 Duplicates and near-duplicates

If the same observation appears twice in the data, a random split can put one copy in the training set and the other in the testing set. The model then gets credit for “predicting” a point it has already seen. The same thing happens, less obviously, with near-duplicates: the same house sold twice in one year, two measurements of one sample run on the same machine, or a record entered twice with a typo. Check for duplicates with distinct() or count() before splitting, and decide whether they are separate observations or the same one.

22.5 Data with Structure: Groups and Time

Ordinary cross-validation assigns observations to folds at random, which assumes the observations are exchangeable: any one could be swapped with any other. Two common kinds of data break this assumption, and in both the usual cross-validation is too optimistic.

22.5.1 Grouped data

Many datasets have several rows per unit: repeated measurements on the same patient, several students from each school, several years of data for each county. Observations from the same unit are usually more alike than observations from different units. If the model will be used to predict new units (a new patient, a new school), then the validation has to hold out whole units. Otherwise rows from the same unit appear on both sides of the split, and the model is rewarded for recognizing units it has already seen.

group_vfold_cv() assigns whole groups to folds.

Example 22.13  

ExampleGrouped cross-validation with repeated measurements

We simulate 30 subjects with five measurements each. Each subject has one value of a predictor x and a subject effect \(u\) that shifts all five of that subject’s responses. The true relationship between x and y is a straight line:

\[ y_{ij} = 3 + 0.5\,x_i + u_i + \varepsilon_{ij}, \qquad u_i \sim N(0, 2^2), \quad \varepsilon_{ij} \sim N(0, 0.5^2). \]

We use cross-validation to choose the degree of a polynomial in x, once with ordinary five-fold CV and once with five-fold CV that keeps each subject’s rows together.

set.seed(2202)

subjects <- tibble(
  subject = factor(1:30),
  x = runif(30, 0, 10),
  u = rnorm(30, sd = 2)
)

grouped_data <- subjects |>
  slice(rep(1:n(), each = 5)) |>
  mutate(y = 3 + 0.5 * x + u + rnorm(n(), sd = 0.5))

poly_recipe <- recipe(y ~ x, data = grouped_data) |>
  step_poly(x, degree = tune())

poly_workflow <- workflow(poly_recipe, linear_reg())

degree_grid <- tibble(degree = 1:10)

set.seed(2202)
ordinary_folds <- vfold_cv(grouped_data, v = 5)

set.seed(2202)
subject_folds <- group_vfold_cv(grouped_data, group = subject, v = 5)

grouped_cv_results <- bind_rows(
  tune_grid(poly_workflow, resamples = ordinary_folds, grid = degree_grid,
            metrics = metric_set(rmse)) |>
    collect_metrics() |>
    mutate(cv = "Ordinary 5-fold CV"),
  tune_grid(poly_workflow, resamples = subject_folds, grid = degree_grid,
            metrics = metric_set(rmse)) |>
    collect_metrics() |>
    mutate(cv = "Grouped 5-fold CV (by subject)")
)

grouped_cv_results |>
  select(cv, degree, mean, std_err)
# A tibble: 20 × 4
   cv                             degree  mean std_err
   <chr>                           <int> <dbl>   <dbl>
 1 Ordinary 5-fold CV                  1  1.85  0.0816
 2 Ordinary 5-fold CV                  2  1.86  0.0750
 3 Ordinary 5-fold CV                  3  1.81  0.0731
 4 Ordinary 5-fold CV                  4  1.79  0.0516
 5 Ordinary 5-fold CV                  5  1.78  0.0394
 6 Ordinary 5-fold CV                  6  1.77  0.0352
 7 Ordinary 5-fold CV                  7  1.78  0.0343
 8 Ordinary 5-fold CV                  8  1.66  0.0258
 9 Ordinary 5-fold CV                  9  1.65  0.0198
10 Ordinary 5-fold CV                 10  1.66  0.0148
11 Grouped 5-fold CV (by subject)      1  1.90  0.251 
12 Grouped 5-fold CV (by subject)      2  1.99  0.248 
13 Grouped 5-fold CV (by subject)      3  2.02  0.328 
14 Grouped 5-fold CV (by subject)      4  2.34  0.153 
15 Grouped 5-fold CV (by subject)      5  2.48  0.169 
16 Grouped 5-fold CV (by subject)      6  3.14  0.630 
17 Grouped 5-fold CV (by subject)      7  3.32  0.774 
18 Grouped 5-fold CV (by subject)      8  2.26  0.177 
19 Grouped 5-fold CV (by subject)      9  3.38  0.891 
20 Grouped 5-fold CV (by subject)     10  5.36  1.94  
grouped_cv_results |>
  ggplot(aes(x = degree, y = mean, color = cv)) +
  geom_line(linewidth = 1) +
  geom_point(size = 2) +
  scale_x_continuous(breaks = 1:10) +
  scale_color_manual(values = c("#D55E00", "#0072B2")) +
  labs(
    x = "Polynomial degree",
    y = "Cross-validated RMSE",
    color = NULL,
    title = "Ordinary CV rewards fitting the subjects; grouped CV does not"
  ) +
  theme_minimal() +
  theme(legend.position = "bottom")

Under ordinary CV, the other four rows of a held-out subject are usually in the training set, so a wiggly polynomial can bend toward that subject’s mean and predict the held-out row well. The ordinary CV error drifts down as the degree increases and would lead us to a degree 9 polynomial, with an estimated RMSE of about 1.65. Under grouped CV, each subject is predicted from the other subjects only, which is the situation the model will face with a new subject. Its error is smallest for the straight line, which is the true model, and it rises quickly with the degree. Even for the straight line, the grouped estimate is larger than any of the ordinary ones. For a new subject the prediction error includes the subject effect, which x cannot predict, so the true RMSE is about \(\sqrt{2^2 + 0.5^2} \approx 2.06\). Ordinary CV would have understated that by about 20% and chosen the wrong model.

The decision about grouping depends on how the model will be used. If we wanted to predict the next measurement on a subject already in the data, ordinary CV would be closer to the right question. If we want to predict for new subjects, we hold out subjects.

22.5.2 Time-ordered data

When the data are collected over time and the model will be used to predict the future, a random split lets the model train on observations from after the ones it is tested on. Neighboring time points are usually similar, so predicting a held-out month from the months on either side of it is much easier than predicting next month from the past.

For time-ordered data, the testing set should come after the training set. initial_time_split() keeps the first part of the data (in its current order) for training and the last part for testing, and rolling_origin() and sliding_period() give resampling versions of the same idea.

Example 22.14  

ExampleRandom split versus time split

We simulate 10 years of monthly data with an upward trend, a seasonal cycle, and some noise, and fit a degree 6 polynomial in time. We compare the test error from a random 80/20 split with the error from training on the first 8 years and testing on the last 2.

set.seed(2204)

monthly <- tibble(month = 1:120) |>
  mutate(
    y = 20 + 0.08 * month + 2 * sin(2 * pi * month / 12) +
      as.numeric(arima.sim(list(ar = 0.6), n = 120, sd = 0.8))
  )

time_workflow <- workflow(
  recipe(y ~ month, data = monthly) |> step_poly(month, degree = 6),
  linear_reg()
)

set.seed(2204)
random_split <- initial_split(monthly, prop = 0.8)
time_split <- initial_time_split(monthly, prop = 0.8)

split_predictions <- function(split, label) {
  fitted_workflow <- fit(time_workflow, training(split))

  all_months <- bind_rows(
    training(split) |> mutate(role = "Training"),
    testing(split) |> mutate(role = "Testing")
  )

  all_months |>
    mutate(
      .pred = predict(fitted_workflow, new_data = all_months)$.pred,
      split_type = label
    )
}

time_comparison <- bind_rows(
  split_predictions(random_split, "Random 80/20 split"),
  split_predictions(time_split, "First 8 years / last 2 years")
)

time_comparison |>
  filter(role == "Testing") |>
  group_by(split_type) |>
  rmse(truth = y, estimate = .pred)
# A tibble: 2 × 4
  split_type                   .metric .estimator .estimate
  <chr>                        <chr>   <chr>          <dbl>
1 First 8 years / last 2 years rmse    standard       32.3 
2 Random 80/20 split           rmse    standard        1.67
time_comparison |>
  arrange(month) |>
  ggplot(aes(x = month)) +
  geom_point(aes(y = y, color = role), alpha = 0.8) +
  geom_line(aes(y = .pred), linewidth = 0.8) +
  facet_wrap(~ split_type, ncol = 1) +
  scale_color_manual(values = c(Testing = "#D55E00", Training = "#0072B2")) +
  coord_cartesian(ylim = c(10, 40)) +
  labs(
    x = "Month",
    y = "y",
    color = NULL,
    title = "The same model validated two ways",
    subtitle = "Black line = fitted degree 6 polynomial"
  ) +
  theme_minimal() +
  theme(legend.position = "bottom")

With the random split, the testing months are scattered through the series and surrounded by training months, so the model only has to interpolate. With the time split, the model has to extrapolate past the end of its training data, and the polynomial heads off in whatever direction its highest-degree terms send it. If this model were going to be used for forecasting, only the second number would be relevant.

22.5.3 Extrapolation

The time example is a special case of a more general problem. Validation tells us how well a model predicts new observations that look like the ones we have. Neither a train-test split nor cross-validation says anything about predictions for predictor values outside the range of the data, because no held-out observation is out there.

Example 22.15  

ExampleTwo models that agree in range and disagree outside it

The true relationship is mildly curved. All of the data have \(x\) between 0 and 5. We fit a straight line and a quadratic, compare them by cross-validation, and then see what they predict out to \(x = 10\).

set.seed(2205)

extrap_data <- tibble(x = runif(60, 0, 5)) |>
  mutate(y = 2 + 1.5 * x - 0.06 * x^2 + rnorm(60, sd = 0.6))

set.seed(2205)
extrap_folds <- vfold_cv(extrap_data, v = 10)

extrap_models <- list(
  "Straight line" = y ~ x,
  "Quadratic" = y ~ x + I(x^2)
)

imap(
  extrap_models,
  \(f, name) fit_resamples(workflow(f, linear_reg()), extrap_folds,
                           metrics = metric_set(rmse)) |>
    collect_metrics() |>
    mutate(model = name)
) |>
  list_rbind() |>
  select(model, .metric, mean, std_err)
# A tibble: 2 × 4
  model         .metric  mean std_err
  <chr>         <chr>   <dbl>   <dbl>
1 Straight line rmse    0.598  0.0387
2 Quadratic     rmse    0.595  0.0398
extrap_grid <- tibble(x = seq(0, 10, length.out = 200))

extrap_curves <- imap(
  extrap_models,
  \(f, name) extrap_grid |>
    mutate(
      .pred = predict(lm(f, data = extrap_data), newdata = extrap_grid),
      model = name
    )
) |>
  list_rbind() |>
  bind_rows(
    extrap_grid |>
      mutate(.pred = 2 + 1.5 * x - 0.06 * x^2, model = "True mean")
  )

ggplot() +
  annotate("rect", xmin = 5, xmax = 10, ymin = -Inf, ymax = Inf,
           fill = "gray90") +
  annotate("text", x = 7.5, y = 1, label = "No data here") +
  geom_point(data = extrap_data, aes(x = x, y = y), alpha = 0.6) +
  geom_line(data = extrap_curves,
            aes(x = x, y = .pred, color = model, linetype = model),
            linewidth = 1) +
  scale_color_manual(values = c(Quadratic = "#0072B2", "Straight line" = "#D55E00",
                                "True mean" = "gray30")) +
  scale_linetype_manual(values = c(Quadratic = "solid", "Straight line" = "solid",
                                   "True mean" = "dashed")) +
  labs(
    x = "x",
    y = "y",
    color = NULL,
    linetype = NULL,
    title = "Cross-validation cannot see past the edge of the data"
  ) +
  theme_minimal() +
  theme(legend.position = "bottom")

The two models have nearly the same cross-validated RMSE, and inside the range of the data their curves are almost on top of each other. Past \(x = 5\) they separate, and by \(x = 10\) they disagree by a large amount. Nothing in the validation results could have told us which one to trust out there. If predictions are needed outside the observed range, the justification has to come from knowledge of the subject (or from collecting data out there), not from validation.

With several predictors, extrapolation is harder to spot. A new observation can have every predictor inside its observed range and still be far from the data, because the combination of values is unusual. The leverage of a new point, \(h_{\text{new}} = \mathbf{x}_{\text{new}}^\top (\mathbf{X}^\top\mathbf{X})^{-1}\mathbf{x}_{\text{new}}\), measures this: values larger than the largest leverage in the training data mean the point is outside the region the model was fit on.

22.6 Comparing Models on Different Response Scales

When we transform the response, the error metrics are on the transformed scale. An RMSE of 0.1 for a model of \(\log(y)\) and an RMSE of 2 for a model of \(y\) cannot be compared, because they are not in the same units. To compare the two, back-transform the predictions to the original scale first, and compute the metrics there.

Example 22.16  

ExampleComparing a log-response model with an untransformed model

We fit mpg and log(mpg) on the logs of disp, hp, and wt, using the same repeated folds for both, and save the held-out predictions.

mtcars_logs <- mtcars |>
  mutate(
    log_mpg = log(mpg),
    log_disp = log(disp),
    log_hp = log(hp),
    log_wt = log(wt)
  )

set.seed(34)
mtcars_log_folds <- vfold_cv(mtcars_logs, v = 5, repeats = 10)

keep_predictions <- control_resamples(save_pred = TRUE)

mpg_scale_results <- fit_resamples(
  workflow(mpg ~ log_disp + log_hp + log_wt, linear_reg()),
  resamples = mtcars_log_folds,
  metrics = metric_set(rmse),
  control = keep_predictions
)

log_scale_results <- fit_resamples(
  workflow(log_mpg ~ log_disp + log_hp + log_wt, linear_reg()),
  resamples = mtcars_log_folds,
  metrics = metric_set(rmse),
  control = keep_predictions
)

bind_rows(
  collect_metrics(mpg_scale_results) |> mutate(model = "mpg"),
  collect_metrics(log_scale_results) |> mutate(model = "log(mpg)")
) |>
  select(model, .metric, mean, std_err)
# A tibble: 2 × 4
  model    .metric  mean std_err
  <chr>    <chr>   <dbl>   <dbl>
1 mpg      rmse    2.16  0.0837 
2 log(mpg) rmse    0.109 0.00434

The RMSE for the log model is tiny, but that is because it is measured in log units. To compare, we back-transform the held-out predictions with exp() and compute the RMSE in mpg for each fold.

log_scale_results |>
  collect_predictions() |>
  mutate(
    mpg = exp(log_mpg),
    mpg_pred = exp(.pred)
  ) |>
  group_by(id, id2) |>
  summarize(rmse = rmse_vec(mpg, mpg_pred), .groups = "drop") |>
  summarize(mean = mean(rmse), std_err = sd(rmse) / sqrt(n()))
# A tibble: 1 × 2
   mean std_err
  <dbl>   <dbl>
1  2.18  0.0856

On the mpg scale, the two models are close. Two cautions with back-transformation: exp() of a predicted mean log is an estimate of the median of \(y\) given the predictors, not the mean, so the back-transformed predictions run a little low. And any model fit on a transformed scale is optimized for errors on that scale, which is not the same as being optimized for errors in mpg.

22.7 Assessing Overfitting and Underfitting

One of the main uses of validation is deciding whether a model is about the right size: complex enough to capture the structure in the data and simple enough that it is not fitting noise.

NoteTraining performance versus validation performance
Pattern Likely issue
Good training performance and poor validation performance Overfitting
Poor training performance and poor validation performance Underfitting
Similar and acceptable training and validation performance More likely to generalize

Validation metrics tell us the most when we compare them with training metrics. The gap between the two often says more than either number does alone.

22.7.1 Understanding overfitting

Overfitting happens when a model is too complex for the amount of information in the data. It fits the training data closely, capturing random fluctuations along with the underlying signal.

Overfitting is more likely when the model has:

  • many predictors relative to the number of observations,
  • very flexible terms, such as high-degree polynomials,
  • high sensitivity to individual observations, or
  • been tuned repeatedly against the same validation or testing data.

That last item is easy to overlook. Each time we compare models on a validation set and keep the winner, we fit a little more to the particular noise in that validation set. Compare a handful of models and the effect is small. Compare hundreds, and the best validation score will be optimistic even if no single model is overfit.

22.7.2 Detecting overfitting

Validation metrics help detect overfitting:

  • A high training \(R^2\) with a much lower validation \(R^2\) suggests the model fits the training data but does not generalize.
  • A low training RMSE with a much higher validation RMSE says the same thing in response units.
  • Cross-validation results that vary widely across folds suggest the model’s fit depends heavily on which observations were in the training data.

The last sign is an indication of high variance in the fitted model itself. The following simulation shows what that variance looks like.

Example 22.17  

ExampleHow much does the fitted curve change from sample to sample?

We draw 30 different training samples of size 35 from the sine model in Example 22.1 and fit polynomials of degree 1, 3, and 12 to each one. Each thin line is the fit from one sample.

set.seed(2206)

curve_grid <- tibble(x = seq(0.02, 0.98, length.out = 200))

refit_levels <- c("Degree 1", "Degree 3", "Degree 12")

many_fits <- expand_grid(sample_id = 1:30, degree = c(1, 3, 12)) |>
  mutate(train = map(sample_id, \(i) simulate_sine(35))) |>
  mutate(
    curve = map2(train, degree, \(d, k) {
      fit <- lm(y ~ poly(x, k), data = d)
      curve_grid |>
        mutate(.pred = predict(fit, newdata = curve_grid))
    }),
    model = factor(paste("Degree", degree), levels = refit_levels)
  ) |>
  select(sample_id, model, curve) |>
  unnest(curve)

many_fits |>
  ggplot(aes(x = x, y = .pred, group = sample_id)) +
  geom_line(alpha = 0.3, color = "#0072B2") +
  geom_function(
    fun = \(x) sin(2 * pi * x),
    inherit.aes = FALSE,
    linetype = "dashed",
    linewidth = 1
  ) +
  facet_wrap(~ model) +
  coord_cartesian(ylim = c(-2, 2)) +
  scale_x_continuous(breaks = c(0, 0.5, 1)) +
  labs(
    x = "x",
    y = "Fitted value",
    title = "Fitted curves from 30 different training samples",
    subtitle = "Dashed line = true mean relationship"
  ) +
  theme_minimal()

The straight lines barely change from sample to sample, but they are all wrong in the same way. The degree 3 fits vary some but cluster around the truth. The degree 12 fits are centered near the truth in the middle of the range and are all over the place near the edges, where a high-degree polynomial is constrained by only a few points. A model with this much sample-to-sample variation will give a different answer for every training set, and the predictions for any one new point are unreliable.

The wild behavior near the edges is a known property of high-degree polynomials, and it is one more reason to be cautious about extrapolating with them (see Example 22.14).

22.7.3 Addressing overfitting

Several things can reduce overfitting:

  1. Reduce the number of predictors to those most relevant to the response, choosing them inside the validation loop as discussed above.
  2. Use regularization. Ridge regression and the lasso, from Chapter 19, shrink the coefficients and reduce the variance of the fit.
  3. Use cross-validation to check whether the performance is stable across different partitions of the data.
  4. Use a simpler model structure. Remove interactions, nonlinear terms, or transformations that the data do not support.
  5. Collect more data, if that is possible. A model that overfits 30 observations may be fine with 300.

22.7.4 Understanding underfitting

Underfitting happens when a model is too simple to capture the main patterns in the data. It misses relationships between the predictors and response and does poorly on both training and testing data.

Underfitting usually comes from:

  • a model that is too constrained,
  • a linear model for a strongly nonlinear relationship,
  • missing predictors, or
  • transformations or interactions that should have been included and were not.

22.7.5 Detecting underfitting

The signs of underfitting are:

  • low \(R^2\) on both the training and validation sets,
  • high RMSE on both, with a small gap between them, and
  • residual plots that show systematic patterns.

An overfit model looks good on the training data and bad on new data. An underfit model looks bad on both.

One complication: a low \(R^2\) on both sets does not always mean underfitting. If the response is mostly noise relative to the available predictors, the best possible model will still have a low \(R^2\). In Example 22.13, no model of x alone can explain the subject effects, and grouped CV correctly reports a large error for every degree. Residual plots help distinguish the two cases. Systematic patterns in the residuals point to underfitting, and residuals that look like random scatter point to a response that is hard to predict from these predictors.

22.7.6 Addressing underfitting

To improve an underfit model:

  1. Add predictors that help explain the response.
  2. Transform variables or create new ones that capture the relationship better.
  3. Add flexibility, such as polynomial terms, interactions, or a different kind of model, when the data support it.
  4. Go back to the residual plots and look for patterns the current model misses.

22.7.7 Bias-variance tradeoff

The balance between overfitting and underfitting is often described as the bias-variance tradeoff.

  • Bias is error caused by assumptions that are too simple. High bias goes with underfitting: the degree 1 fits in Example 22.17 are consistently wrong.
  • Variance is error caused by sensitivity to the particular training sample. High variance goes with overfitting: the degree 12 fits in Example 22.17 change a lot from sample to sample.

For squared error, the expected prediction error at a point splits exactly into three parts: the irreducible noise variance, the squared bias, and the variance of the fitted value. Making the model more flexible lowers the bias and raises the variance. The aim is a model flexible enough to capture the important structure and stable enough to give similar answers on similar data. That is usually somewhere in between the simplest and most complex models we could fit.

Example 22.18  

ExampleVisualizing the bias-variance tradeoff

The following plot shows three polynomial models fit to one noisy sample. The dashed curve is the true mean relationship used to generate the data.

set.seed(3302)

bias_variance_train <- tibble(
  x = sort(runif(35)),
  y = sin(2 * pi * x) + rnorm(35, sd = 0.25)
)

bias_variance_grid <- tibble(
  x = seq(0, 1, length.out = 200)
)

bias_variance_truth <- bias_variance_grid |>
  mutate(truth = sin(2 * pi * x))

bias_variance_model_levels <- c(
  "Too simple: degree 1",
  "Reasonable flexibility: degree 3",
  "Too flexible: degree 12"
)

bias_variance_fits <- tibble(
  degree = c(1, 3, 12),
  model = factor(
    bias_variance_model_levels,
    levels = bias_variance_model_levels
  )
) |>
  mutate(
    fit = map(
      degree,
      \(degree_value) lm(
        y ~ poly(x, degree_value),
        data = bias_variance_train
      )
    ),
    predictions = map(
      fit,
      \(model_fit) bias_variance_grid |>
        mutate(predicted = predict(model_fit, newdata = bias_variance_grid))
    )
  ) |>
  select(model, predictions) |>
  unnest(predictions)

ggplot() +
  geom_point(
    data = bias_variance_train,
    aes(x = x, y = y),
    alpha = 0.7
  ) +
  geom_line(
    data = bias_variance_truth,
    aes(x = x, y = truth),
    linetype = "dashed",
    color = "gray35",
    linewidth = 1
  ) +
  geom_line(
    data = bias_variance_fits,
    aes(x = x, y = predicted),
    color = "#0072B2",
    linewidth = 1
  ) +
  facet_wrap(~ model) +
  coord_cartesian(ylim = c(-1.6, 1.6)) +
  scale_x_continuous(breaks = c(0, 0.5, 1)) +
  labs(
    x = "x",
    y = "y",
    title = "Underfitting, reasonable flexibility, and overfitting",
    subtitle = "Dashed line = true mean relationship; blue line = fitted model"
  ) +
  theme_minimal()

The degree 1 model has high bias: it is too simple to follow the curve. The degree 12 model has high variance: it bends to chase the noise in this particular sample. The degree 3 model is not perfect, but it follows the true curve without chasing individual points. Compare this single sample with the 30 samples in Example 22.17, which show the same thing as a pattern across samples.

22.8 Things to Watch Out For

Most validation mistakes make a model look better than it is. Here are the ones that come up most often, collected in one place.

WarningCommon ways validation goes wrong
  • Using the testing set more than once. Every look at the test set that changes the model makes the final estimate more optimistic.
  • Choosing predictors, transformations, or tuning parameters with all of the data, then validating on part of it (Example 22.12).
  • Splitting rows at random when the data have groups (Example 22.13) or a time order (Example 22.14).
  • Duplicate or near-duplicate rows split across training and testing.
  • Trusting a single split of a small dataset (Example 22.5). Use repeated cross-validation instead.
  • Reporting only the squared-correlation \(R^2\), which ignores bias in the predictions (Example 22.3). Look at RMSE or MAE and a predicted-versus-observed plot.
  • Comparing RMSEs computed on different response scales (Example 22.16).
  • Reading validation results as if they apply outside the range of the data (Example 22.15).
  • Factor levels that appear in the testing set but not the training set (Example 22.7).
  • Assuming future data will look like the current data. If the population changes (new products, a new time period, a different hospital), past validation results may not carry over.

The last item deserves a little more. Every method in this chapter estimates performance on new data drawn from the same population as the data we have. When the model is used somewhere different, the estimate may not apply. The best check is to validate on data collected in the new setting, if any can be obtained, and to keep monitoring predictions after a model is put into use.

22.9 Validation Reporting Checklist

When reporting a validation analysis, include enough detail for someone else to see how the performance estimate was obtained and, ideally, to reproduce it.

TipWhat to report
  • The splitting method: train-test split, validation set, k-fold cross-validation, repeated cross-validation, or LOOCV, and whether the folds respected groups or time order.
  • The random seed used before creating the splits or folds.
  • The sizes of the training and testing sets.
  • The stratification variable, if one was used.
  • The preprocessing steps (transformations, dummy variables, scaling, filtering, feature engineering) and confirmation that they were estimated within each fold.
  • How candidate models were compared and how the final model was chosen, including how many models were compared.
  • The final model: predictors, transformations, and fitting method.
  • The performance metrics, which version of \(R^2\) was used, and the scale on which the metrics were computed.
  • The standard errors or spread of the resampled estimates, along with the averages.
  • Confirmation that the testing set was not used to choose or tune the model.

22.10 Recap

This chapter introduced validation as a way to estimate how well a model will perform on new data, along with the ways that estimate can go wrong.

Idea Meaning
Model validation Evaluating how well a fitted model is likely to perform on unseen data.
Generalization The ability of a model to perform well beyond the data used to fit it.
Training error Error on the data used to fit the model; always optimistic.
Training set The part of the data used to estimate model parameters.
Validation set A held-out set, or resampling process, used to compare candidate models or tune settings.
Testing set The part of the data held back to estimate final predictive performance.
Data leakage Information from held-out data influencing the model fitting, usually making performance look better than it is.
Train-test split Separating the data into training and testing subsets.
Monte Carlo CV Repeating random train-test splits many times and averaging.
Stratification Splitting within groups, or bins of a numeric variable, to keep their proportions similar across splits.
Cross-validation Repeatedly training and validating a model on different partitions of the data.
k-fold cross-validation Dividing the data into \(k\) folds and holding out each fold once.
Repeated cross-validation k-fold cross-validation repeated with different random fold assignments.
LOOCV Leave-one-out cross-validation; for least squares, computed from the PRESS residuals \(e_i/(1-h_{ii})\).
Grouped cross-validation Holding out whole groups (subjects, schools) so the model is tested on groups it has not seen.
Time-based split Training on earlier data and testing on later data.
One-standard-error rule Choosing the simplest model whose CV error is within one standard error of the best.
RMSE Root mean squared prediction error, in response units; penalizes large errors heavily.
MAE Mean absolute prediction error, in response units.
rsq vs rsq_trad Squared correlation between predictions and responses vs. \(1 - \text{SSE}/\text{SST}\); only the second penalizes biased predictions, and it can be negative.
Extrapolation Predicting outside the region covered by the data, where validation gives no information.
Overfitting A model too complex for the data; much better on training data than validation data.
Underfitting A model too simple for the data; poor on both training and validation data.
Bias-variance tradeoff The balance between error from overly simple assumptions and error from sensitivity to the particular sample.
Validation report A summary of the splitting method, seed, preprocessing, model selection process, and performance metrics.

22.11 Check your understanding

NoteProblems
  1. Why can a model that fits the training data well still perform poorly on new data?

  2. In Example 22.1, the training RMSE of the highest-degree polynomials fell below the noise standard deviation of 0.25. Why is that a sign of overfitting?

  3. What is the purpose of holding out a testing set?

  4. Why should the testing set remain untouched during model building?

  5. What is data leakage, conceptually?

  6. A model’s held-out predictions have a squared correlation of 0.95 with the responses, but rsq_trad is \(-0.4\). What does this tell you about the predictions, and what plot would you make?

  7. A model has a test RMSE of 4.1 and a test MAE of 1.6. What does the gap suggest?

  8. Why might stratification be useful when splitting data? What does initial_split() do when you stratify on a numeric variable?

  9. A model with a factor predictor fits fine but predict() fails on the testing set with a “new levels” error. What happened, and name two ways to fix it.

  10. How does k-fold cross-validation differ from a single train-test split, and why does it give a steadier estimate?

  11. What are the tradeoffs in choosing \(k\) for k-fold cross-validation?

  12. What does repeated cross-validation try to reduce?

  13. How can the LOOCV error for a least squares regression be computed without refitting the model \(n\) times?

  14. In Example 22.10, why are the leave-one-out residuals of the high-leverage cars larger, relative to their ordinary residuals, than those of the other cars?

  15. A student finds the 10 predictors most correlated with the response using the full dataset, then runs 10-fold cross-validation on a model with those predictors. What is wrong, and how should it be done?

  16. A dataset has 8 measurements on each of 40 patients. The model will be used to make predictions for new patients. How should the data be split, and why?

  17. Why is a random train-test split inappropriate for a model that will be used to forecast next year’s values?

  18. Two models have almost the same cross-validated RMSE. Can validation tell you which one will predict better at predictor values outside the range of the data?

  19. One model of y has a CV RMSE of 2.3; a model of log(y) has a CV RMSE of 0.09. Which is better?

  20. What is the one-standard-error rule, and why prefer the simpler model?

  21. How does overfitting differ from underfitting, and what training-versus-validation patterns suggest each?

  22. How does the bias-variance tradeoff connect to overfitting and underfitting?

  23. Why should a validation report include the preprocessing steps, the random seed, and the number of models compared?

  24. Why should validation be treated as evidence rather than proof?

  1. The model may have learned noise specific to the sample. It can match the training data closely without capturing a relationship that holds for future observations.

  2. No model can predict new observations with an RMSE smaller than the noise standard deviation, because that noise is unpredictable. A training RMSE below 0.25 means the model is reproducing some of the noise in the training data, which it will not be able to do on new data.

  3. The testing set stands in for future data. Because the model was not fit using those observations, test-set performance is an unbiased estimate of how the model generalizes.

  4. It keeps the performance estimate honest. If we use the testing set to choose predictors, transformations, or tuning settings, it is no longer independent of the modeling process, and the estimate will be optimistic.

  5. Data leakage means information from held-out data gets into model fitting. The usual result is a performance estimate that is too optimistic.

  6. The predictions move with the responses but are systematically off, shifted or scaled, so that they do worse than predicting the mean of the held-out data. A plot of predicted against observed values with the line \(y = x\) would show the points following a line that is not \(y = x\).

  7. RMSE is much larger than MAE, so a few observations have very large errors while most are small. Look at those observations: they may be outliers, data errors, or a part of the data the model does not handle.

  8. Stratification keeps the proportions of important groups similar in the training and testing sets, which matters most when some groups are small or strongly related to the response. For a numeric variable, initial_split() cuts it into bins at its quartiles and stratifies on the bins.

  9. A level of the factor occurs in the testing set but not the training set, so the model has no coefficient for it. Fixes include lumping rare levels together before modeling (fct_lump_min() or step_other()), stratifying the split on that factor, or treating the variable as numeric if that makes sense.

  10. A single split uses one held-out set. k-fold cross-validation holds out each of \(k\) folds once and averages the results, so the estimate is based on every observation and depends much less on one lucky or unlucky split.

  11. Small \(k\) trains each model on less data, so the estimate tends to overstate the error of a model fit to all the data. Large \(k\) reduces that bias but takes more model fits, can be more variable, and leaves fewer observations in each fold, which makes per-fold metrics such as \(R^2\) unstable. Values of 5 or 10 are common compromises.

  12. It reduces the dependence of the estimate on one random assignment of observations to folds.

  13. The leave-one-out residual is \(e_i/(1 - h_{ii})\), where \(e_i\) is the ordinary residual and \(h_{ii}\) is the leverage. Squaring and averaging these gives the LOOCV mean squared error, which is PRESS divided by \(n\).

  14. A high-leverage point pulls the fitted surface toward itself when it is included, so its ordinary residual is small. When it is left out, nothing nearby holds the fit in place, and the prediction for it can be far off. The factor \(1/(1 - h_{ii})\) is large when \(h_{ii}\) is close to 1.

  15. The predictor screening used the held-out observations, so the cross-validation is estimating the error of a procedure that has already seen the test data. The estimate will be too optimistic, as in Example 22.12, where it made pure noise look predictable. The screening has to be redone inside each fold using only that fold’s training data.

  16. Hold out whole patients, for example with group_vfold_cv(group = patient). If a patient’s measurements are on both sides of the split, the model is rewarded for recognizing patients it has seen, which it cannot do for new patients.

  17. A random split lets the model train on data from after the test observations and lets it interpolate between neighboring time points. Forecasting requires predicting past the end of the data. The testing set should be the most recent data, as with initial_time_split() or rolling-origin resampling.

  18. No. Validation only uses observations within the range of the data, so it cannot distinguish models that agree there and disagree outside it (Example 22.15). That choice has to be based on subject knowledge or new data.

  19. The numbers cannot be compared because they are on different scales. Back-transform the log model’s held-out predictions to the original scale and compute RMSE in the original units before comparing.

  20. Find the model with the smallest mean CV error, then choose the simplest model whose mean CV error is within one standard error of it. Differences smaller than a standard error are not reliably real, and among models that perform about the same, the simpler one is easier to interpret and usually more stable.

  21. Overfitting is a model too complex for the data; it shows strong training performance and much weaker validation performance. Underfitting is a model too simple for the data; it shows weak performance on both training and validation data, with a small gap between them.

  22. Underfitting goes with high bias: the model is consistently wrong in the same way. Overfitting goes with high variance: the fitted model changes a lot from one training sample to another. A useful model balances the two.

  23. The seed determines the random splits, so it is needed to reproduce the results. Preprocessing can strongly affect performance and is a common source of leakage. The number of models compared matters because the best of many validation scores is optimistic.

  24. Validation estimates performance on new data from the same population as the current sample. Future data may come from a different population or time period, and even within the same population, the estimate has sampling error of its own.


  1. Hastie, T., Tibshirani, R., & Friedman, J. (2009). The Elements of Statistical Learning (2nd ed.). Springer. Section 7.10.2.↩︎