Assignment 4

Author

Christian Rivera

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

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

Split data into k parts. Train on k−1, test on 1. Repeat k times. Average the errors.

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

i. The validation set approach?

More efficient use of data
More stable error estimate
Slower to run

ii. LLOOCV?

Less variance
Faster to compute
Slightly more bias

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(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) 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)
train <- sample(nrow(Default), nrow(Default) / 2)
train_set <- Default[train, ]
test_set <- Default[-train, ]

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

model_train <- glm(default ~ income + balance, data = train_set, 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_train, test_set, type = "response")
pred <- 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 <- test_set$default
mean(pred != actual)
[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(nrow(Default), nrow(Default) / 2)
model1 <- glm(default ~ income + balance, data = Default, subset = train1, family = binomial)
probs1 <- predict(model1, Default[-train1, ], type = "response")
pred1 <- ifelse(probs1 > 0.5, "Yes", "No")
actual1 <- Default$default[-train1]
mean(pred1 != actual1)
[1] 0.0238
set.seed(3)
train2 <- sample(nrow(Default), nrow(Default) / 2)
model2 <- glm(default ~ income + balance, data = Default, subset = train2, family = binomial)
probs2 <- predict(model2, Default[-train2, ], type = "response")
pred2 <- ifelse(probs2 > 0.5, "Yes", "No")
actual2 <- Default$default[-train2]
mean(pred2 != actual2)
[1] 0.0264
set.seed(4)
train3 <- sample(nrow(Default), nrow(Default) / 2)
model3 <- glm(default ~ income + balance, data = Default, subset = train3, family = binomial)
probs3 <- predict(model3, Default[-train3, ], type = "response")
pred3 <- ifelse(probs3 > 0.5, "Yes", "No")
actual3 <- Default$default[-train3]
mean(pred3 != actual3)
[1] 0.0256

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

set.seed(1)
train <- sample(nrow(Default), nrow(Default) / 2)
model_student <- glm(default ~ income + balance + student, data = Default, subset = train, family = binomial)
probs_student <- predict(model_student, Default[-train, ], type = "response")
pred_student <- ifelse(probs_student > 0.5, "Yes", "No")
actual_student <- Default$default[-train]
mean(pred_student != actual_student)
[1] 0.026

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.

  1. 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 <- 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) {
  coef(glm(default ~ income + balance, data = data, family = binomial, subset = index))
}
boot.fn(Default, 1:10000)
  (Intercept)        income       balance 
-1.154047e+01  2.080898e-05  5.647103e-03 

(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(Default, boot.fn, 500)

ORDINARY NONPARAMETRIC BOOTSTRAP


Call:
boot(data = Default, statistic = boot.fn, R = 500)


Bootstrap Statistics :
         original        bias     std. error
t1* -1.154047e+01 -2.298134e-02 4.212334e-01
t2*  2.080898e-05 -2.053140e-07 5.184890e-06
t3*  5.647103e-03  1.678038e-05 2.178846e-04

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

glm() standard errors: income: 4.985e-06 balance: 2.274e-04

bootstrap() standard errors (from output): income: 5.1489e-06 balance: 2.1784e-04 Bootstrap confirms the glm() estimates. Slight variation is expected.

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

Attaching package: 'ISLR2'
The following objects are masked from 'package:ISLR':

    Auto, Credit
mean(Boston$medv)
[1] 22.53281

(b) Provide an estimate of the standard error of µˆ. Interpret this result.

sd(Boston$medv) / sqrt(length(Boston$medv))
[1] 0.4088611

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

boot.fn <- function(data, index) {
  mean(data[index])
}
set.seed(1)
boot(Boston$medv, boot.fn, 500)

ORDINARY NONPARAMETRIC BOOTSTRAP


Call:
boot(data = Boston$medv, statistic = boot.fn, R = 500)


Bootstrap Statistics :
    original      bias    std. error
t1* 22.53281 0.004967589   0.4265264

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

c(22.53 - 2 * 0.39, 22.53 + 2 * 0.39)
[1] 21.75 23.31
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 

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

median(Boston$medv)
[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 <- function(data, index) {
  median(data[index])
}
set.seed(1)
boot(Boston$medv, boot.fn, 500)

ORDINARY NONPARAMETRIC BOOTSTRAP


Call:
boot(data = Boston$medv, statistic = boot.fn, R = 500)


Bootstrap Statistics :
    original  bias    std. error
t1*     21.2  0.0022   0.3940885

Median is 21.2 with a standard error of 0.39. The 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.)

quantile(Boston$medv, 0.1)
  10% 
12.75 

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

boot.fn <- function(data, index) {
  quantile(data[index], 0.1)
}
set.seed(1)
boot(Boston$medv, boot.fn, 500)

ORDINARY NONPARAMETRIC BOOTSTRAP


Call:
boot(data = Boston$medv, statistic = boot.fn, R = 500)


Bootstrap Statistics :
    original  bias    std. error
t1*    12.75  0.0184   0.5147634