Question 3

We now review k-fold cross-validation.

  1. 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 method is fit on the remaining \(k − 1\) folds. The mean squared error 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. This process results in \(k\) estimates of the test error, and the k-fold cross-validation estimate is computed by averaging these values.
    –Page 181, Introduction to Statistical Learning, 2013.

  2. What are the advantages and disadvantages of k-fold cross-validation relative to:

    1. The validation set approach?

      The advantages of using the validation set approach relative to k-fold cross-validation are that it is conceptually simple and easy to implement. It involves simply splitting the data into two subsets, a training set and a validation set. However, this method has two drawbacks. The test error estimate can be highly variable depending on which observations are included in the training and validation sets. Additionally, this approach tends to overestimate the test error since there are fewer observations in the training set used to fit the model.

    2. LOOCV?

      Leave-One-Out Cross-Validation (LOOCV) is a special case of k-fold cross-validation in which \(k\) is equal to the number of observations in the data set. Thus, it is the most computationally intensive method since the model must be fit \(n\) times, each time using a training set of \(n - 1\) observations. It then makes a prediction on the observation held out. Due to a larger training set, this method tends to have lower bias than k-fold cross-validation, but higher variance as the models are trained on nearly identical training sets, resulting in highly correlated test error estimates.

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.

  1. Fit a logistic regression model that uses income and balance to predict default.
library(ISLR)
library(GGally)
attach(Default)
Default %>% 
  ggpairs(ggplot2::aes(color=default),
          title = "Distributions of Credit Card Debt by Default Status",
          lower = list(combo = wrap("box", alpha=0.5), discrete = wrap("barDiag", alpha=0.8), 
                       continuous = wrap("cor")),
          diag = list(continuous = wrap("densityDiag", alpha=0.5), discrete=wrap("barDiag", alpha=0.8)),
          upper = list(combo="blank", discrete="blank", continuous="blank"))

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
  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.
set.seed(1)
train <- sample(1:nrow(Default), 0.5*nrow(Default))
  1. Fit a multiple logistic regression model using only the training observations.
glm.fit <- glm(default ~ income + balance, data = Default, family = binomial, subset = train)
  1. 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.
glm.probs <- predict(glm.fit, Default[-train, ], type = "response")
glm.pred <- ifelse(glm.probs > 0.5, "Yes", "No")
  1. Compute the validation set error, which is the fraction of the observations in the validation set that are misclassified.
mean(glm.pred != Default[-train, ]$default)
## [1] 0.0254
  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.

    Using different splits for the training and validation set, the test error ranges from 2.3% to 3% due to the variation in the observations that are included in each set.

train <- sample(1:nrow(Default), 0.5*nrow(Default))
glm.fit <- glm(default ~ income + balance, data = Default, 
               family = binomial, subset = train)
glm.probs <- predict(glm.fit, Default[-train, ], type = "response")
glm.pred <- ifelse(glm.probs > 0.5, "Yes", "No")
mean(glm.pred != Default[-train, ]$default)
## [1] 0.0274
train <- sample(1:nrow(Default), 0.6*nrow(Default))
glm.fit <- glm(default ~ income + balance, data = Default, 
               family = binomial, subset = train)
glm.probs <- predict(glm.fit, Default[-train, ], type = "response")
glm.pred <- ifelse(glm.probs > 0.5, "Yes", "No")
mean(glm.pred != Default[-train, ]$default)
## [1] 0.02275
train <- sample(1:nrow(Default), 0.7*nrow(Default))
glm.fit <- glm(default ~ income + balance, data = Default, 
               family = binomial, subset = train)
glm.probs <- predict(glm.fit, Default[-train, ], type = "response")
glm.pred <- ifelse(glm.probs > 0.5, "Yes", "No")
mean(glm.pred != Default[-train, ]$default)
## [1] 0.02966667
  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 dummy variable for student leads to a reduction in the test error rate.

    With student added to the model, income is no longer significant and the test error rate is 2.6%, about the same as the models without student.

train <- sample(nrow(Default), 0.5*nrow(Default))
glm.fit <- glm(default ~ income + balance + student, data = Default, 
               family = binomial, subset = train)
summary(glm.fit)
## 
## Call:
## glm(formula = default ~ income + balance + student, family = binomial, 
##     data = Default, subset = train)
## 
## Deviance Residuals: 
##     Min       1Q   Median       3Q      Max  
## -2.0976  -0.1470  -0.0589  -0.0214   3.7185  
## 
## Coefficients:
##               Estimate Std. Error z value Pr(>|z|)    
## (Intercept) -1.068e+01  6.749e-01 -15.828   <2e-16 ***
## income       2.298e-06  1.113e-05   0.206   0.8365    
## balance      5.615e-03  3.188e-04  17.610   <2e-16 ***
## studentYes  -6.631e-01  3.243e-01  -2.045   0.0409 *  
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## (Dispersion parameter for binomial family taken to be 1)
## 
##     Null deviance: 1497.19  on 4999  degrees of freedom
## Residual deviance:  818.85  on 4996  degrees of freedom
## AIC: 826.85
## 
## Number of Fisher Scoring iterations: 8
glm.probs <- predict(glm.fit, Default[-train, ], type = "response")
glm.pred <- ifelse(glm.probs > 0.5, "Yes", "No")
mean(glm.pred != Default[-train, ]$default)
## [1] 0.0258

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.

  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(2)
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
  1. 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)))
}
  1. Use the boot() function together with your boot.fn() function to estimate the standard errors of the logistic regression coefficients for income and balance.
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 -3.620109e-02 4.243985e-01
## t2*  2.080898e-05 -2.996835e-07 4.625552e-06
## t3*  5.647103e-03  2.793292e-05 2.283349e-04
  1. Comment on the estimated standard errors obtained using the glm() function and using your bootstrap function.

    The bootstrap estimates are nearly identical to the standard error estimates using the glm() function.

detach(Default)

Question 9

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

  1. Based on this data set, provide an estimate for the population mean of medv. Call this estimate \({\hatμ}\).

    The average home value in the Boston data set is $22,532.81.

library(MASS)
attach(Boston)
set.seed(3)
mu <- mean(medv)
mu
## [1] 22.53281
  1. Provide an estimate of the standard error of \(\hatμ\). 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

    The standard error of the mean is relatively small at 0.409, or $409, in comparison to the average home value, which suggests that our sample mean is close to the true mean of the population.

sd(medv)/sqrt(nrow(Boston))
## [1] 0.4088611
  1. Now estimate the standard error of \(\hatμ\) using the bootstrap. How does this compare to your answer from (b)?

    The bootstrap estimate gives us the same standard error of the mean up to the third significant digit as the standard error formula above, 0.409 after rounding.

boot.fn <- function(data,index){
  return(mean(data[index]))
}
boot(medv, boot.fn, 500)
## 
## ORDINARY NONPARAMETRIC BOOTSTRAP
## 
## 
## Call:
## boot(data = medv, statistic = boot.fn, R = 500)
## 
## 
## Bootstrap Statistics :
##     original     bias    std. error
## t1* 22.53281 0.01711423   0.4092449
  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 \([{\hatμ} − 2SE({\hatμ}), { } {\hatμ} + 2SE({\hatμ})]\).

    Both estimation methods provide very similar confidence intervals for the mean, with the same values up to the hundredth place.

c(mu - 2*0.4092449, mu + 2*0.4092449)
## [1] 21.71432 23.35130
t.test(medv)
## 
##  One Sample t-test
## 
## data:  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
  1. Based on this data set, provide an estimate, \({\hatμ}_{med}\), for the median value of medv in the population.

    The median home value is $21,200.

median(medv)
## [1] 21.2
  1. We now would like to estimate the standard error of \({\hatμ}_{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 estimated standard error of the median using the bootstrap is quite small at 0.364, indicating that our estimate is an accurate representation of the population.

boot.fn <- function(data, index) {
    return(median(data[index]))
}
boot(medv, boot.fn, 500)
## 
## ORDINARY NONPARAMETRIC BOOTSTRAP
## 
## 
## Call:
## boot(data = medv, statistic = boot.fn, R = 500)
## 
## 
## Bootstrap Statistics :
##     original  bias    std. error
## t1*     21.2 -0.0092   0.3637031
  1. Based on this data set, provide an estimate for the tenth percentile of medv in Boston suburbs. Call this quantity \(\hatμ_{0.1}\). (You can use the quantile() function.)
mu.1 <- quantile(medv, c(0.1))
mu.1
##   10% 
## 12.75
  1. Use the bootstrap to estimate the standard error of \(\hat{\mu}_{0.1}\). Comment on your findings.

    The standard error estimate of the tenth percentile is slightly higher than the standard error estimates of the mean and median at 0.508, though it is still small in comparison to the tenth percentile home value.

boot.fn <- function(data, index) {
    return(quantile(data[index], c(0.1)))
}
boot(medv, boot.fn, 500)
## 
## ORDINARY NONPARAMETRIC BOOTSTRAP
## 
## 
## Call:
## boot(data = medv, statistic = boot.fn, R = 500)
## 
## 
## Bootstrap Statistics :
##     original  bias    std. error
## t1*    12.75  0.0118   0.5080028
detach(Boston)