library(caret) # cross-validation
library(ggplot2) # visualization
theme_set(theme_light())11.1 Assessing model accuracy
Packages
The bias-variance trade-off
Assessing the accuracy of a model means asking how well it predicts, for a categorical response (classification) as well as for a quantitative response (regression). An error calculated from the same data that were used to fit the model is the training error. It is too optimistic, because the model has adapted to these data, including their random noise. What matters is the test error: how well the model predicts new data that it has not seen (James et al., 2021).
Why is the training error too optimistic, and how complex should a model be? For a new observation \(y_0\) with predictors \(x_0\), the expected squared prediction error of a model \(\hat{f}\) can be split into three parts (James et al., 2021; Kuhn and Johnson, 2013):
\[ E\left[\left(y_0 - \hat{f}(x_0)\right)^2\right] = \mathrm{Var}\left(\hat{f}(x_0)\right) + \left[\mathrm{Bias}\left(\hat{f}(x_0)\right)\right]^2 + \mathrm{Var}(\varepsilon) \]
- Variance: how much the fitted model would change if it were fitted to a different sample from the same population.
- Bias: the systematic error that arises because the form of the model differs from the true relationship, e.g., a straight line fitted to a curved relationship.
- Irreducible error \(\mathrm{Var}(\varepsilon)\): random variation in the response that no model can predict.
Simple models, with few predictors and a linear form, have a low variance but may have a high bias: they underfit, i.e., they miss part of the true relationship (Figure 14.1, left). Flexible models, with many predictors or polynomial terms, have a low bias but a high variance: they also fit the noise in the training data, i.e., they overfit (Figure 14.1, right). An overfitted model follows the training data closely but predicts new data poorly, because the noise of new data differs. A good model captures the true relationship but not the noise (Figure 14.1, center).
More flexibility therefore always lowers the training error. The test error, however, decreases only as long as the reduction in bias outweighs the increase in variance, and then rises again (Figure 14.2). The best model balances bias and variance. To find it, we need an estimate of the test error, not the training error, for example from an independent test dataset or from cross-validation (see Resampling techniques).
Resampling techniques
Ideally, we estimate the test error with an independent test dataset. Often, however, there are not enough data to set one aside. Resampling techniques solve this by repeatedly splitting the available data: the model is fitted to one part and evaluated on the other, and the errors are averaged over all splits (James et al., 2021; Kuhn and Johnson, 2013). The most widely used resampling techniques are cross-validation and the bootstrap. Here, we focus on two forms of cross-validation: K-fold and leave-one-out. Other variants include repeated K-fold cross-validation and Monte Carlo cross-validation, which uses repeated random splits into training and test data (Kuhn and Johnson, 2013).
A single random split has two drawbacks. First, the error estimate varies, because it depends on which observations end up in the test set. Second, it tends to overestimate the test error of the final model, because the model is fitted to only part of the data. Resampling reduces the first problem by averaging the error over many splits, and the second by fitting each model to most of the data (James et al., 2021). In addition, some resampling techniques can be used to quantify the uncertainty of the error estimate (Kuhn and Johnson, 2013).
K-fold cross-validation
K-fold cross-validation randomly splits the data into K roughly equal-sized parts (folds). Each fold is held out once as test data, while the model is fitted to the remaining K − 1 folds. This gives K error estimates, which are averaged. Every observation is thus used once for testing. Typical choices of K are 5 or 10. Figure 14.3 shows the procedure for K = 5.
Leave-one-out cross-validation
Leave-one-out cross-validation (LOOCV) is the special case K = N, where N is the number of observations. Each observation is held out once, and the model is fitted to the remaining N − 1 observations (Figure 14.4). LOOCV thus requires N model fits, which can be slow for large datasets. Because each model is fitted to almost all data, the LOOCV error estimate has little bias. However, because the N training sets are nearly identical, it has a higher variance than K-fold cross-validation with K = 5 or 10, which is therefore commonly used (James et al., 2021). For small datasets, LOOCV and repeated K-fold cross-validation are both suitable, while for large datasets the differences between resampling methods become less pronounced (Kuhn and Johnson, 2013). In the examples, we use LOOCV, because both datasets are small (111 and 120 observations).
Classification accuracy
A classification model predicts a class for each observation. To assess its accuracy, we compare the predicted with the observed classes, ideally for an independent test dataset or with cross-validation (see Resampling techniques). We summarize this comparison in a confusion matrix (Table 14.1): the rows are the predicted classes, the columns the observed classes, and the diagonal holds the correctly classified cases.
| Obs. A | Obs. B | Obs. C | Precision | |
|---|---|---|---|---|
| Pred. A | TP | FP | FP | TP / row total |
| Pred. B | FN | TP | · | TP / row total |
| Pred. C | FN | · | TP | TP / row total |
| Recall | TP / column total | TP / column total | TP / column total | Overall accuracy = diagonal / N |
- Obs., Pred.: observed (reference) and predicted class
- TP (true positive): correctly classified cases (diagonal)
- FP (false positive): cases of another class wrongly assigned to the predicted class (shown for class A)
- FN (false negative): cases of the observed class wrongly assigned to another class (shown for class A)
- ·: errors between classes B and C
- N: total number of cases
Per-class measures treat one class as positive and all other classes as negative. Every off-diagonal cell is therefore a false positive for its row class and a false negative for its column class. The remaining cases, neither observed nor predicted as the class, are true negatives (TN); for class A, these are all cells in rows and columns B–C. From the matrix, we calculate three measures:
- Precision: of the cases predicted as a class, the share that truly belong to it. Commission error = 1 − precision.
- Recall: of the cases observed in a class, the share the model correctly predicts. Omission error = 1 − recall.
- Overall accuracy: the share of all cases on the diagonal.
In remote sensing, precision is called user’s accuracy and recall producer’s accuracy (Olofsson et al., 2014).
In hypothesis testing, false positives and false negatives are called type I and type II errors. A type I error is the incorrect rejection of a true null hypothesis, i.e., detecting an effect that is not present. A type II error is the failure to reject a false null hypothesis, i.e., missing an effect that is present.
Example: LDA model
The chapter on linear discriminant function analysis applies these measures to a classification of four plant taxa: it constructs the confusion matrix, calculates precision, recall, and overall accuracy, and compares the training error with the test error estimated by leave-one-out cross-validation.
Regression accuracy
For a quantitative response, we compare the predicted values \(\hat{y}_i\) directly with the observed values \(y_i\). The difference \(y_i - \hat{y}_i\) is the prediction error of observation \(i\), and we summarize these errors over all \(n\) observations. The most common measure is the root mean squared error (RMSE), which is calculated from the mean squared error (MSE) (Kuhn and Johnson, 2013). A third common measure, which caret also reports, is the mean absolute error (MAE).
Mean Squared Error (MSE): the average squared error. Squaring gives large errors more weight.
\[ MSE = \frac{1}{n} \sum_{i=1}^n(y_i - \hat{y}_i)^2 = \frac{1}{n} SSE \]
where SSE is the sum of squared errors.
Root Mean Squared Error (RMSE): the square root of the MSE. It is in the same units as the response and can be read as the typical size of a prediction error.
\[ RMSE = \sqrt{MSE} \]
Mean Absolute Error (MAE): the average absolute error. It is also in the units of the response but less sensitive to large errors than the RMSE.
\[ MAE = \frac{1}{n} \sum_{i=1}^n|y_i - \hat{y}_i| \]
Example: ozone model
We use the air quality data from the chapter on multiple regression: daily measurements of ozone (ppb), solar radiation (Langleys), wind speed (mph), and temperature (°F) in New York from May to September 1973. We assess how well the best model from the exhaustive model selection predicts ozone concentrations. This model explains log-transformed ozone by solar radiation, temperature, wind speed, and the interaction between temperature and wind speed. As before, we remove the rows with missing values and log-transform ozone:
airq <- read.table("data/airquality.txt", sep = ",", dec = ".", header = TRUE)
airq <- na.omit(airq)
airq$logOzone <- log(airq$Ozone)
fit <- lm(logOzone ~ Solar + Temp + Wind + Temp:Wind, data = airq)
summary(fit)
Call:
lm(formula = logOzone ~ Solar + Temp + Wind + Temp:Wind, data = airq)
Residuals:
Min 1Q Median 3Q Max
-1.98683 -0.32080 -0.05444 0.30229 1.19024
Coefficients:
Estimate Std. Error t value Pr(>|t|)
(Intercept) -2.5842953 1.1938493 -2.165 0.0327 *
Solar 0.0025945 0.0005484 4.731 6.92e-06 ***
Temp 0.0782286 0.0145813 5.365 4.79e-07 ***
Wind 0.1660818 0.1053138 1.577 0.1178
Temp:Wind -0.0029287 0.0013403 -2.185 0.0311 *
---
Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
Residual standard error: 0.4998 on 106 degrees of freedom
Multiple R-squared: 0.6789, Adjusted R-squared: 0.6668
F-statistic: 56.03 on 4 and 106 DF, p-value: < 2.2e-16
Cross-validation with caret
The caret package (Kuhn, 2026) cross-validates many types of models with a few lines of code. It takes two steps: trainControl() defines the resampling method, here LOOCV, and train() fits the model with this method and reports the cross-validated RMSE, \(R^2\), and MAE.
# define training control
train.control <- trainControl(method = "LOOCV")
# LOOCV of the linear model
loocv <- train(logOzone ~ Solar + Temp + Wind + Temp:Wind,
data = airq,
method = "lm",
trControl = train.control)
loocvLinear Regression
111 samples
3 predictor
No pre-processing
Resampling: Leave-One-Out Cross-Validation
Summary of sample sizes: 110, 110, 110, 110, 110, 110, ...
Resampling results:
RMSE Rsquared MAE
0.5159639 0.6423331 0.404394
Tuning parameter 'intercept' was held constant at a value of TRUE
caret reports \(R^2\) as the squared correlation between the observed values and the cross-validated (out-of-sample) predictions. The \(R^2\) of the OLS fit, in contrast, is based on the fitted (in-sample) values. For the fitted values of an OLS model with intercept, both calculations give the same value. caret’s \(R^2\) is therefore lower only because it is based on out-of-sample predictions, just as the cross-validated error is higher than the training error. Note that a squared correlation measures whether predictions and observations agree in pattern, not whether the predictions are accurate: predictions that are systematically too high can still have a high \(R^2\) (Kuhn and Johnson, 2013).
# R2 estimated from OLS
summary(fit)[["r.squared"]][1] 0.6788894
# adjusted R2 estimated from OLS
summary(fit)[["adj.r.squared"]][1] 0.666772
# R2 from caret
loocv$results$Rsquared[1] 0.6423331
The RMSE reported by caret is on the log scale, because the model predicts logOzone, and it cannot be back-transformed by simply exponentiating it. Instead, we back-transform the cross-validated predictions, which caret stores in $pred, and calculate the RMSE from them:
cv_pred <- loocv$pred
head(cv_pred) pred obs rowIndex intercept
1 2.880417 3.713572 1 TRUE
2 2.977771 3.583519 2 TRUE
3 2.960394 2.484907 3 TRUE
4 2.900448 2.890372 4 TRUE
7 3.062097 3.135494 5 TRUE
8 2.142072 2.944439 6 TRUE
# RMSE of the back-transformed cross-validated predictions (ppb)
sqrt(mean((exp(cv_pred$pred) - exp(cv_pred$obs))^2))[1] 21.84837
ggplot(cv_pred, aes(x = exp(obs), y = exp(pred))) +
geom_point() +
geom_abline(intercept = 0, slope = 1) +
labs(x = "Observed ozone (ppb)", y = "Predicted ozone (ppb)")
The cross-validated RMSE is about 22 ppb, i.e., the predicted ozone concentrations are typically about 22 ppb off.
This cross-validation estimates how well the model predicts new days from the same period. It has two limitations. First, it ignores the order of the days and therefore does not show how well the model forecasts future days. This requires predicting later days from earlier ones (time-series cross-validation). Second, neighboring days are similar, so the estimated error may be somewhat too optimistic. Holding out blocks of consecutive days instead of single days (blocked cross-validation) avoids this.
To see what happens inside a cross-validation, we write our own K-fold cross-validation with a function and a loop. First, we use the caret package to split the dataset into 10 folds (sub-samples). The assignment to folds is random, so we set a seed to make the results reproducible:
set.seed(42)
folds <- createFolds(airq$Ozone, k = 10)We provide createFolds() only with the response, not the entire dataset. It returns a list with one element per fold, containing the row numbers of the observations held out as test data in that fold. The folds are stratified by the response, i.e., each fold contains a similar range of ozone values.
class(folds)[1] "list"
folds[1:4]$Fold01
[1] 10 18 55 68 71 73 76 83 101 107 111
$Fold02
[1] 13 28 34 42 45 46 86 90 91 93 100 109
$Fold03
[1] 8 11 24 54 58 62 70 79 82 89
$Fold04
[1] 2 5 12 30 31 49 53 60 77 106 110
Next, we write a function cv_lm() with two arguments: the entire data frame (data) and the row numbers of one fold (i). It fits the model to all other rows and predicts the rows of the fold:
cv_lm <- function(data, i){
# all rows that are not in the fold are copied into a training dataset
train <- data[-i, ]
# all rows that are in the fold are used as test dataset
test <- data[i, ]
# fit a model using the training dataset
fit_train <- lm(logOzone ~ Solar + Temp + Wind + Temp:Wind, data = train)
# apply the model to the test dataset
pred_log <- predict(fit_train, newdata = test)
# back-transform log Ozone to Ozone
pred <- exp(pred_log)
# extract the observed Ozone concentration (reference)
ref <- test$Ozone
# return a data.frame with two columns containing the cross-validated
# predictions for the fold and the corresponding reference observations
return(data.frame(Prediction = pred,
Reference = ref))
}Let’s test our function on the first fold:
cv_first_fold <- cv_lm(airq, folds[[1]])
head(cv_first_fold) Prediction Reference
14 22.85492 14
22 24.82637 11
88 25.51527 52
106 29.46315 65
110 24.49058 23
112 28.51336 44
The function works, but we also need the predictions from the other folds. We can gather them all together by writing a loop from fold 1 to fold 10:
# create empty data.frame
cv_all_folds <- data.frame(Prediction = numeric(0), Reference = numeric(0))
for(i in folds){
# add the rows of the fold
cv_all_folds <- rbind(cv_all_folds, cv_lm(airq, i))
}
ggplot(cv_all_folds, aes(x = Reference, y = Prediction)) +
geom_point() +
xlim(0, 175) +
ylim(0, 175) +
geom_abline(intercept = 0, slope = 1) +
labs(x = "Observed ozone (ppb)", y = "Predicted ozone (ppb)")
With the cross-validated predictions and the observations of all folds in one data frame, we can calculate the MSE, RMSE, and MAE:
mse <- function(x, y){mean((x - y)^2)}
mse(x = cv_all_folds$Prediction, y = cv_all_folds$Reference)[1] 482.6393
rmse <- function(x, y){sqrt(mean((x - y)^2))}
rmse(x = cv_all_folds$Prediction, y = cv_all_folds$Reference)[1] 21.96905
mae <- function(x, y){mean(abs(x - y))}
mae(x = cv_all_folds$Prediction, y = cv_all_folds$Reference)[1] 14.58951
The 10-fold cross-validated RMSE is also about 22 ppb. How does this compare with the training error of the model fitted to all data?
# training error: model fitted to and evaluated on all data
rmse(x = exp(fitted(fit)), y = airq$Ozone)[1] 20.8166
The training RMSE is slightly lower than the cross-validated RMSE: as expected, the training error is too optimistic. The difference is small here, because a linear model with few predictors has a low variance and hardly overfits (see The bias-variance trade-off).