3. We now review k-fold cross-validation.

(a) Explain how k-fold cross-validation is implemented.
k-fold cross-validation involves randomly dividing the dataset into k equal-sized folds (subsets). For each of the k iterations, one fold is treated as the validation set, while the model is trained on the remaining k−1 folds. The performance metric—such as the mean squared error (MSE)—is computed on the validation set (e.g., MSE₁ in the first iteration). This process is repeated k times, with each fold used exactly once as the validation set, resulting in k test error estimates: MSE₁, MSE₂, …, MSEₖ. The final k-fold CV estimate of the test error is obtained by averaging these k values.

(b) What are the advantages and disadvantages of k-fold cross validation relative to:

i. The validation set approach?
Compared to the validation set approach, k-fold cross-validation provides a more stable and accurate estimate of test error. It reduces variance because it averages over multiple folds and uses the entire dataset for both training and validation. In contrast, the validation set approach relies on a single split, which can lead to high variability and less efficient use of data. However, k-fold CV is more computationally expensive, as it requires training the model k times instead of just once.

ii. LOOCV?
Compared to leave-one-out cross-validation (LOOCV), k-fold CV is computationally much more efficient, especially for large datasets. While LOOCV has lower bias—since it trains on almost the full dataset—it tends to have higher variance due to its reliance on single-point validation sets. k-fold CV strikes a better balance between bias and variance and is generally preferred for practical applications.

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.

set.seed(1)
#load ISLR library to access Default data
library(ISLR)
## Warning: package 'ISLR' was built under R version 4.4.3
attach(Default)
#Logistic regression model
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. ii. Fit a multiple logistic regression model using only the training observations.

# Set seed for reproducibility
set.seed(1)
# Split the data
train = sample(10000, 5000)
train_data = Default[train, ]
validation_data = Default[-train, ]

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

# Fit logistic regression model on training set
glm.fit2 = glm(default ~ income + balance, data = train_data, family = binomial)
summary(glm.fit2)
## 
## Call:
## glm(formula = default ~ income + balance, family = binomial, 
##     data = train_data)
## 
## Coefficients:
##               Estimate Std. Error z value Pr(>|z|)    
## (Intercept) -1.194e+01  6.178e-01 -19.333  < 2e-16 ***
## income       3.262e-05  7.024e-06   4.644 3.41e-06 ***
## balance      5.689e-03  3.158e-04  18.014  < 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: 1523.8  on 4999  degrees of freedom
## Residual deviance:  803.3  on 4997  degrees of freedom
## AIC: 809.3
## 
## Number of Fisher Scoring iterations: 8

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.

# Predict on validation set
probs = predict(glm.fit2, newdata = validation_data, type = "response")
predicted = ifelse(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.

# Actual default values
actual = validation_data$default

# Compute validation set error
error_rate = mean(predicted != actual)
print(paste("Validation set error rate:", round(error_rate, 4)))
## [1] "Validation set error rate: 0.0254"

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

# Define a function to perform the validation process
run_validation <- function(seed) {
  set.seed(seed)
  train = sample(10000, 5000)
  
  # Training and validation sets
  train_data = Default[train, ]
  validation_data = Default[-train, ]
  
  # Fit logistic model
  model = glm(default ~ income + balance, data = train_data, family = "binomial")
  
  # Predict on validation set
  probs = predict(model, newdata = validation_data, type = "response")
  predicted = ifelse(probs > 0.5, "Yes", "No")
  
  # Compute validation error
  mean(predicted != validation_data$default)
}

# Run the process with three different random seeds
error1 = run_validation(1)
error2 = run_validation(2)
error3 = run_validation(3)

# Display results
cat("Validation Set Errors:\n")
## Validation Set Errors:
cat("Split 1 (seed = 1):", round(error1, 4), "\n")
## Split 1 (seed = 1): 0.0254
cat("Split 2 (seed = 2):", round(error2, 4), "\n")
## Split 2 (seed = 2): 0.0238
cat("Split 3 (seed = 3):", round(error3, 4), "\n")
## Split 3 (seed = 3): 0.0264

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

# Define function for validation with student variable
run_validation_with_student <- function(seed) {
  set.seed(seed)
  train = sample(10000, 5000)
  
  # Training and validation sets
  train_data = Default[train, ]
  validation_data = Default[-train, ]
  
  # Fit logistic model with student variable
  model = glm(default ~ income + balance + student, data = train_data, family = "binomial")
  
  # Predict on validation set
  probs = predict(model, newdata = validation_data, type = "response")
  predicted = ifelse(probs > 0.5, "Yes", "No")
  
  # Compute validation error
  mean(predicted != validation_data$default)
}

# Define function for validation without student variable (from part c)
run_validation_without_student <- function(seed) {
  set.seed(seed)
  train = sample(10000, 5000)
  
  # Training and validation sets
  train_data = Default[train, ]
  validation_data = Default[-train, ]
  
  # Fit logistic model without student variable
  model = glm(default ~ income + balance, data = train_data, family = "binomial")
  
  # Predict on validation set
  probs = predict(model, newdata = validation_data, type = "response")
  predicted = ifelse(probs > 0.5, "Yes", "No")
  
  # Compute validation error
  mean(predicted != validation_data$default)
}

# Run both models with the same three seeds for fair comparison
seeds = c(1, 2, 3)
errors_without_student = numeric(3)
errors_with_student = numeric(3)

cat("Comparison of Models:\n")
## Comparison of Models:
cat("====================\n")
## ====================
for(i in 1:3) {
  errors_without_student[i] = run_validation_without_student(seeds[i])
  errors_with_student[i] = run_validation_with_student(seeds[i])
  
  cat("Split", i, "(seed =", seeds[i], "):\n")
  cat("  Without student:", round(errors_without_student[i], 4), "\n")
  cat("  With student:   ", round(errors_with_student[i], 4), "\n")
  cat("  Difference:     ", round(errors_with_student[i] - errors_without_student[i], 4), "\n\n")
}
## Split 1 (seed = 1 ):
##   Without student: 0.0254 
##   With student:    0.026 
##   Difference:      6e-04 
## 
## Split 2 (seed = 2 ):
##   Without student: 0.0238 
##   With student:    0.0246 
##   Difference:      8e-04 
## 
## Split 3 (seed = 3 ):
##   Without student: 0.0264 
##   With student:    0.0272 
##   Difference:      8e-04
# Summary
cat("\nSummary:\n")
## 
## Summary:
cat("Mean error without student:", round(mean(errors_without_student), 4), "\n")
## Mean error without student: 0.0252
cat("Mean error with student:", round(mean(errors_with_student), 4), "\n")
## Mean error with student: 0.0259
mean_diff = mean(errors_with_student) - mean(errors_without_student)
cat("Difference:", round(mean_diff, 4), "\n")
## Difference: 7e-04
# Comment
if(mean_diff < 0) {
  cat("Including student variable reduces test error rate.\n")
} else if(mean_diff > 0) {
  cat("Including student variable increases test error rate.\n")
} else {
  cat("Including student variable has no effect on test error rate.\n")
}
## Including student variable increases test error rate.

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.

# Set seed for reproducibility
set.seed(123)
# Fit logistic regression model
model <- glm(default ~ income + balance, data = Default, family = binomial)

# Display model summary
summary_model <- summary(model)
summary_model
## 
## 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) Write a function, boot.fn(), that takes as input the Default dataset 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 logistic regression model on the bootstrap sample
  boot_model <- glm(default ~ income + balance, 
                    data = data, 
                    subset = index,
                    family = "binomial")
  
  # Return coefficients for income and balance
  return(coef(boot_model)[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.

# Set seed again for reproducibility
set.seed(123)
library(boot)
# Perform bootstrap with 1000 replicates
boot_results <- boot(Default, boot.fn, R = 1000)

# Display bootstrap results
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.582518e-07 4.729534e-06
## t2* 5.647103e-03 1.296980e-05 2.217214e-04

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

The standard errors obtained from both methods are very similar:
For the income coefficient: The GLM standard error (4.985e-06) is very close to the bootstrap standard error (4.729e-06), with a small difference of about 2.56e-07.
For the balance coefficient: The GLM standard error (2.274e-04) is also very close to the bootstrap standard error (2.217e-04), with a difference of about 5.68e-06.

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ˆµ.

library(ISLR2)
## Warning: package 'ISLR2' was built under R version 4.4.3
## 
## Attaching package: 'ISLR2'
## The following objects are masked from 'package:ISLR':
## 
##     Auto, Credit
data(Boston)

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

(b) Provide an estimate of the standard error of ˆ µ. 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.

# Sample size
n <- nrow(Boston)

# Sample standard deviation
s <- sd(Boston$medv)

# Standard error of the mean
se_mu <- s / sqrt(n)
se_mu
## [1] 0.4088611

(c) Now estimate the standard error of ˆµ using the bootstrap. How does this compare to your answer from (b)?

# Set seed for reproducibility
set.seed(123)

# Define bootstrap function to compute mean of medv
boot_fn <- function(data, index) {
  return(mean(data[index]))
}

# Perform 1000 bootstrap replicates
n <- nrow(Boston)
boot_means <- replicate(1000, boot_fn(Boston$medv, sample(1:n, n, replace = TRUE)))

# Bootstrap estimate of standard error
se_boot <- sd(boot_means)
se_boot
## [1] 0.4185474

The bootstrap standard error of 0.4185 is slightly larger than the analytical standard error of 0.4089

(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 [ˆ µ− 2SE(ˆ µ), ˆ µ + 2SE(ˆ µ)].

# 95% CI using bootstrap SE
mu_hat <- mean(Boston$medv)
se_boot <- 0.4185

# Approximate 95% CI
ci_lower <- mu_hat - 2 * se_boot
ci_upper <- mu_hat + 2 * se_boot
c(ci_lower, ci_upper)
## [1] 21.69581 23.36981
t.test(Boston$medv)
## 
##  One Sample t-test
## 
## data:  Boston$medv
## t = 55.111, df = 505, p-value < 2.2e-16
## alternative hypothesis: true mean is not equal to 0
## 95 percent confidence interval:
##  21.72953 23.33608
## sample estimates:
## mean of x 
##  22.53281

Based on the bootstrap standard error of 0.4185, the approximate 95% confidence interval for the population mean of medv is [21.70, 23.37]. This closely matches the t-test-based confidence interval of [21.73, 23.34]. The results are consistent, with the bootstrap interval being slightly wider due to not assuming normality or using the t-distribution.

(e) Based on this data set, provide an estimate, ˆ µmed, for the median value of medv in the population.

# Estimate the median
mu_med <- median(Boston$medv)
mu_med
## [1] 21.2

(f) We now would like to estimate the standard error of ˆ µ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.

# Set seed for reproducibility
set.seed(123)

# Define bootstrap function to compute the median
boot_median <- function(data, index) {
  return(median(data[index]))
}

# Perform 1000 bootstrap replicates
n <- nrow(Boston)
boot_medians <- replicate(1000, boot_median(Boston$medv, sample(1:n, n, replace = TRUE)))

# Estimate the standard error of the median
se_median <- sd(boot_medians)
se_median
## [1] 0.3852428

The bootstrap estimate of the standard error of the sample median is:
\(SE(\hat{\mu}_{\text{med}}) \approx 0.3852\).

(g) Based on this data set, provide an estimate for the tenth percentile of medv in Boston census tracts. Call this quantity ˆµ0.1.(You can use the quantile() function.)

# Estimate the 10th percentile of medv
mu_0.1 <- quantile(Boston$medv, 0.1)
mu_0.1
##   10% 
## 12.75

(h) Use the bootstrap to estimate the standard error of ˆ µ0.1. Comment on your findings.

# Set seed for reproducibility
set.seed(123)

# Define a bootstrap function to compute the 10th percentile
boot_q10 <- function(data, index) {
  return(quantile(data[index], 0.1))
}

# Perform 1000 bootstrap replicates
n <- nrow(Boston)
boot_q10s <- replicate(1000, boot_q10(Boston$medv, sample(1:n, n, replace = TRUE)))

# Estimate the standard error of the 10th percentile
se_q10 <- sd(boot_q10s)
se_q10
## [1] 0.5054028

The bootstrap estimate of the standard error of the 10th percentile of medv is:
\(SE(\hat{\mu}_{0.1}) \approx 0.5054\)