Chapter 05 (page 197): 3, 5, 6, 9

Problem 3

We now review k-fold cross-validation.
(a) Explain how k-fold cross-validation is implemented.
“This approach 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 method is fit on the remaining \(k − 1\) folds. The mean squared error, MSE, is then computed on the observations in the held-out fold. This procedure is repeated k times; each time, a different group of observations is treated as a validation set.”

(b) What are the advantages and disadvantages of k-fold crossvalidation relative to:
“…but potentially more important advantage of k-fold CV is that it often gives more accurate estimates of the test error rate than does LOOCV. This has to do with a bias-variance trade-off.”
i. The validation set approach?
A disadvantages of the validation set approach relative to \(k-fold\) cross-validation is the validation estimate of the test error rate can be highly variable (depends on which observations are included in the training/validation set). Another disadvantage is that only a subset of the observations are used to fit the model, so the validation set error may overestimate the test error rate for the model fit on the entire data set.
ii. LOOCV?
“The most obvious advantage is computational. \(LOOCV\) requires fitting the statistical learning method \(n\) times. This has the potential to be computationally expensive (except for linear models fit by least squares, in which case formula (5.2) can be used).”

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)
attach(Default)
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) 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 <- sample(dim(Default)[1], dim(Default)[1] / 2)

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

glm.fit1 <- glm(default ~ income + balance, data = Default, subset = train, family = binomial)
summary(glm.fit1)
## 
## Call:
## glm(formula = default ~ income + balance, family = binomial, 
##     data = Default, subset = train)
## 
## Deviance Residuals: 
##     Min       1Q   Median       3Q      Max  
## -2.5830  -0.1428  -0.0573  -0.0213   3.3395  
## 
## Coefficients:
##               Estimate Std. Error z value Pr(>|z|)    
## (Intercept) -1.194e+01  6.178e-01 -19.333  < 2e-16 ***
## income       3.262e-05  7.024e-06   4.644 3.41e-06 ***
## balance      5.689e-03  3.158e-04  18.014  < 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: 1523.8  on 4999  degrees of freedom
## Residual deviance:  803.3  on 4997  degrees of freedom
## AIC: 809.3
## 
## 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.

probs <- predict.glm(glm.fit1, newdata = Default[-train, ], type = "response")
pred.glm <- rep("No", length(probs))
pred.glm[probs > 0.5] <- "Yes"

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

mean(pred.glm != Default[-train, ]$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.

# split the data
train <- sample(dim(Default)[1], dim(Default)[1] / 2)
# fit the model
glm.fit2 <- glm(default ~ income + balance, data = Default, family = "binomial", subset = train)
# test error rate
probs <- predict.glm(glm.fit2, newdata = Default[-train, ], type = "response")
pred.glm <- rep("No", length(probs))
pred.glm[probs > 0.5] <- "Yes"
mean(pred.glm != Default[-train, ]$default)
## [1] 0.0274
train <- sample(dim(Default)[1], dim(Default)[1] / 2)
glm.fit3 <- glm(default ~ income + balance, data = Default, family = "binomial", subset = train)
probs <- predict.glm(glm.fit3, newdata = Default[-train, ], type = "response")
pred.glm <- rep("No", length(probs))
pred.glm[probs > 0.5] <- "Yes"
mean(pred.glm != Default[-train, ]$default)
## [1] 0.0244
# split the data
train <- sample(dim(Default)[1], dim(Default)[1] / 2)
# fit the model
glm.fit4 <- glm(default ~ income + balance, data = Default, family = "binomial", subset = train)
# test error rate
probs <- predict.glm(glm.fit4, newdata = Default[-train, ], type = "response")
pred.glm <- rep("No", length(probs))
pred.glm[probs > 0.5] <- "Yes"
mean(pred.glm != Default[-train, ]$default)
## [1] 0.0244

It is evident that from the three different splits, this will yield in a different error rate. This is due to the fact different observations fall in the training and testing sets each time we split the data.

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

# split the data
train <- sample(dim(Default)[1], dim(Default)[1] / 2)
# fit the model while including the student variable
glm.fit5 <- glm(default ~ balance + income + student, data = Default, subset = train, family = binomial)
summary(glm.fit5)
## 
## Call:
## glm(formula = default ~ balance + income + student, family = binomial, 
##     data = Default, subset = train)
## 
## Deviance Residuals: 
##     Min       1Q   Median       3Q      Max  
## -2.3850  -0.1413  -0.0568  -0.0212   3.7409  
## 
## Coefficients:
##               Estimate Std. Error z value Pr(>|z|)    
## (Intercept) -1.042e+01  6.921e-01 -15.058   <2e-16 ***
## balance      5.638e-03  3.276e-04  17.212   <2e-16 ***
## income      -5.472e-06  1.205e-05  -0.454   0.6498    
## studentYes  -8.286e-01  3.468e-01  -2.389   0.0169 *  
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## (Dispersion parameter for binomial family taken to be 1)
## 
##     Null deviance: 1409.45  on 4999  degrees of freedom
## Residual deviance:  767.12  on 4996  degrees of freedom
## AIC: 775.12
## 
## Number of Fisher Scoring iterations: 8
# estimate the test error
probs <- predict.glm(glm.fit5, newdata = Default[-train, ], type = "response")
pred.glm <- rep("No", length(probs))
pred.glm[probs > 0.5] <- "Yes"
mean(pred.glm != Default[-train, ]$default)
## [1] 0.0278

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(123)
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, subset = index, family = binomial)))
boot.fn(Default, 1:10000)
##   (Intercept)        income       balance 
## -1.154047e+01  2.080898e-05  5.647103e-03
# The boot.fn() function can also be used in order to create bootstrap estimates for the intercept and slope terms by randomly sampling from among the observations with replacement
set.seed(1)
boot.fn(Default ,sample (10000,10000, replace=T))
##   (Intercept)        income       balance 
## -1.209470e+01  2.815290e-05  5.837117e-03
boot.fn(Default ,sample (10000,10000, replace=T))
##   (Intercept)        income       balance 
## -1.157101e+01  2.185983e-05  5.710998e-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)
# use the boot() function to compute the standard errors of 1,000 bootstrap estimates for the intercept and slope terms.
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* -1.154047e+01 -3.861439e-02 4.351231e-01
## t2*  2.080898e-05  1.618852e-07 4.847720e-06
## t3*  5.647103e-03  1.817356e-05 2.302502e-04
# regression coeff. in the glm
summary(glm(default ~ income + balance ,data=Default, family = binomial))$coef
##                  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

(d) Comment on the estimated standard errors obtained using the glm() function and using your bootstrap function.
This indicates that the bootstrap estimate for \(SE(β_{0})\) is \(4.369234e-01\), and that the bootstrap estimate for \(SE(β_{1})\) is \(4.953271e-06\), and that the bootstrap estimate for \(SE(β_{2})\) is \(2.320058e-04\).

The standard error estimates for \(β_{0}\), \(β_{1}\) and \(β_{2}\) obtained using the formulas from Section 3.1.2 are \(4.347564e-01\) for the intercept and \(4.985167e-06\) and \(2.273731e-04\) for the slopes.

The bootstrap approach does not rely on any of these assumptions, and so it is likely giving a more accurate estimate of the standard errors of \(β_{0}\), \(β_{1}\) and \(β_{2}\) than is the summary() function.

Problem 9

We will now consider the Boston housing data set, from the MASS library.
(a) Based on this data set, provide an estimate for the population mean of medv. Call this estimate ˆμ.

library(MASS)
attach(Boston)
mu.hat <- mean(medv)
mu.hat
## [1] 22.53281

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

se.hat <- sd(medv) / sqrt(dim(Boston)[1])
se.hat
## [1] 0.4088611

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

# Estimating the Accuracy of a Statistic of Interest
set.seed(1)
boot.fn <- function(data ,index){
  mu <- mean(data[index])
  return (mu)}
boot(Boston$medv, 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.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).

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
# Hint: You can approximate a 95 % confidence interval using the formula [ˆμ − 2SE(ˆμ), μˆ + 2SE(ˆμ)].
CI.mu.hat <- c(22.53281 - 2*0.4119374, 22.53281 + 2*0.4119374)
CI.mu.hat
## [1] 21.70894 23.35668

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

med.hat <- median(medv)
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 <- function(data, index) {
    mu <- median(data[index])
    return (mu)
}
boot(medv, boot.fn, R=1000)
## 
## ORDINARY NONPARAMETRIC BOOTSTRAP
## 
## 
## Call:
## boot(data = medv, statistic = boot.fn, R = 1000)
## 
## 
## Bootstrap Statistics :
##     original  bias    std. error
## t1*     21.2 -0.0386   0.3770241

The median of “medv” using the median() function, gave us 21.2, which is the same value we got when we used the bootstrap.

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

mu.hat.01 <- quantile(medv, probs = c(0.1))
mu.hat.01
##   10% 
## 12.75

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

boot.fn <- function(data, index) {
    mu <- quantile(data[index], probs = c(0.1))
    return (mu)
}
boot(medv, boot.fn, R=1000)
## 
## ORDINARY NONPARAMETRIC BOOTSTRAP
## 
## 
## Call:
## boot(data = medv, statistic = boot.fn, R = 1000)
## 
## 
## Bootstrap Statistics :
##     original  bias    std. error
## t1*    12.75  0.0186   0.4925766

The quantile() function gave us 12.75, which is the same value we got when we bootstrapped it.