Question 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(ISLR2)
## Warning: package 'ISLR2' was built under R version 4.4.2
set.seed(42)
fit <- glm(default ~ income + balance, data = Default, family = "binomial")
  1. 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.
  2. Fit a multiple logistic regression model using only the training observations.
  3. Obtain a prediction of default status for each individual inthe validation set by computing the posterior probability ofdefault for that individual, and classifying the individual to the default category if the posterior probability is greater than 0.5.
  4. Compute the validation set error, which is the fraction of the observations in the validation set that are misclassified.
train <- sample(nrow(Default), nrow(Default) / 2)
fit <- glm(default ~ income + balance, data = Default, family = "binomial", subset = train)
pred <- ifelse(predict(fit, newdata = Default[-train, ], type = "response") > 0.5, "Yes", "No")
table(pred, Default$default[-train])
##      
## pred    No  Yes
##   No  4817  110
##   Yes   20   53
mean(pred != Default$default[-train])
## [1] 0.026
  1. 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.
replicate(3, {
  train <- sample(nrow(Default), nrow(Default) / 2)
  fit <- glm(default ~ income + balance, data = Default, family = "binomial", subset = train)
  pred <- ifelse(predict(fit, newdata = Default[-train, ], type = "response") > 0.5, "Yes", "No")
  mean(pred != Default$default[-train])
})
## [1] 0.0260 0.0294 0.0258

The results obtained are variable and depend on the samples allocated to training vs. test.

  1. 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.
replicate(3, {
  train <- sample(nrow(Default), nrow(Default) / 2)
  fit <- glm(default ~ income + balance + student, data = Default, family = "binomial", subset = train)
  pred <- ifelse(predict(fit, newdata = Default[-train, ], type = "response") > 0.5, "Yes", "No")
  mean(pred != Default$default[-train])
})
## [1] 0.0278 0.0256 0.0250

Including student does not seem to make a substantial improvement to the test error.

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

The standard errors obtained by bootstrapping are β^1= 5.0e-6 and β^2= 2.3e-4.

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(x, i) {
  fit <- glm(default ~ income + balance, data = x[i, ], family = "binomial")
  coef(fit)[-1]
}

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(42)
boot(Default, boot.fn, R = 1000)
## 
## ORDINARY NONPARAMETRIC BOOTSTRAP
## 
## 
## Call:
## boot(data = Default, statistic = boot.fn, R = 1000)
## 
## 
## Bootstrap Statistics :
##         original       bias     std. error
## t1* 2.080898e-05 2.737444e-08 5.073444e-06
## t2* 5.647103e-03 1.176249e-05 2.299133e-04

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

The standard errors obtained by bootstrapping are similar to those estimated by glm.

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

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

fit <- glm(Direction ~ Lag1 + Lag2, data = Weekly, family = "binomial")

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

fit <- glm(Direction ~ Lag1 + Lag2, data = Weekly[-1, ], family = "binomial")

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?

predict(fit, newdata = Weekly[1, , drop = FALSE], type = "response") > 0.5
##    1 
## TRUE

Yes the observation was correctly classified

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

i.Fit a logistic regression model using all but the ith observation to predict Direction using Lag1 and Lag2

  1. Compute the posterior probability of the market moving up for the ith observation.

  2. Use the posterior probability for the ith observation in order to predict whether or not the market moves up.

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

error <- numeric(nrow(Weekly))
for (i in 1:nrow(Weekly)) {
  fit <- glm(Direction ~ Lag1 + Lag2, data = Weekly[-i, ], family = "binomial")
  p <- predict(fit, newdata = Weekly[i, , drop = FALSE], type = "response") > 0.5
  error[i] <- ifelse(p, "Down", "Up") == Weekly$Direction[i]
}
  1. Take the average of the n numbers obtained in (d) in order to obtain the LOOCV estimate for the test error. Comment on the results.
mean(error)
## [1] 0.4499541

The LOOCV test error rate is 45% which implies that our predictions are marginally more often correct than not.

Question 9

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

  1. Based on this data set, provide an estimate for the population mean of medv. Call this estimate ˆ µ.
(mu <- mean(Boston$medv))
## [1] 22.53281
  1. Provide an estimate of the standard error of ˆ µ. Interpret this result. Hint: We can compute the standard error of the sample mean bydividing the sample standard deviation by the square root of the number of observations.
sd(Boston$medv) / sqrt(length(Boston$medv))
## [1] 0.4088611
  1. Now estimate the standard error of ˆ µ using the bootstrap. How does this compare to your answer from (b)?
set.seed(42)
(bs <- boot(Boston$medv, function(v, i) mean(v[i]), 10000))
## 
## ORDINARY NONPARAMETRIC BOOTSTRAP
## 
## 
## Call:
## boot(data = Boston$medv, statistic = function(v, i) mean(v[i]), 
##     R = 10000)
## 
## 
## Bootstrap Statistics :
##     original      bias    std. error
## t1* 22.53281 0.002175751   0.4029139

The standard error using the bootstrap (0.403) is very close to that obtained from the formula above (0.409).

  1. 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(ˆ µ)].
se <- sd(bs$t)
c(mu - 2 * se, mu + 2 * se)
## [1] 21.72698 23.33863
  1. Based on this data set, provide an estimate, ˆ µmed, for the median value of medv in the population.
median(Boston$medv)
## [1] 21.2
  1. Wenowwouldlike 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(42)
boot(Boston$medv, function(v, i) median(v[i]), 10000)
## 
## ORDINARY NONPARAMETRIC BOOTSTRAP
## 
## 
## Call:
## boot(data = Boston$medv, statistic = function(v, i) median(v[i]), 
##     R = 10000)
## 
## 
## Bootstrap Statistics :
##     original   bias    std. error
## t1*     21.2 -0.01331   0.3744634

The estimated standard error of the median is 0.374. This is lower than the standard error of the mean.

  1. 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.)
quantile(Boston$medv, 0.1)
##   10% 
## 12.75
  1. Use the bootstrap to estimate the standard error of ˆ µ0.1. Comment on your findings.
set.seed(42)
boot(Boston$medv, function(v, i) quantile(v[i], 0.1), 10000)
## 
## ORDINARY NONPARAMETRIC BOOTSTRAP
## 
## 
## Call:
## boot(data = Boston$medv, statistic = function(v, i) quantile(v[i], 
##     0.1), R = 10000)
## 
## 
## Bootstrap Statistics :
##     original   bias    std. error
## t1*    12.75 0.013405    0.497298

We get a standard error of ~0.5. This is higher than the standard error of the median. Nevertheless the standard error is quite small, thus we can be fairly confidence about the value of the 10th percentile.