Predictive Modeling Homework 4

Author

Cheryl Chiu (wky301)

Published

March 26, 2025

Load libraries

library(ISLR)
library(ISLR2)
library(boot)

Exercise 3

We now review k-fold cross-validation.

(a) Explain how k-fold cross-validation is implemented.

🔴 Answer: K-fold cross-validation splits the data into k equal sized folds. For each each of k iterations, one fold is used as the test set and the remaining k-1 is used as the training set. The model is trained on the training set and tested on the test set, and this is repeated so that each part is used as the test set once. The test errors (MSE) from all rounds are averaged to give a final estimate of the model’s performance.

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

i. The validation set approach?

🔴 Answer: K-fold cross-validation uses every observation for both training and testing, this process makes it more reliable than ones that just rely on one random split. However, it require more computation to train more than once.

ii. LOOCV?

🔴 Answer: K-fold cross-validation is faster than LOOCV since LOOCV trains the model once for each observation. This makes LOOCV very time-consuming for large dataset. LOOCV often suffer from high variability since the training sets are almost identical. In contrast, k-fold cross-validation can offer a good balance by slightly increasing bias while reducing the variance.

Exercise 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)
data(Default)
model1 <- glm(default ~ income + balance, data = Default, family = binomial)
summary(model1)

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:

  1. Split the sample set into a training set and a validation set.
set.seed(1)
n <- nrow(Default)
train_indices <- sample(1:n, size = round(n/2))
train_set <- Default[train_indices, ]
validation_set <- Default[-train_indices, ]
  1. Fit a multiple logistic regression model using only the training observations.
model_train <- glm(default ~ income + balance, data = train_set, family = binomial)
  1. 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.
pred_prob <- predict(model_train, newdata = validation_set, type = "response")
pred_default <- ifelse(pred_prob > 0.5, "Yes", "No")
  1. Compute the validation set error, which is the fraction of the observations in the validation set that are misclassified.
actual_default <- validation_set$default
validation_error <- mean(pred_default != actual_default)
validation_error
[1] 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.

set.seed(1)
error_rates <- numeric(3)

for(i in 1:3){
  train_indices <- sample(1:n, size = round(n/2))
  train_set <- Default[train_indices, ]
  validation_set <- Default[-train_indices, ]
  model_train <- glm(default ~ income + balance, data = train_set, family = binomial)
  pred_prob <- predict(model_train, newdata = validation_set, type = "response")
  pred_default <- ifelse(pred_prob > 0.5, "Yes", "No")
  error_rates[i] <- mean(pred_default != validation_set$default)
}

error_rates
[1] 0.0254 0.0274 0.0244

🔴 Answer: The error rates are 0.0254, 0.0274, and 0.0244. The similar error rates indicate that the model performs consistent across different random splits of the data.

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

set.seed(1)
train_indices <- sample(1:n, size = round(n/2))
train_set <- Default[train_indices, ]
validation_set <- Default[-train_indices, ]

model_student <- glm(default ~ income + balance + student, data = train_set, family = binomial)

pred_prob_student <- predict(model_student, newdata = validation_set, type = "response")
pred_default_student <- ifelse(pred_prob_student > 0.5, "Yes", "No")

validation_error_student <- mean(pred_default_student != validation_set$default)
validation_error_student
[1] 0.026

🔴 Answer: The validation error rate of 0.026 indicates that adding the student predictor does not significantly improve predictive accuracy.

Exercise 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 esti- mated standard errors for the coefficients associated with income and balance in a multiple logistic regression model that uses both predictors.

set.seed(1)
model <- glm(default ~ income + balance, data = Default, family = binomial)
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 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 the logistic regression model on the subset defined by index
  fit <- glm(default ~ income + balance, data = data, family = binomial, subset = index)
  # Return coefficients for income and balance
  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)
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.

🔴 Answer: The standard errors from the glm() output (4.985e-06 for income and 2.274e-04 for balance) are similar to bootstrap’s result (4.866e-06 for income and 2.299e-04 for balance). The analytic standard error estimates are reliable. Both methods provide a good assessment of the variability of the coefficient estimates.

Exercise 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 μˆ.

data(Boston)
mu_hat <- mean(Boston$medv)
mu_hat
[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.

n <- nrow(Boston)
se_mu <- sd(Boston$medv) / 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)?

boot.mean <- function(data, indices) {
  d <- data[indices, ]
  return(mean(d$medv))
}
boot_results <- boot(data = Boston, statistic = 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.0109415    0.414028

🔴 Answer: The bootstrap standard error (0.414) is very close to the analytic estimate ( 0.409) in part b. The sample distribution of medv behaves very regularly.

(d) Based on your bootstrap estimate from (c), provide a 95 % con- fidence 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(μˆ)].

se_boot <- sd(boot_results$t)
ci_boot <- c(mu_hat - 2 * se_boot, mu_hat + 2 * se_boot)
ci_boot
[1] 21.70475 23.36086
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 

🔴 Answer: The bootstrap 95% confidence interval for μˆ is [21.70, 23.36] and the result is ssimilar to the t-test interval of [21.73, 23.34]. B

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

med_hat <- median(Boston$medv)
med_hat
[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.

boot.median <- function(data, indices) {
  d <- data[indices, ]
  return(median(d$medv))
}
boot_median_results <- boot(data = Boston, statistic = boot.median, R = 1000)
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.02095   0.3707169

🔴 Answer: The bootstrap results show that the estimated median is about 21.2, with almost no bias and a standard error of roughly 0.37. This means that if we repeated the sampling, the median would likely stay close to 21.2, suggesting our median estimate is stable and reliable.

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

perc10 <- quantile(Boston$medv, 0.1)
perc10
  10% 
12.75 

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

boot.percentile <- function(data, indices) {
  d <- data[indices, ]
  return(as.numeric(quantile(d$medv, 0.1)))
}

boot_perc10_results <- boot(data = Boston, statistic = boot.percentile, R = 1000)
boot_perc10_results

ORDINARY NONPARAMETRIC BOOTSTRAP


Call:
boot(data = Boston, statistic = boot.percentile, R = 1000)


Bootstrap Statistics :
    original  bias    std. error
t1*    12.75 0.02795   0.5077737

🔴 Answer: The bootstrap results for the tenth percentile show an estimate of 12.75 with a very small bias (about 0.028) and a standard error of roughly 0.51. This indicates that if we repeated the sampling process, the tenth percentile would typically vary by about half a unit from 12.75. In comparison, the median has a lower standard error (around 0.37), making it the most stable estimate compared to the mean and the percentile estimates.