Chapter 5: 3, 5, 6, 9

Question 3

We now review k-fold cross validation.

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

  • k-fold cross validation is implemented by randomly dividing the set of observations into k groups of approximately equal size. One fold is treated as the validation set and the remaining observations are fit to the model. This is repeated k times.

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

  • The validation set approach? The validation set approach has highly variable test error rates. Also this approach only uses a subset of the data to fit the model which tends to overestimate the test error rate.
  • LOOCV? THe LOOCV is a special case of the k fold cross validation in which k = n. This is computationally expensive as the number of observations increases. The most obvious advantage of the k fold is computational when comparing to LOOCV. Another advantage of the k fold method compared to the LOOCV is that it does not suffer from high variance. The LOOCV has a higher variance due to averaging outputs of the fitted models that are trained on nearly identical sets of observations. Therefore, the outputs will be highly correlated which gives higher variance. However, there is a variance-biase tradeoff. Comparatively, the LOOCV cross-validation gives unbiased estimates of test error compared to the k fold method.

Question 5

In Chapter 4, we used logistic regression to predict the probability of default using income and blanace on the Defaul data set. We will now estimate the test error of this logistic regression model using the validation set appraoch. Do not forget to set a randome 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.0.5
data(Default)
summary(Default)
##  default    student       balance           income     
##  No :9667   No :7056   Min.   :   0.0   Min.   :  772  
##  Yes: 333   Yes:2944   1st Qu.: 481.7   1st Qu.:21340  
##                        Median : 823.6   Median :34553  
##                        Mean   : 835.4   Mean   :33517  
##                        3rd Qu.:1166.3   3rd Qu.:43808  
##                        Max.   :2654.3   Max.   :73554
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:

  • Split the sample set into a training set and a validation set.
train = sample(dim(Default)[1], dim(Default)[1]/2)
  • Fit a multiple logistic regression model using only the training observations.
glm.fit = glm(default~income+balance, data = Default, family = 'binomial', subset = train)
summary(glm.fit)
## 
## 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
  • 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.fit, newdata = Default[-train,], type="response")
glm.pred = rep("No", length(probs))
glm.pred[probs > 0.5] <-  "Yes"
  • Compute the validation set error, which is the fraction of the observations int he validation set that are misclassified.
mean(glm.pred != Default[-train,]$default)
## [1] 0.0254
  • There is a 2.54% test error rate with the validation set approach

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)
train = sample(dim(Default)[1], dim(Default)[1]/2)
glm.fit = glm(default~income+balance, data = Default, family = 'binomial', subset = train)
summary(glm.fit)
## 
## Call:
## glm(formula = default ~ income + balance, family = "binomial", 
##     data = Default, subset = train)
## 
## Deviance Residuals: 
##     Min       1Q   Median       3Q      Max  
## -2.3702  -0.1628  -0.0673  -0.0259   3.6470  
## 
## Coefficients:
##               Estimate Std. Error z value Pr(>|z|)    
## (Intercept) -1.090e+01  5.749e-01 -18.955   <2e-16 ***
## income       1.622e-05  6.891e-06   2.354   0.0186 *  
## balance      5.365e-03  3.049e-04  17.598   <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: 1483.83  on 4999  degrees of freedom
## Residual deviance:  854.49  on 4997  degrees of freedom
## AIC: 860.49
## 
## Number of Fisher Scoring iterations: 8
probs = predict(glm.fit, newdata = Default[-train,], type="response")
glm.pred = rep("No", length(probs))
glm.pred[probs > 0.5] <-  "Yes"
mean(glm.pred != Default[-train,]$default)
## [1] 0.0238
  • The test error is 2.38% with this validation set.
set.seed(20)
train = sample(dim(Default)[1], dim(Default)[1]/2)
glm.fit = glm(default~income+balance, data = Default, family = 'binomial', subset = train)
summary(glm.fit)
## 
## Call:
## glm(formula = default ~ income + balance, family = "binomial", 
##     data = Default, subset = train)
## 
## Deviance Residuals: 
##     Min       1Q   Median       3Q      Max  
## -2.6003  -0.1285  -0.0481  -0.0170   3.7909  
## 
## Coefficients:
##               Estimate Std. Error z value Pr(>|z|)    
## (Intercept) -1.222e+01  6.764e-01 -18.074  < 2e-16 ***
## income       2.440e-05  7.382e-06   3.305  0.00095 ***
## balance      5.999e-03  3.537e-04  16.958  < 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: 1382.01  on 4999  degrees of freedom
## Residual deviance:  716.55  on 4997  degrees of freedom
## AIC: 722.55
## 
## Number of Fisher Scoring iterations: 8
probs = predict(glm.fit, newdata = Default[-train,], type="response")
glm.pred = rep("No", length(probs))
glm.pred[probs > 0.5] <-  "Yes"
mean(glm.pred != Default[-train,]$default)
## [1] 0.0288
  • The test error rate is 2.88% with this validation set.
set.seed(30)
train = sample(dim(Default)[1], dim(Default)[1]/2)
glm.fit = glm(default~income+balance, data = Default, family = 'binomial', subset = train)
summary(glm.fit)
## 
## Call:
## glm(formula = default ~ income + balance, family = "binomial", 
##     data = Default, subset = train)
## 
## Deviance Residuals: 
##     Min       1Q   Median       3Q      Max  
## -1.8476  -0.1473  -0.0586  -0.0212   3.7145  
## 
## Coefficients:
##               Estimate Std. Error z value Pr(>|z|)    
## (Intercept) -1.157e+01  5.979e-01 -19.351  < 2e-16 ***
## income       2.300e-05  6.736e-06   3.414  0.00064 ***
## balance      5.644e-03  3.158e-04  17.871  < 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: 1510.51  on 4999  degrees of freedom
## Residual deviance:  808.76  on 4997  degrees of freedom
## AIC: 814.76
## 
## Number of Fisher Scoring iterations: 8
probs = predict(glm.fit, newdata = Default[-train,], type="response")
glm.pred = rep("No", length(probs))
glm.pred[probs > 0.5] <-  "Yes"
mean(glm.pred != Default[-train,]$default)
## [1] 0.026
  • The test error rate is 2.7% with this validation set
  • We see that the test error rates are variable depending on the observations are included in the training and validations sets.

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.

glm.fit = glm(default~income+balance+student, data = Default, family='binomial')
summary(glm.fit)
## 
## Call:
## glm(formula = default ~ income + balance + student, family = "binomial", 
##     data = Default)
## 
## Deviance Residuals: 
##     Min       1Q   Median       3Q      Max  
## -2.4691  -0.1418  -0.0557  -0.0203   3.7383  
## 
## Coefficients:
##               Estimate Std. Error z value Pr(>|z|)    
## (Intercept) -1.087e+01  4.923e-01 -22.080  < 2e-16 ***
## income       3.033e-06  8.203e-06   0.370  0.71152    
## balance      5.737e-03  2.319e-04  24.738  < 2e-16 ***
## studentYes  -6.468e-01  2.363e-01  -2.738  0.00619 ** 
## ---
## 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: 1571.5  on 9996  degrees of freedom
## AIC: 1579.5
## 
## Number of Fisher Scoring iterations: 8
set.seed(40)
train = sample(dim(Default)[1], dim(Default)[1]/2)
glm.fit = glm(default~income+balance, data = Default, family = 'binomial', subset = train)
summary(glm.fit)
## 
## Call:
## glm(formula = default ~ income + balance, family = "binomial", 
##     data = Default, subset = train)
## 
## Deviance Residuals: 
##     Min       1Q   Median       3Q      Max  
## -2.4149  -0.1421  -0.0562  -0.0209   3.7396  
## 
## Coefficients:
##               Estimate Std. Error z value Pr(>|z|)    
## (Intercept) -1.124e+01  6.123e-01  -18.35   <2e-16 ***
## income       1.233e-05  7.250e-06    1.70   0.0891 .  
## balance      5.637e-03  3.229e-04   17.46   <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: 1456.95  on 4999  degrees of freedom
## Residual deviance:  783.64  on 4997  degrees of freedom
## AIC: 789.64
## 
## Number of Fisher Scoring iterations: 8
probs = predict(glm.fit, newdata = Default[-train,], type="response")
glm.pred = rep("No", length(probs))
glm.pred[probs > 0.5] <-  "Yes"
mean(glm.pred != Default[-train,]$default)
## [1] 0.026
  • The test error rate is 2.6%. This is similar to the error rates for the previously fitted models that did not include the student dummy variable. Therefore, it appears that adding the student dummy variable does not reduce the test error rate.

Question 6

We continue to consider the use of a logistic regression model to predict the probability of deafult 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 co-efficients 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) {
  fit <-glm(default ~ income+balance, data = data, family = 'binomial', subset = index)
  return (coef(fit))
}

c) Use the boot() function together with your boot.fn() function estimate the standard errors of the logistic regression coefficients for income and balance.

library(boot)
boot(Default, boot.fn, 1000)
## 
## ORDINARY NONPARAMETRIC BOOTSTRAP
## 
## 
## Call:
## boot(data = Default, statistic = boot.fn, R = 1000)
## 
## 
## Bootstrap Statistics :
##          original        bias     std. error
## t1* -1.154047e+01 -3.945460e-02 4.344722e-01
## t2*  2.080898e-05  1.680317e-07 4.866284e-06
## t3*  5.647103e-03  1.855765e-05 2.298949e-04
  • The estimates for the standard errors are…

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

  • The coefficient for income obtained using the glm() function is similar to the second standard error coefficient using the bootstrap. Similarly, the coefficient for balance using the glm() function is similar to the third standard error coefficient using the boostrap.

Question 9

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

library(MASS)
data(Boston)
set.seed(10)

a) Based on this data set, provide an estimate for the population mean of medv. Call this estimate mu hat.

mu.hat = mean(Boston$medv)
mu.hat
## [1] 22.53281

b) Provide an estimate of the standard error of mu hate. 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

se.hat = sd(Boston$medv/sqrt(length(Boston$medv)))
se.hat
## [1] 0.4088611

c) Now estimate the standard error of mu hate using the boostrap. How does this compare to your answer from b)?

boot.fn = function(data, index) {
  return(mean(data[index]))
}
boot(Boston$medv, boot.fn, 1000)
## 
## ORDINARY NONPARAMETRIC BOOTSTRAP
## 
## 
## Call:
## boot(data = Boston$medv, statistic = boot.fn, R = 1000)
## 
## 
## Bootstrap Statistics :
##     original       bias    std. error
## t1* 22.53281 -0.008041502   0.4017124
  • The standard errors are similar (0.4089 vs 0.4107)

d) Based on your bootstrap estimate from c), provide a 95% confidence interval from 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
CI.mu.hat = c(mu.hat-2*0.4107, mu.hat+2*0.4107)
CI.mu.hat
## [1] 21.71141 23.35421
  • The confidence intervals based on the bootstrap is similar to the confidence interval of the t test (21.71-23.35 vs 21.73-23.34)

e) Based on this dataset, provide an estimate of mu hat med, for the median value of medv in the population.

mu.hat.med = median(Boston$medv)
mu.hat.med
## [1] 21.2

f) We now would like to estimate the standard error mu 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.

boot.fn = function(data,index) {
  return(median(data[index]))
}
boot(Boston$medv, boot.fn, 1000)
## 
## ORDINARY NONPARAMETRIC BOOTSTRAP
## 
## 
## Call:
## boot(data = Boston$medv, statistic = boot.fn, R = 1000)
## 
## 
## Bootstrap Statistics :
##     original   bias    std. error
## t1*     21.2 -0.00885    0.376465
  • Using the bootstrap, we get the same estimated median value of 21.2 as we did in part e. The standard error is 0.39 which is relatively small.

g) Based on this data set, provide an estimate for the tenth percentile of medv in Boston suburbs. Call this quantity mu hat 0.1. (You can use the quantile() function.)

mu.hat.percent = quantile(Boston$medv, c(0.1))
mu.hat.percent
##   10% 
## 12.75

h) Use the bootstrap to estimate the standard error mu hat 0.1. Comment on your findings.

boot.fn = function(data, index) {
  return(quantile(data[index], c(0.1)))
}
boot(Boston$medv, boot.fn, 1000)
## 
## ORDINARY NONPARAMETRIC BOOTSTRAP
## 
## 
## Call:
## boot(data = Boston$medv, statistic = boot.fn, R = 1000)
## 
## 
## Bootstrap Statistics :
##     original  bias    std. error
## t1*    12.75  0.0287   0.4784666
  • Using the boostrap, we get the same estimated median value of 12.5 as we did in part g. The standard error is 0.50 which is relatively small.