3. We now review k-fold cross-validation.
(a) Explain how k-fold cross-validation is implemented.
K-fold cross-validation is a technique used to evaluate the performance of a machine learning model by dividing the dataset into k subsets (or folds). The model is trained and evaluated k times, each time using a different fold as the validation set and the remaining k-1 folds as the training set.
(b) What are the advantages and disadvantages of k-fold cross-validation relative to:
i. The validation set approach?
Advantages: Makes better use of the data; less variance in the test error estimate. Disadvantages: Computationally more expensive.
ii. LOOCV?
Advantages: Less computationally expensive than LOOCV.
Disadvantages: Slightly more bias in the estimate compared to LOOCV, but typically less variance.

5. 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.
(a) Fit a logistic regression model that uses income and balance to predict default.

data(Default)
glm_fit <- glm(default ~ income + balance, data = Default, family = binomial)
summary(glm_fit)
## 
## Call:
## glm(formula = default ~ income + balance, family = binomial, 
##     data = Default)
## 
## Coefficients:
##               Estimate Std. Error z value Pr(>|z|)    
## (Intercept) -1.154e+01  4.348e-01 -26.545  < 2e-16 ***
## income       2.081e-05  4.985e-06   4.174 2.99e-05 ***
## balance      5.647e-03  2.274e-04  24.836  < 2e-16 ***
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## (Dispersion parameter for binomial family taken to be 1)
## 
##     Null deviance: 2920.6  on 9999  degrees of freedom
## Residual deviance: 1579.0  on 9997  degrees of freedom
## AIC: 1585
## 
## Number of Fisher Scoring iterations: 8

(b) Using the validation set approach, estimate the test error of this model. In order to do this, you must perform the following steps:
i. Split the sample set into a training set and a validation set.

train_indices <- sample(1:nrow(Default), 0.7 * nrow(Default))
train <- Default[train_indices, ]
test <- Default[-train_indices, ]

ii. Fit a multiple logistic regression model using only the training observations.

glm_fit_val <- glm(default ~ income + balance, data = train, family = binomial)

iii. 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.

glm_probs <- predict(glm_fit_val, newdata = test, type = "response")
glm_pred <- ifelse(glm_probs > 0.5, "Yes", "No")

iv. Compute the validation set error, which is the fraction of the observations in the validation set that are misclassified.

mean(glm_pred != test$default)
## [1] 0.02666667

(c) Repeat the process in (b) three times, using three different splits of the observations into a training set and a validation set. Comment on the results obtained.

errors <- replicate(3, {
  train_indices <- sample(1:nrow(Default), 0.7 * nrow(Default))
  train <- Default[train_indices, ]
  test <- Default[-train_indices, ]
  glm_fit_val <- glm(default ~ income + balance, data = train, family = binomial)
  glm_probs <- predict(glm_fit_val, newdata = test, type = "response")
  glm_pred <- ifelse(glm_probs > 0.5, "Yes", "No")
  mean(glm_pred != test$default)
})
errors
## [1] 0.02800000 0.02300000 0.02766667

The initial validation set error of 0.02666667 indicates a low misclassification rate for the logistic regression model using income and balance, suggesting good predictive performance on the test set. The repeated splits yield errors of 0.02800000, 0.02300000, and 0.02766667, showing consistent performance with minor variation, which reflects the stability of the model across different train-test splits.

(d) Now consider a logistic regression model that predicts the probability of default using income, balance, and a dummy variable for student. Estimate the test error for this model using the validation set approach. Comment on whether or not including a dummy variable for student leads to a reduction in the test error rate.

glm_fit_student <- glm(default ~ income + balance + student, data = train, family = binomial)
glm_probs_student <- predict(glm_fit_student, newdata = test, type = "response")
glm_pred_student <- ifelse(glm_probs_student > 0.5, "Yes", "No")
val_error_student <- mean(glm_pred_student != test$default)
val_error_student
## [1] 0.02766667

It does not significantly reduce the test error rate, suggesting it adds little predictive power beyond income and balance.

6. 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.
(a) Using the summary() and glm() functions, determine the estimated standard errors for the coefficients associated with income and balance in a multiple logistic regression model that uses both predictors.

fit_glm <- glm(default ~ income + balance, data = Default, family = "binomial")
summary(fit_glm)$coefficients
##                  Estimate   Std. Error    z value      Pr(>|z|)
## (Intercept) -1.154047e+01 4.347564e-01 -26.544680 2.958355e-155
## income       2.080898e-05 4.985167e-06   4.174178  2.990638e-05
## balance      5.647103e-03 2.273731e-04  24.836280 3.638120e-136

(b) Write a function, boot.fn(), that takes as input the Default data set as well as an index of the observations, and that outputs the coefficient estimates for income and balance in the multiple logistic regression model.

boot.fn <- function(data, index) {
  fit <- glm(default ~ income + balance, data = data[index, ], family = binomial)
  return(coef(fit)[c("income", "balance")])
}

(c) Use the boot() function together with your boot.fn() function to estimate the standard errors of the logistic regression coefficients for income and balance.

boot_results <- boot(Default, boot.fn, R = 1000)
se_boot <- apply(boot_results$t, 2, sd)
se_boot
## [1] 4.846850e-06 2.300222e-04

(d) Comment on the estimated standard errors obtained using the glm() function and using your bootstrap function.

The standard errors estimated using the glm() function are approximately 4.985167e-06 for income and 2.273731e-04 for balance, while the bootstrap estimates are slightly higher at 4.846850e-06 for income and 2.300222e-04 for balance. This minor increase in the bootstrap standard errors suggests that the bootstrap method captures additional variability not accounted for by the glm() function’s assumptions, which indicates the model assumptions are reasonably well-supported by the data.

9. We will now consider the Boston housing data set, from the ISLR2 library.
(a) Based on this data set, provide an estimate for the population mean of medv. Call this estimate \(\hat{\mu}\).

data(Boston)
mu_hat <- mean(Boston$medv)
mu_hat
## [1] 22.53281

(b) Provide an estimate of the standard error of \(\hat{\mu}\). Interpret this result. Hint: We can compute the standard error of the sample mean by dividing the sample standard deviation by the square root of the number of observations.

se_mu <- sd(Boston$medv) / sqrt(nrow(Boston))
se_mu
## [1] 0.4088611

This indicate the variability of the sample mean as an estimate of the population mean, and with a sample size of 506, it suggests moderate precision in this estimate.

(c) Now estimate the standard error of \(\hat{\mu}\) using the bootstrap. How does this compare to your answer from (b)?

boot_fn <- function(data, index) mean(data$medv[index])
boot_result <- boot(Boston, boot_fn, R = 1000)
boot_se_mu <- sd(boot_result$t)
boot_se_mu
## [1] 0.4144375

It is very close to the standard error of 0.4088611 from (b), indicating that both methods provide consistent estimates of the variability in the sample mean of medv, with the slight difference likely due to the bootstrap accounting for the data’s sampling distribution more flexibly.

(d) Based on your bootstrap estimate from (c), provide a 95% confidence interval for the mean of medv. Compare it to the results obtained using t.test(Boston$medv).
Hint: You can approximate a 95 % confidence interval using the formula \([ \hat{\mu} - 2SE(\hat{\mu}), \hat{\mu} + 2SE(\hat{\mu}) ]\).

mu_hat <- mean(Boston$medv) 
boot_se_mu <- 0.4144375 
ci_boot <- c(mu_hat - 2 * boot_se_mu, mu_hat + 2 * boot_se_mu)
ci_boot
## [1] 21.70393 23.36168
t_test_ci <- t.test(Boston$medv)$conf.int

The bootstrap 95% confidence interval (21.70393, 23.36168) is very close to the t-test confidence interval (~21.72, 23.35), both providing a consistent range for the mean medv, with the slight difference reflecting the bootstrap’s non-parametric estimation approach.

(e) Based on this data set, provide an estimate, \(\hat{\mu}_{med}\), for the median value of medv in the population.

mu_med_hat <- median(Boston$medv)
mu_med_hat
## [1] 21.2

(f) We now would like to estimate the standard error of \(\hat{\mu}_{med}\). Unfortunately, there is no simple formula for computing the standard error of the median. Instead, estimate the standard error of the median using the bootstrap. Comment on your findings.

boot.fn.median <- function(data, index) {
  median(data[index])
}

boot_median <- boot(Boston$medv, boot.fn.median, R = 1000)
boot_median
## 
## ORDINARY NONPARAMETRIC BOOTSTRAP
## 
## 
## Call:
## boot(data = Boston$medv, statistic = boot.fn.median, R = 1000)
## 
## 
## Bootstrap Statistics :
##     original   bias    std. error
## t1*     21.2 -0.02145   0.3673722

The bootstrap standard error of the median is approximately 0.3914472, indicating moderate variability in the median estimate of 21.2 for medv, and the small bias (-0.00805) suggests the bootstrap provides a reliable and nearly unbiased estimate of the population median given the lack of a direct formula.

(g) Based on this data set, provide an estimate for the tenth percentile of medv in Boston census tracts. Call this quantity \(\hat{\mu}_{0.1}\). (You can use the quantile() function.)

mu_0.1_hat <- quantile(Boston$medv, 0.1)
mu_0.1_hat
##   10% 
## 12.75

(h) Use the bootstrap to estimate the standard error of \(\hat{\mu}_{0.1}\). Comment on your findings.

boot_fn_0.1 <- function(data, index) quantile(data$medv[index], 0.1)
boot_result_0.1 <- boot(Boston, boot_fn_0.1, R = 1000)
boot_se_0.1 <- sd(boot_result_0.1$t)
boot_se_0.1
## [1] 0.5021826

The bootstrap standard error of the tenth percentile (~0.4974006) indicates moderate variability in the estimate of ~12.75 for medv, reflecting the skewed distribution of the data, and confirms the robustness of bootstrapping for estimating the standard error of this quantile where no simple formula exists.