Problem 3

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

We divide the data set into K different parts. Then remove the first part, fit the model into remaining K-1 parts, and see how good the predictions are on the left out part. By averaging the K different MSE’s we get an estimated validation error rate for new observations.

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

i. The validation set approach?

K-Fold has lower variability than validation set and all the data is used for the train and test models. The validation approach is easier to understand and has a computational advantage.

ii. LOOCV?

K-fold is less computationally demanding and has more bias than LOOCV, however LOOCV has a higher variance.

Problem 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)
library(MASS)
library(dplyr)
library(caret)
library(ggplot2)
library(rmarkdown)
attach(Default)
log_def <- glm(default ~ income + balance, data = Default, family = "binomial")
summary(log_def)
## 
## 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: i. Split the sample set into a training set and a validation set. 5.4 Exercises 199

set.seed(1, sample.kind = "Rounding")
index <- createDataPartition(y = Default$default, p = 0.7, list = F)
train <- Default[index, ]
test <- Default[-index, ]
nrow(train) / nrow(Default)
## [1] 0.7001

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

log_def_2 <- glm(default ~ income + balance, data = train, family = "binomial")
summary(log_def_2)
## 
## Call:
## glm(formula = default ~ income + balance, family = "binomial", 
##     data = train)
## 
## Deviance Residuals: 
##     Min       1Q   Median       3Q      Max  
## -2.4416  -0.1434  -0.0582  -0.0214   3.7176  
## 
## Coefficients:
##               Estimate Std. Error z value Pr(>|z|)    
## (Intercept) -1.144e+01  5.128e-01 -22.300  < 2e-16 ***
## income       1.932e-05  5.958e-06   3.243  0.00118 ** 
## balance      5.601e-03  2.673e-04  20.956  < 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: 2050.6  on 7000  degrees of freedom
## Residual deviance: 1101.2  on 6998  degrees of freedom
## AIC: 1107.2
## 
## Number of Fisher Scoring iterations: 8

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.

test_pred <- factor(ifelse(predict(log_def_2, newdata = test, type = "response") > 0.5, "Yes", "No"))
test_pred[1:10]
##  2  3  9 15 31 33 35 38 41 44 
## No No No No No No No No No No 
## Levels: No Yes

iv. Compute the validation set error, which is the fraction of the observations in the validation set that are misclassified.

round(mean(test$default != test_pred), 5)
## [1] 0.02701

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

log_def_errors <- c()
log_def_errors[1] <- mean(test$default != test_pred)
set.seed(1, sample.kind = "Rounding")
for (i in 2:4) { index <- createDataPartition(y = Default$default, p = 0.7, list = F)
train <- Default[index, ]
test <- Default[-index, ]
log_def <- glm(default ~ income + balance, data = train, family = "binomial")
test_pred <- factor(ifelse(predict(log_def, newdata = test, type = "response") > 0.5, "Yes", "No"))
log_def_errors[i] <- mean(test$default != test_pred)
}
round(log_def_errors, 5)
## [1] 0.02701 0.02701 0.02734 0.02834

Average error is .02701

(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(3, sample.kind = "Rounding")
index <- createDataPartition(y = Default$default, p = 0.7, list = F)
train <- Default[index, ]
test <- Default[-index, ]
log_def <- glm(default ~ ., data = train, family = "binomial")
summary(log_def)
## 
## Call:
## glm(formula = default ~ ., family = "binomial", data = train)
## 
## Deviance Residuals: 
##     Min       1Q   Median       3Q      Max  
## -2.4693  -0.1380  -0.0536  -0.0195   3.7531  
## 
## Coefficients:
##               Estimate Std. Error z value Pr(>|z|)    
## (Intercept) -1.087e+01  5.831e-01 -18.641   <2e-16 ***
## studentYes  -7.208e-01  2.799e-01  -2.575    0.010 *  
## balance      5.773e-03  2.793e-04  20.667   <2e-16 ***
## income       1.313e-06  9.642e-06   0.136    0.892    
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## (Dispersion parameter for binomial family taken to be 1)
## 
##     Null deviance: 2050.6  on 7000  degrees of freedom
## Residual deviance: 1092.2  on 6997  degrees of freedom
## AIC: 1100.2
## 
## Number of Fisher Scoring iterations: 8
test_pred <- factor(ifelse(predict(log_def, newdata = test, type = "response") > 0.5, "Yes", "No"))
round(mean(test$default != test_pred), 5)
## [1] 0.02534

The error for this model is less than the previous error. Lower than 3 of the 4.

Problem 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)
glm.fit = glm(default ~ income + balance, data = Default, family = binomial)
summary(glm.fit)
## 
## 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 ~ income + balance, 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, 50)
## 
## ORDINARY NONPARAMETRIC BOOTSTRAP
## 
## 
## Call:
## boot(data = Default, statistic = boot.fn, R = 50)
## 
## 
## Bootstrap Statistics :
##          original        bias     std. error
## t1* -1.154047e+01  1.181200e-01 4.202402e-01
## t2*  2.080898e-05 -5.466926e-08 4.542214e-06
## t3*  5.647103e-03 -6.974834e-05 2.282819e-04

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

The estimated standard errors are

Problem 9

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

library(ISLR)
library(MASS)
library(dplyr)
library(caret)
library(ggplot2)
library(rmarkdown)
attach(Boston)

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

mean(Boston$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.

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(vector, index) {mean(vector[index])}
set.seed(1, sample.kind = "Rounding")
(boot_results <- boot(data = Boston$medv, statistic = boot.fn, R = 1000))
## 
## ORDINARY NONPARAMETRIC BOOTSTRAP
## 
## 
## Call:
## boot(data = Boston$medv, statistic = boot.fn, R = 1000)
## 
## 
## Bootstrap Statistics :
##     original      bias    std. error
## t1* 22.53281 0.008517589   0.4119374

The standard error for (b) was lower than this one.

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

boot_results_SE <- sd(boot_results$t)
round(c(mean(Boston$medv) - 2*boot_results_SE, mean(Boston$medv) + 2*boot_results_SE), 4)
## [1] 21.7089 23.3567
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

The results from (c) falls in between the results we got in (d)

(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(vector, index) {median(vector[index])}
set.seed(1, sample.kind = "Rounding")
(boot_results <- boot(data = Boston$medv, statistic = boot.fn, R = 1000))
## 
## ORDINARY NONPARAMETRIC BOOTSTRAP
## 
## 
## Call:
## boot(data = Boston$medv, statistic = boot.fn, R = 1000)
## 
## 
## Bootstrap Statistics :
##     original   bias    std. error
## t1*     21.2 -0.01615   0.3801002

The standard error is very small compared to the estimate from (e)

(g) Based on this data set, provide an estimate for the tenth percentile of medv in Boston suburbs. 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(vector, index) {
  quantile(vector[index], 0.1)
}

set.seed(1, sample.kind = "Rounding")

(boot_results <- boot(data = Boston$medv, statistic = boot.fn, R = 1000))
## 
## ORDINARY NONPARAMETRIC BOOTSTRAP
## 
## 
## Call:
## boot(data = Boston$medv, statistic = boot.fn, R = 1000)
## 
## 
## Bootstrap Statistics :
##     original  bias    std. error
## t1*    12.75 0.01005    0.505056

The results were larger than \(\mu_{0.1}\)