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)
model_a <- glm(default~income+balance, data = Default, family=binomial)
summary(model_a)
## 
## 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), nrow(Default) / 2)

train <- Default[train_indices, ]
validation <- Default[-train_indices, ]

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

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

probs <- predict(model_b, newdata = validation, type = "response")
preds <- 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.

mean(preds != validation$default)
## [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(2)
train1 <- sample(1:nrow(Default), nrow(Default) / 2)
model1 <- glm(default ~ income + balance, data = Default[train1, ], family = "binomial")
preds1 <- ifelse(predict(model1, newdata = Default[-train1, ], type = "response") > 0.5, "Yes", "No")
error1 <- mean(preds1 != Default[-train1, ]$default)

set.seed(3)
train2 <- sample(1:nrow(Default), nrow(Default) / 2)
model2 <- glm(default ~ income + balance, data = Default[train2, ], family = "binomial")
preds2 <- ifelse(predict(model2, newdata = Default[-train2, ], type = "response") > 0.5, "Yes", "No")
error2 <- mean(preds2 != Default[-train2, ]$default)

set.seed(4)
train3 <- sample(1:nrow(Default), nrow(Default) / 2)
model3 <- glm(default ~ income + balance, data = Default[train3, ], family = "binomial")
preds3 <- ifelse(predict(model3, newdata = Default[-train3, ], type = "response") > 0.5, "Yes", "No")
error3 <- mean(preds3 != Default[-train3, ]$default)

error1
## [1] 0.0238
error2
## [1] 0.0264
error3
## [1] 0.0256

These validation errors represent the test error rates, i.e., the fraction of misclassified observations on the validation sets across three random splits.

The error rates are consistently low, ranging between 2.38% and 2.64%, which indicates that the logistic regression model using income and balance is performing quite well in predicting default.

The small variation across the three trials (about ±0.0013) suggests that the model’s performance is stable and not overly sensitive to how the data is split into training and validation sets.

This stability increases our confidence in the generalization ability of the model — i.e., its ability to perform well on unseen data.

In short, the model demonstrates reliable and robust classification performance with minimal variance across different validation 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 dummyvariable for student leads to a reduction in the test error rate.

set.seed(1)
train4 <- sample(1:nrow(Default), nrow(Default) / 2)

model_d <- glm(default ~ income + balance + student, data = Default[train4, ], family = "binomial")

preds_d <- ifelse(predict(model_d, newdata = Default[-train4, ], type = "response") > 0.5, "Yes", "No")

error_d <- mean(preds_d != Default[-train4, ]$default)
error_d
## [1] 0.026

Including the dummy variable for student did not lead to a meaningful reduction in the test error rate. In fact:

The test error with student (0.0260) is very similar to — and in one case slightly higher than — the errors from the model without it.

This suggests that student status does not provide much additional predictive power for default beyond what is already captured by income and balance.

It’s likely that the variable student is not strongly associated with default after controlling for income and balance. Any effect it has may already be accounted for by the other two predictors.

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

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

summary(model_6a)$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, family = "binomial", subset = index)
  
  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.

library(boot)

set.seed(1)

boot_results <- boot(data = Default, statistic = boot.fn, R = 100)

boot_results
## 
## ORDINARY NONPARAMETRIC BOOTSTRAP
## 
## 
## Call:
## boot(data = Default, statistic = boot.fn, R = 100)
## 
## 
## Bootstrap Statistics :
##         original        bias     std. error
## t1* 2.080898e-05 -3.993598e-07 4.186088e-06
## t2* 5.647103e-03 -4.116657e-06 2.226242e-04

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

The standard errors obtained using the bootstrap method are very similar to those computed using the glm() function’s internal formula:

For income, the glm() SE is 4.99e-06, while the bootstrap SE is slightly smaller at 4.19e-06.

For balance, the glm() SE is 2.27e-04, and the bootstrap SE is 2.23e-04.

These results are consistent with what we would expect when the model assumptions (e.g., binomial distribution of the response, large enough sample size) hold reasonably well:

The small differences arise because the glm() standard errors are model-based and rely on theoretical asymptotic approximations.

The bootstrap standard errors are empirical, relying on resampling the observed data to directly estimate variability in the coefficients.

In this case, the close agreement between the two methods suggests that the assumptions used by glm() are appropriate, and the model is well-behaved.

7. In Sections 5.3.2 and 5.3.3, we saw that the cv.glm() function can be used in order to compute the LOOCV test error estimate. Alternatively, one could compute those quantities using just the glm() and predict.glm() functions, and a for loop. You will now take this approach in order to compute the LOOCV error for a simple logistic regression model on the Weekly data set. Recall that in the context of classification problems, the LOOCV error is given in (5.4).

data("Weekly")
str(Weekly)
## 'data.frame':    1089 obs. of  9 variables:
##  $ Year     : num  1990 1990 1990 1990 1990 1990 1990 1990 1990 1990 ...
##  $ Lag1     : num  0.816 -0.27 -2.576 3.514 0.712 ...
##  $ Lag2     : num  1.572 0.816 -0.27 -2.576 3.514 ...
##  $ Lag3     : num  -3.936 1.572 0.816 -0.27 -2.576 ...
##  $ Lag4     : num  -0.229 -3.936 1.572 0.816 -0.27 ...
##  $ Lag5     : num  -3.484 -0.229 -3.936 1.572 0.816 ...
##  $ Volume   : num  0.155 0.149 0.16 0.162 0.154 ...
##  $ Today    : num  -0.27 -2.576 3.514 0.712 1.178 ...
##  $ Direction: Factor w/ 2 levels "Down","Up": 1 1 2 2 2 1 2 2 2 1 ...

a). Fit a logistic regression model that predicts Direction using Lag1 and Lag2.

model_7a <- glm(Direction ~ Lag1 + Lag2, data = Weekly, family = "binomial")
summary(model_7a)
## 
## Call:
## glm(formula = Direction ~ Lag1 + Lag2, family = "binomial", data = Weekly)
## 
## Coefficients:
##             Estimate Std. Error z value Pr(>|z|)    
## (Intercept)  0.22122    0.06147   3.599 0.000319 ***
## Lag1        -0.03872    0.02622  -1.477 0.139672    
## Lag2         0.06025    0.02655   2.270 0.023232 *  
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## (Dispersion parameter for binomial family taken to be 1)
## 
##     Null deviance: 1496.2  on 1088  degrees of freedom
## Residual deviance: 1488.2  on 1086  degrees of freedom
## AIC: 1494.2
## 
## Number of Fisher Scoring iterations: 4

b). Fit a logistic regression model that predicts Direction using Lag1 and Lag2 using all but the first observation.

model_7b <- glm(Direction ~ Lag1 + Lag2, data = Weekly[-1, ], family = "binomial")
summary(model_7b)
## 
## Call:
## glm(formula = Direction ~ Lag1 + Lag2, family = "binomial", data = Weekly[-1, 
##     ])
## 
## Coefficients:
##             Estimate Std. Error z value Pr(>|z|)    
## (Intercept)  0.22324    0.06150   3.630 0.000283 ***
## Lag1        -0.03843    0.02622  -1.466 0.142683    
## Lag2         0.06085    0.02656   2.291 0.021971 *  
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## (Dispersion parameter for binomial family taken to be 1)
## 
##     Null deviance: 1494.6  on 1087  degrees of freedom
## Residual deviance: 1486.5  on 1085  degrees of freedom
## AIC: 1492.5
## 
## Number of Fisher Scoring iterations: 4

c). Use the model from (b) to predict the direction of the first observation. You can do this by predicting that the first observation will go up if P(Direction = “Up”|Lag1, Lag2) > 0.5. Was this observation correctly classified?

prob1 <- predict(model_7b, newdata = Weekly[1, ], type = "response")

pred1 <- ifelse(prob1 > 0.5, "Up", "Down")

actual1 <- Weekly$Direction[1]
pred1
##    1 
## "Up"
actual1
## [1] Down
## Levels: Down Up
correct <- pred1 == actual1
correct
## [1] FALSE

The model incorrectly classified the first observation. It predicted the market would go up, but in reality, it went down.

d). Write a for loop from i =1to i = n, where n is the number of observations in the data set, that performs each of the following steps:

  1. Fit a logistic regression model using all but the ith observation to predict Direction using Lag1 and Lag2.
  2. Compute the posterior probability of the market moving up for the ith observation.
  3. Use the posterior probability for the ith observation in order to predict whether or not the market moves up.
  4. Determine whether or not an error was made in predicting the direction for the ith observation. If an error was made, then indicate this as a 1, and otherwise indicate it as a 0.
n <- nrow(Weekly)
errors <- rep(NA, n)

for (i in 1:n) {
  # i. Fit model
  fit <- glm(Direction ~ Lag1 + Lag2, data = Weekly[-i, ], family = "binomial")
  
  # ii. Posterior probability
  prob <- predict(fit, newdata = Weekly[i, ], type = "response")
  
  # iii. Classification
  pred <- ifelse(prob > 0.5, "Up", "Down")
  
  # iv. Record error
  actual <- Weekly$Direction[i]
  errors[i] <- ifelse(pred != actual, 1, 0)
}

e). Take the average of the n numbers obtained in (d)iv in order to obtain the LOOCV estimate for the test error. Comment on the results.

loocv_error <- mean(errors)
loocv_error
## [1] 0.4499541

This means that the logistic regression model misclassified about 44.99% of the observations when evaluated using LOOCV, which tests each point using a model trained on all other points.

In practical terms: out of 1089 weekly market observations, the model predicted the direction of the market incorrectly about 490 times.

Is this good performance? Not really — for a binary classification task where the response is either Up or Down, a random guess would have an expected error rate of around 50%. Your model:

Achieved ~45% error, which is only slightly better than random guessing.

Shows that Lag1 and Lag2 alone do not provide strong predictive power for the market’s direction.

9. We will now consider the Boston housing data set, from the ISLR2 library.

library(ISLR2)
library(boot)

data("Boston")
set.seed(1)

str(Boston)
## 'data.frame':    506 obs. of  13 variables:
##  $ crim   : num  0.00632 0.02731 0.02729 0.03237 0.06905 ...
##  $ zn     : num  18 0 0 0 0 0 12.5 12.5 12.5 12.5 ...
##  $ indus  : num  2.31 7.07 7.07 2.18 2.18 2.18 7.87 7.87 7.87 7.87 ...
##  $ chas   : int  0 0 0 0 0 0 0 0 0 0 ...
##  $ nox    : num  0.538 0.469 0.469 0.458 0.458 0.458 0.524 0.524 0.524 0.524 ...
##  $ rm     : num  6.58 6.42 7.18 7 7.15 ...
##  $ age    : num  65.2 78.9 61.1 45.8 54.2 58.7 66.6 96.1 100 85.9 ...
##  $ dis    : num  4.09 4.97 4.97 6.06 6.06 ...
##  $ rad    : int  1 2 2 3 3 3 5 5 5 5 ...
##  $ tax    : num  296 242 242 222 222 222 311 311 311 311 ...
##  $ ptratio: num  15.3 17.8 17.8 18.7 18.7 18.7 15.2 15.2 15.2 15.2 ...
##  $ lstat  : num  4.98 9.14 4.03 2.94 5.33 ...
##  $ medv   : num  24 21.6 34.7 33.4 36.2 28.7 22.9 27.1 16.5 18.9 ...

a). Based on this data set, provide an estimate for the population mean of medv. Call this estimate ˆ µ.

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.

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

This tells us the typical variation we might expect in the sample mean if we repeatedly drew random samples of the same size from the population. If we were to repeatedly draw random samples of the same size from the Boston population and compute the mean medv (median house value) for each sample, the standard deviation of those means would be approximately 0.41.

It tells us how precise our estimate of the population mean is.

A smaller SE means more confidence in the sample mean being close to the true population mean. Since the standard deviation of medv is much larger (around 9.2), the SE is small in comparison, meaning the sample mean is a very stable estimator with relatively low variability.

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

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

boot_mean <- boot(data = Boston$medv, statistic = boot.fn.mean, R = 1000)
boot_mean
## 
## ORDINARY NONPARAMETRIC BOOTSTRAP
## 
## 
## Call:
## boot(data = Boston$medv, statistic = boot.fn.mean, R = 1000)
## 
## 
## Bootstrap Statistics :
##     original      bias    std. error
## t1* 22.53281 0.007650791   0.4106622
se_mu_bootstrap <- sd(boot_mean$t)
se_mu_bootstrap
## [1] 0.4106622

Comparison and Interpretation The two standard error estimates are extremely close — the difference is only about 0.0018.

This small difference indicates that the model-based formula in 9b is working very well, likely because:

The sample size (n = 506) is large enough for the Central Limit Theorem to hold.

The sample isn’t excessively skewed or heavy-tailed in a way that would mislead the parametric formula.

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(ˆ µ)].

ci_boot <- c(mu_hat - 2 * se_mu_bootstrap, mu_hat + 2 * se_mu_bootstrap)
ci_boot
## [1] 21.71148 23.35413
t.test(Boston$medv)$conf.int
## [1] 21.72953 23.33608
## attr(,"conf.level")
## [1] 0.95

Comparison and Interpretation: The two intervals are very close — differing only slightly at both the lower and upper bounds (within ~0.02 units).

The bootstrap CI is very slightly wider than the one from t.test():

Bootstrap width: 23.35413 − 21.71148 = 1.64265

t.test() width: 23.33608 − 21.72953 = 1.60655

Both intervals capture the same central location, centered around the sample mean (~22.5).

The t-test CI is based on the assumption that the sample mean follows a t-distribution — which is appropriate when:

The sample size is moderate to large, and

The population distribution is reasonably normal (which seems to hold for medv).

The bootstrap CI is more flexible and data-driven, relying on resampling rather than theoretical distributions.

In this case, the similarity between the two CIs suggests that the theoretical assumptions underlying the t-test are valid, and the sampling distribution of the mean is approximately normal.

The slightly wider bootstrap CI reflects its non-parametric nature, which doesn’t assume a specific distribution and may be slightly more conservative in borderline cases.

e). Based on this data set, provide an estimate, ˆ µ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 ˆ µ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) {
  return(median(data[index]))
}

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

se_median_bootstrap <- sd(boot_median$t)
se_median_bootstrap
## [1] 0.3770241

This result tells us that if we repeatedly drew random samples (with replacement) from the Boston housing data and computed the median of medv each time, the standard deviation of those medians would be approximately 0.377.

The sample median is a stable and reliable estimator of the population median, with moderate variability — slightly less than half a thousand dollars.

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_p10_hat <- quantile(Boston$medv, 0.1)
mu_p10_hat
##   10% 
## 12.75

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

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

boot_p10 <- boot(data = Boston$medv, statistic = boot.fn.p10, R = 1000)
se_p10_bootstrap <- sd(boot_p10$t)
se_p10_bootstrap
## [1] 0.4925766

Interpretation: This value means that if we were to repeatedly sample (with replacement) from the Boston housing dataset and calculate the 10th percentile each time, the standard deviation of those estimates would be about 0.493 (in thousands of dollars).

The 10th percentile estimate is subject to more variability than the mean or median, with a standard error nearly 0.5.

The SE of ≈ 0.493 suggests that the estimate of the 10th percentile is less stable than the mean or median.

However, using the bootstrap provides a reliable, distribution-free way to assess its uncertainty.

This kind of analysis is especially important when dealing with inequality, low-income housing, or affordable housing analysis, where lower-percentile values (like the 10th percentile of medv) may drive decision-making.