Problem 3

We now review k-fold cross-validation.* *(a) Explain how k-fold cross-validation is implemented.

This approach involves randomly dividing the set of observations into k groups, or folds, or approximately equal size. The first fold is treated as a validation set, and the method is fit on the remaining k - 1 folds. The mean squared error, MSE1, is then computed on the observations in the held-out fold. This procedure is repeated k times; each time, a diferent group of observations is treated as a validation set. This process results in k estimates of the test error, MSE1, MSE2,…, MSEk. After completing all k iterations, the accuracy is calculatred for all folds.

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

i. The validation set approach?

K-fold cross validation offers a more robust estimate of model performance, but it can be computationally more intensive than the simple validation set approach.

ii. LOOCV?

Cross-validation is a very general approach that can be applied to almost any statistical learning method. Some statistical learning methods have computationally intensive fitting procedures, and so performing LOOCV may pose computational problems, especially if n is extremely large. It also gives more accurate estimates of the test error rate. LOOCV may provide a more accurate estimate of the model’s performance for small datasets, but it can be computationally expensive. k-fold cross validation offers more stability in estimating model performance.

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

library(ISLR)
## Warning: package 'ISLR' was built under R version 4.4.2
set.seed(3)
glm.Default <- glm(default~income+balance, data=Default,family=binomial)
summary(glm.Default)
## 
## 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.

set.seed(1)
n <- nrow(Default)
train_index <- sample(1:n, n/2)
train_data <- Default[train_index, ]
validation_data <- Default[-train_index, ]

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

glm.fit <- glm(default ~ income + balance, data = train_data, 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.

probs <- predict(glm.fit, newdata = validation_data, type = "response")
predicted_default <- 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 misclassifed.

actual_default <- validation_data$default
misclassified <- mean(predicted_default != actual_default)
print(paste("Validation Set Error Rate:", round(misclassified, 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.

validation_error <- function(seed) {
  set.seed(seed)
  n <- nrow(Default)
  train_index <- sample(1:n, n/2)
  train_data <- Default[train_index, ]
  validation_data <- Default[-train_index, ]
  
  glm.fit <- glm(default ~ income + balance, data = train_data, family = binomial)
  probs <- predict(glm.fit, newdata = validation_data, type = "response")
  predicted_default <- ifelse(probs > 0.5, "Yes", "No")
  actual_default <- validation_data$default
  mean(predicted_default != actual_default)
}

error1 <- validation_error(1)
error2 <- validation_error(2)
error3 <- validation_error(3)

print(paste("Validation Error 1:", round(error1, 4)))
## [1] "Validation Error 1: 0.0254"
print(paste("Validation Error 2:", round(error2, 4)))
## [1] "Validation Error 2: 0.0238"
print(paste("Validation Error 3:", round(error3, 4)))
## [1] "Validation Error 3: 0.0264"
avg_error <- mean(c(error1, error2, error3))
print(paste("Average Validation Error:", round(avg_error, 4)))
## [1] "Average Validation Error: 0.0252"

Validation rates are similar across all three runs, ranging from ~2.38% to 2.64%. This tells us the model is performing consistently.

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

validation_error_with_student <- function(seed) {
  set.seed(seed)
  n <- nrow(Default)
  train_index <- sample(1:n, n/2)
  train_data <- Default[train_index, ]
  validation_data <- Default[-train_index, ]
  
  glm.fit <- glm(default ~ income + balance + student, data = train_data, family = binomial)
  probs <- predict(glm.fit, newdata = validation_data, type = "response")
  predicted_default <- ifelse(probs > 0.5, "Yes", "No")
  actual_default <- validation_data$default
  mean(predicted_default != actual_default)
}

error1_student <- validation_error_with_student(1)
error2_student <- validation_error_with_student(2)
error3_student <- validation_error_with_student(3)

print(paste("Validation Error with student (seed 1):", round(error1_student, 4)))
## [1] "Validation Error with student (seed 1): 0.026"
print(paste("Validation Error with student (seed 2):", round(error2_student, 4)))
## [1] "Validation Error with student (seed 2): 0.0246"
print(paste("Validation Error with student (seed 3):", round(error3_student, 4)))
## [1] "Validation Error with student (seed 3): 0.0272"
avg_error_student <- mean(c(error1_student, error2_student, error3_student))
print(paste("Average Validation Error with student:", round(avg_error_student, 4)))
## [1] "Average Validation Error with student: 0.0259"

The inclusion of the student dummy variable didn’t lead to a reduction in test error rate. Even though the variable may be statistically significant, the difference in model accuracy is tiny.

Problem 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 coeffcients in two diferent 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.

set.seed(1)

glm.fit <- glm(default ~ income + balance, data = Default, family = binomial)

summary(glm.fit)$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
boot.fn <- function(data, index) {
  fit <- glm(default ~ income + balance, data = data[index, ], family = binomial)
  return(coef(fit)[2:3])
}

set.seed(1)
boot.results <- replicate(1000, boot.fn(Default, sample(1:nrow(Default), replace = TRUE)))

boot.results <- t(boot.results)

bootstrap_se <- apply(boot.results, 2, sd)
names(bootstrap_se) <- c("income", "balance")
bootstrap_se
##       income      balance 
## 4.826770e-06 2.323302e-04

(a) Using the summary() and glm() functions, determine the estimated standard errors for the coeffcients associated with income and balance in a multiple logistic regression model that uses both predictors.

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) 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 coeffcient 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")])}

set.seed(1)
boot.fn(Default, sample(1:nrow(Default), 1000, replace = TRUE))
##       income      balance 
## 0.0000513686 0.0060944222

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

library(boot)

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

set.seed(1)

boot.results <- boot(data = Default, statistic = boot.fn, R = 1000)

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

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

The bootstrap estimates are very similar to those from the glm() function. This can be used as confirmation that the logistic model can be trusted and is consistent.

Problem 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)

mu_hat <- mean(Boston$medv)

print(paste("Estimated population mean of medv (µ̂):", round(mu_hat, 4)))
## [1] "Estimated population mean of medv (µ̂): 22.5328"

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

n <- nrow(Boston)
s <- sd(Boston$medv)

se_mu_hat <- s / sqrt(n)

print(paste("Standard error of µ̂:", round(se_mu_hat, 4)))
## [1] "Standard error of µ̂: 0.4089"

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

boot.fn <- function(data, index) {
  return(mean(data$medv[index]))
}

set.seed(1)

boot_results <- boot(data = Boston, statistic = boot.fn, R = 1000)

print(boot_results)
## 
## ORDINARY NONPARAMETRIC BOOTSTRAP
## 
## 
## Call:
## boot(data = Boston, statistic = boot.fn, R = 1000)
## 
## 
## Bootstrap Statistics :
##     original      bias    std. error
## t1* 22.53281 0.007650791   0.4106622

Both yielded similar results.

(d) Based on your bootstrap estimate from (c), provide a 95 % confdence interval for the mean of medv. Compare it to the results obtained using t.test(Boston$medv). Hint: You can approximate a 95 % confdence interval using the formula [ˆµ − 2SE(ˆµ), µˆ + 2SE(ˆµ)].

mu_hat <- mean(Boston$medv)
se_boot <- 0.4119  # from part (c)

ci_boot <- c(mu_hat - 2 * se_boot, mu_hat + 2 * se_boot)
print(paste("Bootstrap 95% CI for µ:", round(ci_boot[1], 4), "to", round(ci_boot[2], 4)))
## [1] "Bootstrap 95% CI for µ: 21.709 to 23.3566"
t_test_result <- t.test(Boston$medv)
print(t_test_result$conf.int)
## [1] 21.72953 23.33608
## attr(,"conf.level")
## [1] 0.95

Both confidence intervals are almost the same, telling us that the bootstrap method is consistent with parametric methods and the sample size is large enough.

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

mu_hat_med <- median(Boston$medv)

print(paste("Estimated population median of medv (µ̂_med):", mu_hat_med))
## [1] "Estimated population median of medv (µ̂_med): 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 fndings.

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

set.seed(1)

boot.median <- boot(data = Boston, statistic = boot.fn.median, R = 1000)

print(boot.median)
## 
## ORDINARY NONPARAMETRIC BOOTSTRAP
## 
## 
## Call:
## boot(data = Boston, statistic = boot.fn.median, R = 1000)
## 
## 
## Bootstrap Statistics :
##     original  bias    std. error
## t1*     21.2 0.02295   0.3778075

The standard error is 0.378, which is lower than the standard error of the mean. This tells us that median is a bit better.

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

mu_hat_0.1 <- quantile(Boston$medv, probs = 0.1)

print(paste("Estimated 10th percentile of medv (µ̂0.1):", mu_hat_0.1))
## [1] "Estimated 10th percentile of medv (µ̂0.1): 12.75"

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

boot.fn.p10 <- function(data, index) {
  return(quantile(data$medv[index], probs = 0.1))
}

set.seed(1)

boot.p10 <- boot(data = Boston, statistic = boot.fn.p10, R = 1000)

print(boot.p10)
## 
## ORDINARY NONPARAMETRIC BOOTSTRAP
## 
## 
## Call:
## boot(data = Boston, statistic = boot.fn.p10, R = 1000)
## 
## 
## Bootstrap Statistics :
##     original  bias    std. error
## t1*    12.75  0.0339   0.4767526

The standard error is 0.48, meaning that if we sampled from the population by the 10th percentile, estimated value would vary by ~$505.