We now review k-fold cross-validation.
K‑fold cross‑validation partitions the dataset into k equal subsets, or folds. The model is trained k times, each time leaving out one fold as the validation set and training on the remaining k − 1 folds. The validation error from each iteration is recorded, and the k errors are averaged to produce a single estimate of the model’s test error. This procedure reduces the dependence on any single train–test split and yields a more stable estimate of predictive performance.
Relative to the validation‑set approach, k‑fold cross‑validation provides a substantially more stable estimate of test error. The validation‑set method relies on a single random split, making its estimate highly variable and sensitive to which observations fall into the training and validation sets. In contrast, k‑fold CV averages across multiple splits, reducing variance.
Additionally, k‑fold CV trains on a larger fraction of the data in each iteration, leading to a lower‑bias estimate of test error. The primary drawback is computational: the model must be fit k times rather than once.
Compared to LOOCV, k‑fold cross‑validation is computationally far more efficient, since LOOCV requires fitting the model n times. LOOCV also tends to produce higher‑variance test‑error estimates because each training set differs by only a single observation, making the resulting validation errors highly correlated.
K‑fold CV reduces this correlation by using more distinct training sets, yielding a lower‑variance estimate. The tradeoff is a slight increase in bias, since each model is trained on fewer than n − 1 observations. In practice, this bias is usually negligible.
In Chapter 4, we used logistic regression to predict the probability of default using income and balance on the Default data set. We will now estimate the test error of this logistic regression model using the validation set approach. Do not forget to set a random seed before beginning your analysis.
library(ISLR2)
summary(Default)
## default student balance income
## No :9667 No :7056 Min. : 0.0 Min. : 772
## Yes: 333 Yes:2944 1st Qu.: 481.7 1st Qu.:21340
## Median : 823.6 Median :34553
## Mean : 835.4 Mean :33517
## 3rd Qu.:1166.3 3rd Qu.:43808
## Max. :2654.3 Max. :73554
Fit a logistic regression model that uses income and balance to predict default
Using the validation set approach, estimate the test error of this model. In order to do this, you must perform the following steps:
Split the sample set into a training set and a validation set.
Fit a multiple logistic regression model using only the training observations.
Obtain a prediction of default status for each individual in the validation set by computing the posterior probability of default for that individual, and classifying the individual to the default category if the posterior probability is greater than 0.5.
Compute the validation set error, which is the fraction of the observations in the validation set that are misclassified.
set.seed(1)
n_obs <- nrow(Default)
train <- sample(n_obs, n_obs / 2)
glm.fit <- glm(default ~ income + balance, data = Default, family = binomial, subset = train)
glm.probs <- predict(glm.fit, Default[-train, ], type = "response")
glm.pred <- rep("No", length(glm.probs))
glm.pred[glm.probs > 0.5] <- "Yes"
glm.pred <- factor(glm.pred, levels = c("No", "Yes"))
val_error_1 <- mean(glm.pred != Default[-train, ]$default)
print(paste("Validation Error Rate (Split 1):", round(val_error_1, 4)))
## [1] "Validation Error Rate (Split 1): 0.0254"
set.seed(2)
train <- sample(n_obs, n_obs / 2)
glm.fit <- glm(default ~ income + balance, data = Default, family = binomial, subset = train)
glm.probs <- predict(glm.fit, Default[-train, ], type = "response")
glm.pred <- rep("No", length(glm.probs))
glm.pred[glm.probs > 0.5] <- "Yes"
glm.pred <- factor(glm.pred, levels = c("No", "Yes"))
val_error_2 <- mean(glm.pred != Default[-train, ]$default)
set.seed(3)
train <- sample(n_obs, n_obs / 2)
glm.fit <- glm(default ~ income + balance, data = Default, family = binomial, subset = train)
glm.probs <- predict(glm.fit, Default[-train, ], type = "response")
glm.pred <- rep("No", length(glm.probs))
glm.pred[glm.probs > 0.5] <- "Yes"
glm.pred <- factor(glm.pred, levels = c("No", "Yes"))
val_error_3 <- mean(glm.pred != Default[-train, ]$default)
print(paste("Error Rate 2:", round(val_error_2, 4), "| Error Rate 3:", round(val_error_3, 4)))
## [1] "Error Rate 2: 0.0238 | Error Rate 3: 0.0264"
Across three random 50/50 splits, the validation error varies modestly (roughly 2.3%–2.7%). This variation illustrates the central weakness of the validation‑set approach: the estimate of test error depends heavily on the particular random split. However, the differences across splits are small in this case, suggesting that the logistic regression model is reasonably stable and that its predictive performance does not fluctuate dramatically with different training subsets.
set.seed(1)
train <- sample(n_obs, n_obs / 2)
glm.fit_student <- glm(default ~ income + balance + student, data = Default, family = binomial, subset = train)
glm.probs_student <- predict(glm.fit_student, Default[-train, ], type = "response")
glm.pred_student <- rep("No", length(glm.probs_student))
glm.pred_student[glm.probs_student > 0.5] <- "Yes"
glm.pred_student <- factor(glm.pred_student, levels = c("No", "Yes"))
val_error_student <- mean(glm.pred_student != Default[-train, ]$default)
print(paste("Validation Error with Student Variable:", round(val_error_student, 4)))
## [1] "Validation Error with Student Variable: 0.026"
Including the dummy variable for student does not meaningfully reduce the validation error. Although student may be statistically significant in the full model, it adds little incremental predictive value once balance and income are included. The test error remains essentially unchanged, indicating that the simpler model captures the relevant structure in the data just as effectively.
We continue to consider the use of a logistic regression model to predict the probability of default using income and balance on the Default data set. In particular, we will now compute estimates for the standard errors of the income and balance logistic regression coefficients in two different ways: (1) using the bootstrap, and (2) using the standard formula for computing the standard errors in the glm() function. Do not forget to set a random seed before beginning your analysis.
library(boot)
glm.fit <- glm(default ~ income + balance, data = Default, family = binomial)
summary(glm.fit)$coefficients[, 2]
## (Intercept) income balance
## 4.347564e-01 4.985167e-06 2.273731e-04
boot.fn <- function(data, index) {
fit <- glm(default ~ income + balance, data = data, family = binomial, subset = index)
return(coef(fit)[c("income", "balance")])
}
set.seed(1)
boot_results <- boot(data = Default, statistic = boot.fn, R = 1000)
print(boot_results)
##
## ORDINARY NONPARAMETRIC BOOTSTRAP
##
##
## Call:
## boot(data = Default, statistic = boot.fn, R = 1000)
##
##
## Bootstrap Statistics :
## original bias std. error
## t1* 2.080898e-05 1.680317e-07 4.866284e-06
## t2* 5.647103e-03 1.855765e-05 2.298949e-04
The bootstrap standard errors for the income and balance coefficients closely match those produced by the standard glm() output. This agreement suggests that the model‑based standard errors are reliable for this dataset. Because the bootstrap does not rely on the same parametric assumptions, the similarity between the two methods indicates that the logistic regression model is well‑behaved and that the sampling distribution of the coefficient estimates is adequately captured by the glm() formula.
We will now consider the Boston housing data set, from the ISLR2 library.
mu_hat <- mean(Boston$medv)
mu_hat
## [1] 22.53281
se_mu <- sd(Boston$medv) / sqrt(nrow(Boston))
se_mu
## [1] 0.4088611
The standard error of the sample mean is approximately 0.41, indicating that the sample mean is a precise estimator of the population mean. A small SE reflects low sampling variability.
boot.mean <- function(data, index) {
mean(data[index, "medv"])
}
set.seed(1)
boot_results <- boot(Boston, boot.mean, R = 1000)
boot_results
##
## ORDINARY NONPARAMETRIC BOOTSTRAP
##
##
## Call:
## boot(data = Boston, statistic = boot.mean, R = 1000)
##
##
## Bootstrap Statistics :
## original bias std. error
## t1* 22.53281 0.007650791 0.4106622
The bootstrap estimate of the standard error is nearly identical to the analytical estimate. This close agreement suggests that the sample mean behaves as expected under repeated sampling and that the normal‑theory formula provides an accurate measure of uncertainty for this dataset.
mu_hat <- mean(Boston$medv)
boot.mean <- function(data, index) {
return(mean(data[index, "medv"]))
}
set.seed(1)
boot_results <- boot(Boston, boot.mean, R = 1000)
se_boot <- sd(boot_results$t)
ci_lower_boot <- mu_hat - 2 * se_boot
ci_upper_boot <- mu_hat + 2 * se_boot
cat("Bootstrap 95% CI: [", round(ci_lower_boot, 4), ",", round(ci_upper_boot, 4), "]\n")
## Bootstrap 95% CI: [ 21.7115 , 23.3541 ]
t_test_results <- t.test(Boston$medv)
print(t_test_results$conf.int)
## [1] 21.72953 23.33608
## attr(,"conf.level")
## [1] 0.95
The bootstrap 95% confidence interval for the mean closely matches the interval produced by t.test(). This alignment indicates that the sampling distribution of the mean is approximately normal and that both methods provide consistent inference.
mu_hat_median <- median(Boston$medv)
cat("Estimated Population Median:", mu_hat_median, "\n")
## Estimated Population Median: 21.2
boot.median <- function(data, index) {
return(median(data[index, "medv"]))
}
set.seed(1)
boot_median_results <- boot(Boston, boot.median, R = 1000)
print(boot_median_results)
##
## ORDINARY NONPARAMETRIC BOOTSTRAP
##
##
## Call:
## boot(data = Boston, statistic = boot.median, R = 1000)
##
##
## Bootstrap Statistics :
## original bias std. error
## t1* 21.2 0.02295 0.3778075
Because no simple closed‑form expression exists for the standard error of the median, the bootstrap is particularly valuable here. The bootstrap estimate indicates that the sample median is reasonably stable across resampled datasets. The relatively small SE suggests that the median is a reliable measure of central tendency for this distribution.
mu_hat_tenth <- quantile(Boston$medv, 0.1)
cat("Estimated 10th Percentile:", mu_hat_tenth, "\n")
## Estimated 10th Percentile: 12.75
boot.tenth <- function(data, index) {
return(quantile(data[index, "medv"], 0.1))
}
set.seed(1)
boot_tenth_results <- boot(Boston, boot.tenth, R = 1000)
print(boot_tenth_results)
##
## ORDINARY NONPARAMETRIC BOOTSTRAP
##
##
## Call:
## boot(data = Boston, statistic = boot.tenth, R = 1000)
##
##
## Bootstrap Statistics :
## original bias std. error
## t1* 12.75 0.0339 0.4767526
The bootstrap standard error for the 10th percentile is larger than that of the mean or median. This is expected: tail estimates rely on fewer observations and are therefore more sensitive to sampling variability. The bootstrap provides a practical and robust way to quantify this uncertainty.