We now review k-fold cross-validation.
(a) Explain how k-fold cross-validation is implemented.
K-fold cross-validation involves randomly dividing the set of observations into k groups, or folds, of approximately equal size. The first fold is treated as a validation set and the rest act as a training set. The test error is then computed using the average of the the mean squared error estimates.
(b) What are the advantages and disadvantages of k-fold cross-validation relative to:
i. The validation set approach?
The main drawbacks of the validation set approach are that it can lead to overestimates of the test error rate and will also have high variability in the test error but it is simple and easy to implement.
ii. LOOCV?
The LOOCV approach has less bias and produces a less variable mean square error but will have a higher variance than k-fold CV and is computationally intensive.
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.
library(ISLR2)
attach(Default)
(a) Fit a logistic regression model that uses income and balance to predict default.
all_model <- glm(default ~ income + balance, data = Default, family = "binomial")
summary(all_model)
##
## Call:
## glm(formula = default ~ income + balance, family = "binomial",
## data = Default)
##
## Deviance Residuals:
## Min 1Q Median 3Q Max
## -2.4725 -0.1444 -0.0574 -0.0211 3.7245
##
## 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:
set.seed(1)
inTrain <- sample(1:nrow(Default), 0.8*nrow(Default))
default_train <- Default[inTrain,]
default_test <- Default[-inTrain,]
glm_model <-glm(default ~ income + balance, data = default_train, family = "binomial")
glm_probs <- predict(glm_model, default_test, type="response")
glm_pred <- factor(ifelse(glm_probs>=0.50, "Yes", "No"))
table(glm_pred, default_test$default)
##
## glm_pred No Yes
## No 1928 50
## Yes 2 20
mean(glm_pred != default_test$default)
## [1] 0.026
(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.
inTrain <- sample(1:nrow(Default), 0.8*nrow(Default))
default_train <- Default[inTrain,]
default_test <- Default[-inTrain,]
glm_model <-glm(default ~ income + balance, data = default_train, family = "binomial")
glm_probs <- predict(glm_model, default_test, type="response")
glm_pred <- factor(ifelse(glm_probs>=0.50, "Yes", "No"))
table(glm_pred, default_test$default)
##
## glm_pred No Yes
## No 1934 42
## Yes 6 18
mean(glm_pred != default_test$default)
## [1] 0.024
inTrain <- sample(1:nrow(Default), 0.8*nrow(Default))
default_train <- Default[inTrain,]
default_test <- Default[-inTrain,]
glm_model <-glm(default ~ income + balance, data = default_train, family = "binomial")
glm_probs <- predict(glm_model, default_test, type="response")
glm_pred <- factor(ifelse(glm_probs>=0.50, "Yes", "No"))
table(glm_pred, default_test$default)
##
## glm_pred No Yes
## No 1922 48
## Yes 5 25
mean(glm_pred != default_test$default)
## [1] 0.0265
inTrain <- sample(1:nrow(Default), 0.8*nrow(Default))
default_train <- Default[inTrain,]
default_test <- Default[-inTrain,]
glm_model <-glm(default ~ income + balance, data = default_train, family = "binomial")
glm_probs <- predict(glm_model, default_test, type="response")
glm_pred <- factor(ifelse(glm_probs>=0.50, "Yes", "No"))
table(glm_pred, default_test$default)
##
## glm_pred No Yes
## No 1915 56
## Yes 7 22
mean(glm_pred != default_test$default)
## [1] 0.0315
(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.
Comparing the model created in part(a) and this model created with the added dummy variable for student, shows that when adding the dummy variable for student, it makes income no longer significant. Although it is no longer significant it can be kept in the model as it does not seem to change much in terms of the test error rate.
inTrain <- sample(1:nrow(Default), 0.8*nrow(Default))
default_train <- Default[inTrain,]
default_test <- Default[-inTrain,]
glm_model2 <-glm(default ~ income + balance + student, data = default_train, family = "binomial")
glm_probs <- predict(glm_model2, default_test, type="response")
glm_pred <- factor(ifelse(glm_probs>=0.50, "Yes", "No"))
table(glm_pred, default_test$default)
##
## glm_pred No Yes
## No 1929 39
## Yes 12 20
mean(glm_pred != default_test$default)
## [1] 0.0255
summary(glm_model2)
##
## Call:
## glm(formula = default ~ income + balance + student, family = "binomial",
## data = default_train)
##
## Deviance Residuals:
## Min 1Q Median 3Q Max
## -2.2078 -0.1418 -0.0551 -0.0200 3.7496
##
## Coefficients:
## Estimate Std. Error z value Pr(>|z|)
## (Intercept) -1.105e+01 5.555e-01 -19.884 <2e-16 ***
## income 4.120e-06 9.116e-06 0.452 0.6513
## balance 5.867e-03 2.622e-04 22.374 <2e-16 ***
## studentYes -6.507e-01 2.622e-01 -2.482 0.0131 *
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## (Dispersion parameter for binomial family taken to be 1)
##
## Null deviance: 2387.5 on 7999 degrees of freedom
## Residual deviance: 1266.3 on 7996 degrees of freedom
## AIC: 1274.3
##
## Number of Fisher Scoring iterations: 8
detach(Default)
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.
library(ISLR2)
attach(Default)
(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)
fit.glm <- glm(default ~ income + balance, data = Default, family = "binomial")
summary(fit.glm)
##
## Call:
## glm(formula = default ~ income + balance, family = "binomial",
## data = Default)
##
## Deviance Residuals:
## Min 1Q Median 3Q Max
## -2.4725 -0.1444 -0.0574 -0.0211 3.7245
##
## 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) {return(coef(glm(default ~ balance + income, data = data, family = binomial, subset = index)))}
(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)
boot(Default, boot.fn, 100)
##
## ORDINARY NONPARAMETRIC BOOTSTRAP
##
##
## Call:
## boot(data = Default, statistic = boot.fn, R = 100)
##
##
## Bootstrap Statistics :
## original bias std. error
## t1* -1.154047e+01 8.556378e-03 4.122015e-01
## t2* 5.647103e-03 -4.116657e-06 2.226242e-04
## t3* 2.080898e-05 -3.993598e-07 4.186088e-06
(d) Comment on the estimated standard errors obtained using the glm() function and using your bootstrap function.
The standard errors obtained using the bootstrap function are 4.122015e-01, 2.226242e-04, and 4.186088e-06 while the standard errors obtained using the glm() function are 4.348e-01, 4.985e-06, 2.274e-04. As you can see, these standard errors are very similar.
detach(Default)
We will now consider the Boston housing data set, from the ISLR2 library.
library(ISLR2)
attach(Boston)
(a) Based on this data set, provide an estimate for the population mean of medv. Call this estimate ˆµ.
mean_medv <- mean(medv)
mean_medv
## [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.
std_mean <- sd(medv)/sqrt(length(medv))
std_mean
## [1] 0.4088611
(c) Now estimate the standard error of ˆµ using the bootstrap. How does this compare to your answer from (b)?
The standard error using bootstrap is 0.4106622 is similar to the standard error computed in (b) at 0.4088611.
library(boot)
set.seed(1)
boot.fn <- function(data, index) (return(mean(data[index])))
boot(medv, boot.fn, 1000)
##
## ORDINARY NONPARAMETRIC BOOTSTRAP
##
##
## Call:
## boot(data = medv, statistic = boot.fn, R = 1000)
##
##
## Bootstrap Statistics :
## original bias std. error
## t1* 22.53281 0.007650791 0.4106622
(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(ˆµ)].
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
CImean_medv <- c(22.5328 - 2 * 0.4106622, 22.5328 + 2 * 0.4106622)
CImean_medv
## [1] 21.71148 23.35412
(e) Based on this data set, provide an estimate, ˆµmed, for the median value of medv in the population.
median_medv = median(medv)
median_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.
The median of 21.2 calculated using bootstrap is the same as the median value computed in (e) and the standard error is 0.3923675.
boot_fn2 <- function(data,index)return(median(data[index]))
boot(medv, boot_fn2, 100)
##
## ORDINARY NONPARAMETRIC BOOTSTRAP
##
##
## Call:
## boot(data = medv, statistic = boot_fn2, R = 100)
##
##
## Bootstrap Statistics :
## original bias std. error
## t1* 21.2 -0.015 0.3530888
(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.)
tenth_hat <- quantile(medv, c(0.1))
tenth_hat
## 10%
## 12.75
(h) Use the bootstrap to estimate the standard error of ˆµ0.1. Comment on your findings.
Using bootstrap we estimated a tenth percentile of 12.75, which is the same as the tenth percentile of medv computed in (g), and the standard error is 0.4878177.
boot_fn3 = function(data, index) return(quantile(data[index], c(0.1)))
boot(medv,boot_fn3, 1000)
##
## ORDINARY NONPARAMETRIC BOOTSTRAP
##
##
## Call:
## boot(data = medv, statistic = boot_fn3, R = 1000)
##
##
## Bootstrap Statistics :
## original bias std. error
## t1* 12.75 0.00525 0.4917843
detach(Boston)