Problem 3. We now review k-fold cross-validation.

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

In k-fold cross-validation, the data is divided into k different groups. The first fold or group is used as the validation set and the model is fit with the remaining groups and validated on the validation set. This occurs over and over again until all groups have a turn at being the validation set. The average MSE across all runs becomes the estimated test error.

(b) What are the advantages and disadvantages of k-fold cross-validation relative to:
i. The validation set approach?

The validation set approach can be less computationally intensive than the k-fold approach because the user can choose to run very few times. The validation set approach is also simple and easy to implement. However, the validation MSE can be highly variable compared to the k-fold approach. Also, only a subset of observations are used to fit the model therefore data sets with very few observations will do very poor with the validation set approach.

ii. LOOCV?

k-fold is less computationally intensive than the LOOCV because it only leverages k amount of runs instead of running through each observation in the data set one by one. There is also more variance associated with LOOCV that with k-fold. LOOCV also has a lot of variance due to the high correlation of the training sets.

Problem 5. In Chapter 4, we used logistic regression to predict the probability of default using income and balance on the [Default]:https://rdrr.io/cran/ISLR/man/Default.html 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)
#head(Default)
#create binary outcome variable to use in logistic regression
Default$Default2<-ifelse(default=="Yes",1,0)
#summary(Default)
log.fit<-glm(Default2~income + balance, data=Default, family=binomial)
summary(log.fit)
## 
## Call:
## glm(formula = Default2 ~ 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.

# Create a 70/30 train/test
set.seed(3)
#trainid will be the variable that holds the TRUE/FALSE indicator
trainid <- sample(1:nrow(Default), nrow(Default)*0.7 , replace=F)  # 70% train, 30% test
train <- Default[trainid,]
test <- Default[-trainid,]

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

trainlog.fit<-glm(Default2~income + balance, data=train, family=binomial)
summary(trainlog.fit)
## 
## Call:
## glm(formula = Default2 ~ income + balance, family = binomial, 
##     data = train)
## 
## Deviance Residuals: 
##     Min       1Q   Median       3Q      Max  
## -2.5585  -0.1385  -0.0528  -0.0188   3.7631  
## 
## Coefficients:
##               Estimate Std. Error z value Pr(>|z|)    
## (Intercept) -1.185e+01  5.286e-01  -22.42  < 2e-16 ***
## income       2.141e-05  5.898e-06    3.63 0.000283 ***
## balance      5.860e-03  2.757e-04   21.26  < 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: 2157.1  on 6999  degrees of freedom
## Residual deviance: 1110.9  on 6997  degrees of freedom
## AIC: 1116.9
## 
## 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

#Create a probability vector
glm.probs=predict(trainlog.fit, test, type= 'response')
glm.pred=ifelse(glm.probs > 0.5, '1', '0')

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

table(glm.pred, test$Default2)
##         
## glm.pred    0    1
##        0 2904   61
##        1   13   22
#misclassification rate/Error Rate
mean(glm.pred!= test$Default2)
## [1] 0.02466667

(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(5)
#trainid will be the variable that holds the TRUE/FALSE indicator
trainid <- sample(1:nrow(Default), nrow(Default)*0.7 , replace=F)  # 70% train, 30% test
train <- Default[trainid,]
test <- Default[-trainid,]
trainlog.fit<-glm(Default2~income + balance, data=train, family=binomial)
summary(trainlog.fit)
## 
## Call:
## glm(formula = Default2 ~ income + balance, family = binomial, 
##     data = train)
## 
## Deviance Residuals: 
##     Min       1Q   Median       3Q      Max  
## -2.5399  -0.1371  -0.0530  -0.0185   3.5340  
## 
## Coefficients:
##               Estimate Std. Error z value Pr(>|z|)    
## (Intercept) -1.174e+01  5.273e-01 -22.267  < 2e-16 ***
## income       1.784e-05  6.012e-06   2.968  0.00299 ** 
## balance      5.868e-03  2.792e-04  21.017  < 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: 2084  on 6999  degrees of freedom
## Residual deviance: 1082  on 6997  degrees of freedom
## AIC: 1088
## 
## Number of Fisher Scoring iterations: 8
glm.probs=predict(trainlog.fit, test, type= 'response')
glm.pred=ifelse(glm.probs > 0.5, '1', '0')
table(glm.pred, test$Default2)
##         
## glm.pred    0    1
##        0 2895   63
##        1   11   31
#misclassification rate/Error Rate
mean(glm.pred!= test$Default2)
## [1] 0.02466667
set.seed(17)
#trainid will be the variable that holds the TRUE/FALSE indicator
trainid <- sample(1:nrow(Default), nrow(Default)*0.7 , replace=F)  # 70% train, 30% test
train <- Default[trainid,]
test <- Default[-trainid,]
trainlog.fit<-glm(Default2~income + balance, data=train, family=binomial)
summary(trainlog.fit)
## 
## Call:
## glm(formula = Default2 ~ income + balance, family = binomial, 
##     data = train)
## 
## Deviance Residuals: 
##     Min       1Q   Median       3Q      Max  
## -2.4704  -0.1478  -0.0590  -0.0219   3.6997  
## 
## Coefficients:
##               Estimate Std. Error z value Pr(>|z|)    
## (Intercept) -1.145e+01  5.156e-01 -22.218  < 2e-16 ***
## income       2.273e-05  5.955e-06   3.817 0.000135 ***
## balance      5.568e-03  2.673e-04  20.835  < 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: 2064.0  on 6999  degrees of freedom
## Residual deviance: 1128.5  on 6997  degrees of freedom
## AIC: 1134.5
## 
## Number of Fisher Scoring iterations: 8
glm.probs=predict(trainlog.fit, test, type= 'response')
glm.pred=ifelse(glm.probs > 0.5, '1', '0')
table(glm.pred, test$Default2)
##         
## glm.pred    0    1
##        0 2893   63
##        1   10   34
#misclassification rate/Error Rate
mean(glm.pred!= test$Default2)
## [1] 0.02433333
set.seed(65)
#trainid will be the variable that holds the TRUE/FALSE indicator
trainid <- sample(1:nrow(Default), nrow(Default)*0.7 , replace=F)  # 70% train, 30% test
train <- Default[trainid,]
test <- Default[-trainid,]
trainlog.fit<-glm(Default2~income + balance, data=train, family=binomial)
summary(trainlog.fit)
## 
## Call:
## glm(formula = Default2 ~ income + balance, family = binomial, 
##     data = train)
## 
## Deviance Residuals: 
##     Min       1Q   Median       3Q      Max  
## -2.5073  -0.1455  -0.0576  -0.0209   3.7221  
## 
## Coefficients:
##               Estimate Std. Error z value Pr(>|z|)    
## (Intercept) -1.160e+01  5.232e-01 -22.180  < 2e-16 ***
## income       2.243e-05  6.002e-06   3.737 0.000186 ***
## balance      5.678e-03  2.741e-04  20.717  < 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: 2030.3  on 6999  degrees of freedom
## Residual deviance: 1101.5  on 6997  degrees of freedom
## AIC: 1107.5
## 
## Number of Fisher Scoring iterations: 8
glm.probs=predict(trainlog.fit, test, type= 'response')
glm.pred=ifelse(glm.probs > 0.5, '1', '0')
table(glm.pred, test$Default2)
##         
## glm.pred    0    1
##        0 2888   62
##        1   10   40
#misclassification rate/Error Rate
mean(glm.pred!= test$Default2)
## [1] 0.024

While there was some variance in the coefficients, all of the error rates were very close close to each other. They were around 2.4%.

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

Default$Student2<-ifelse(student=="Yes",1,0)
set.seed(5)
#trainid will be the variable that holds the TRUE/FALSE indicator
trainid <- sample(1:nrow(Default), nrow(Default)*0.7 , replace=F)  # 70% train, 30% test
train <- Default[trainid,]
test <- Default[-trainid,]
trainlog.fit<-glm(Default2~income + balance + Student2, data=train, family=binomial)
summary(trainlog.fit)
## 
## Call:
## glm(formula = Default2 ~ income + balance + Student2, family = binomial, 
##     data = train)
## 
## Deviance Residuals: 
##     Min       1Q   Median       3Q      Max  
## -2.5353  -0.1332  -0.0506  -0.0176   3.6093  
## 
## Coefficients:
##               Estimate Std. Error z value Pr(>|z|)    
## (Intercept) -1.083e+01  5.866e-01 -18.462  < 2e-16 ***
## income      -7.140e-06  9.758e-06  -0.732  0.46436    
## balance      6.006e-03  2.873e-04  20.909  < 2e-16 ***
## Student2    -9.145e-01  2.804e-01  -3.262  0.00111 ** 
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## (Dispersion parameter for binomial family taken to be 1)
## 
##     Null deviance: 2084.0  on 6999  degrees of freedom
## Residual deviance: 1071.5  on 6996  degrees of freedom
## AIC: 1079.5
## 
## Number of Fisher Scoring iterations: 8
glm.probs=predict(trainlog.fit, test, type= 'response')
glm.pred=ifelse(glm.probs > 0.5, '1', '0')
table(glm.pred, test$Default2)
##         
## glm.pred    0    1
##        0 2894   63
##        1   12   31
#misclassification rate/Error Rate
mean(glm.pred!= test$Default2)
## [1] 0.025
#trainid will be the variable that holds the TRUE/FALSE indicator
trainid <- sample(1:nrow(Default), nrow(Default)*0.7 , replace=F)  # 70% train, 30% test
train <- Default[trainid,]
test <- Default[-trainid,]
trainlog.fit<-glm(Default2~income + balance + Student2, data=train, family=binomial)
summary(trainlog.fit)
## 
## Call:
## glm(formula = Default2 ~ income + balance + Student2, family = binomial, 
##     data = train)
## 
## Deviance Residuals: 
##     Min       1Q   Median       3Q      Max  
## -2.4324  -0.1395  -0.0550  -0.0201   3.7488  
## 
## Coefficients:
##               Estimate Std. Error z value Pr(>|z|)    
## (Intercept) -1.122e+01  6.160e-01 -18.221   <2e-16 ***
## income       1.056e-05  1.016e-05   1.040    0.298    
## balance      5.687e-03  2.803e-04  20.287   <2e-16 ***
## Student2    -4.378e-01  2.950e-01  -1.484    0.138    
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## (Dispersion parameter for binomial family taken to be 1)
## 
##     Null deviance: 1941.7  on 6999  degrees of freedom
## Residual deviance: 1055.0  on 6996  degrees of freedom
## AIC: 1063
## 
## Number of Fisher Scoring iterations: 8
glm.probs=predict(trainlog.fit, test, type= 'response')
glm.pred=ifelse(glm.probs > 0.5, '1', '0')
table(glm.pred, test$Default2)
##         
## glm.pred    0    1
##        0 2881   84
##        1    4   31
#misclassification rate/Error Rate
mean(glm.pred!= test$Default2)
## [1] 0.02933333
#trainid will be the variable that holds the TRUE/FALSE indicator
trainid <- sample(1:nrow(Default), nrow(Default)*0.7 , replace=F)  # 70% train, 30% test
train <- Default[trainid,]
test <- Default[-trainid,]
trainlog.fit<-glm(Default2~income + balance + Student2, data=train, family=binomial)
summary(trainlog.fit)
## 
## Call:
## glm(formula = Default2 ~ income + balance + Student2, family = binomial, 
##     data = train)
## 
## Deviance Residuals: 
##     Min       1Q   Median       3Q      Max  
## -2.4039  -0.1478  -0.0600  -0.0223   3.6838  
## 
## Coefficients:
##               Estimate Std. Error z value Pr(>|z|)    
## (Intercept) -1.078e+01  5.837e-01 -18.466   <2e-16 ***
## income       8.671e-06  9.788e-06   0.886    0.376    
## balance      5.510e-03  2.696e-04  20.441   <2e-16 ***
## Student2    -4.552e-01  2.818e-01  -1.615    0.106    
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## (Dispersion parameter for binomial family taken to be 1)
## 
##     Null deviance: 2003.2  on 6999  degrees of freedom
## Residual deviance: 1114.5  on 6996  degrees of freedom
## AIC: 1122.5
## 
## Number of Fisher Scoring iterations: 8
glm.probs=predict(trainlog.fit, test, type= 'response')
glm.pred=ifelse(glm.probs > 0.5, '1', '0')
table(glm.pred, test$Default2)
##         
## glm.pred    0    1
##        0 2884   72
##        1   10   34
#misclassification rate/Error Rate
mean(glm.pred!= test$Default2)
## [1] 0.02733333

Including student does not result in a reduction in the test error rate.

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.

log.fit<-glm(Default2~income + balance, data = Default, family = 'binomial')
summary(log.fit)
## 
## Call:
## glm(formula = Default2 ~ 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.

set.seed(5)
glm.fit<-glm(Default2~income + balance, data=Default, family='binomial')
boot.fn=function(data,index){
return(coef(glm(Default2~income + balance, data=data, subset=index, family='binomial')))
}

boot.fn(Default, 1:1000)
##   (Intercept)        income       balance 
## -1.155359e+01  3.074546e-05  5.609161e-03
#Return the SE
summary(glm.fit)$coefficients[, 2]
##  (Intercept)       income      balance 
## 4.347564e-01 4.985167e-06 2.273731e-04

(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, 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.787648e-02 4.380326e-01
## t2*  2.080898e-05  2.733337e-07 4.909003e-06
## t3*  5.647103e-03  1.512143e-05 2.332406e-04

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

The standard errors are very similar between the glm and bootstrap functions although the bootstrap function comes in slightly smaller.

glm SE: (Intercept) income balance 4.347564e-01 4.985167e-06 2.273731e-04

Problem 9. We will now consider the [Boston housing]: https://rdrr.io/cran/mlbench/man/BostonHousing.html data set, from the MASS library.

library(MASS)
attach(Boston)

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

mu=mean(medv)
mu
## [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.

s.err<-function(x, index){sd(x[index])/sqrt(length(x[index]))}
s.err(medv)
## [1] 0.4088611

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

set.seed(5)
mu2<-function(x,index){mean(x[index])}
boot(medv, mu2, R=1000)
## 
## ORDINARY NONPARAMETRIC BOOTSTRAP
## 
## 
## Call:
## boot(data = medv, statistic = mu2, R = 1000)
## 
## 
## Bootstrap Statistics :
##     original     bias    std. error
## t1* 22.53281 0.01637984   0.4096144

The standard error of bootstrap is slightly higher but extremely close to that of my non bootstrap.

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

mu-2*0.4096144
## [1] 21.71358
mu+2*0.4096144
## [1] 23.35204

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

med.fun<- function(x, index){median(x[index])}
med.fun(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.

set.seed(5)
boot(medv, med.fun, R=1000)
## 
## ORDINARY NONPARAMETRIC BOOTSTRAP
## 
## 
## Call:
## boot(data = medv, statistic = med.fun, R = 1000)
## 
## 
## Bootstrap Statistics :
##     original  bias    std. error
## t1*     21.2 -0.0026   0.3847418

After processing the bootstrap 1000 times, the average standard error for the median is 0.3847418.

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

mu0.1<-quantile(medv, c(0.10))
mu0.1
##   10% 
## 12.75

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

mu0.1.fun<-function(x, index){quantile(x[index], c(0.10))}
boot(medv, mu0.1.fun, R=1000)
## 
## ORDINARY NONPARAMETRIC BOOTSTRAP
## 
## 
## Call:
## boot(data = medv, statistic = mu0.1.fun, R = 1000)
## 
## 
## Bootstrap Statistics :
##     original  bias    std. error
## t1*    12.75  0.0187   0.5076002

After processing the bootstrap 1000 times, the average error for finding the tenth percentile of medv in the Boston Housing data set is 0.5076002.