Question 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 is computed on the observations in the held-out fold. This procedure is repeated k times, where each time a different group of observations is treated as a validation set. Hence, we get k estimates of the test error and the k-fold cross-validation estimate is nothing but the average of these values.

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

i. The validation set approach?

The advantage of cross-validation compared to the validation set approach is we are not wasting any data. In the validation set approach, the data used for validation is being wasted and never used for training but in cross-validation, we use the validation set also for training. Data is really important to the model and hence should be used judiciously.

The disadvantage of k-fold cross validation is that if the value of k is very high, it becomes computationally intensive since the training algorithm has to run from scratch k times.

ii. LOOCV?

LOOCV is computationally very intensive. Some statistical learning methods have computationally intensive fitting procedures, so performing LOOCV may pose computational problems, especially if n is extremely high. In contrast, performing 10-fold CV requires fitting the learning procedure only 10 times, which may be much more feasible. k-fold CV also often gives more accurate estimates of the test error rate than does LOOCV. This has to do with a bias-variance trade-off. On the other hand, when performing k-fold CV for k=5 or k=10, it will lead to an intermediate level of bias since each training set contains (k-1)n/k observations - fewer than in the LOOCV approach but substantially more than in the validation set approach. Therefore, from the perspective of bias reduction, it is clear that LOOCV is to be preferred to k-fold CV.

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. (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
set.seed(1)
attach(Default)
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: i. Split the sample set into a training set and a validation set.
index = sample(1:nrow(Default), 0.8 * nrow(Default))
train = Default[index,]
test = Default[-index,]
  1. Fit a multiple logistic regression model using only the training observations.
glm.fit.train = glm(default ~ income + balance, data = train, family = "binomial")
summary(glm.fit.train)
## 
## Call:
## glm(formula = default ~ income + balance, family = "binomial", 
##     data = train)
## 
## Deviance Residuals: 
##     Min       1Q   Median       3Q      Max  
## -2.4758  -0.1413  -0.0563  -0.0210   3.4620  
## 
## Coefficients:
##               Estimate Std. Error z value Pr(>|z|)    
## (Intercept) -1.168e+01  4.893e-01 -23.879  < 2e-16 ***
## income       2.547e-05  5.631e-06   4.523  6.1e-06 ***
## balance      5.613e-03  2.531e-04  22.176  < 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: 2313.6  on 7999  degrees of freedom
## Residual deviance: 1239.2  on 7997  degrees of freedom
## AIC: 1245.2
## 
## Number of Fisher Scoring iterations: 8
  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.
pred = predict(glm.fit.train, newdata =test,type = "response")
glm.pred = rep("No",length(pred))
glm.pred[pred > 0.5] = "Yes"
  1. Compute the validation set error, which is the fraction of the observations in the validation set that are misclassified.
mean(glm.pred != test$default)
## [1] 0.026

The validation set error is 2.6%

  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.
index = sample(1:nrow(Default), 0.7 * nrow(Default))
train = Default[index,]
test = Default[-index,]
glm.fit.train = glm(default ~ income + balance, data = train, family = "binomial")
summary(glm.fit.train)
## 
## Call:
## glm(formula = default ~ income + balance, family = "binomial", 
##     data = train)
## 
## Deviance Residuals: 
##     Min       1Q   Median       3Q      Max  
## -2.4932  -0.1390  -0.0544  -0.0197   3.7591  
## 
## Coefficients:
##               Estimate Std. Error z value Pr(>|z|)    
## (Intercept) -1.176e+01  5.299e-01 -22.193  < 2e-16 ***
## income       2.140e-05  6.001e-06   3.567 0.000362 ***
## balance      5.749e-03  2.756e-04  20.859  < 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: 2057.2  on 6999  degrees of freedom
## Residual deviance: 1084.8  on 6997  degrees of freedom
## AIC: 1090.8
## 
## Number of Fisher Scoring iterations: 8
pred = predict(glm.fit.train, newdata = test,type = "response")
glm.pred = rep("No",length(pred))
glm.pred[pred > 0.5] = "Yes"
mean(glm.pred != test$default)
## [1] 0.02533333

The validation set error is now 2.53% for the 70-30 split.

index = sample(1:nrow(Default), 0.75 * nrow(Default))
train = Default[index,]
test = Default[-index,]
glm.fit.train = glm(default ~ income + balance, data = train, family = "binomial")
summary(glm.fit.train)
## 
## Call:
## glm(formula = default ~ income + balance, family = "binomial", 
##     data = train)
## 
## Deviance Residuals: 
##     Min       1Q   Median       3Q      Max  
## -2.5332  -0.1393  -0.0541  -0.0193   3.7533  
## 
## Coefficients:
##               Estimate Std. Error z value Pr(>|z|)    
## (Intercept) -1.184e+01  5.178e-01  -22.86  < 2e-16 ***
## income       2.155e-05  5.794e-06    3.72 0.000199 ***
## balance      5.821e-03  2.708e-04   21.49  < 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: 2198.9  on 7499  degrees of freedom
## Residual deviance: 1159.9  on 7497  degrees of freedom
## AIC: 1165.9
## 
## Number of Fisher Scoring iterations: 8
pred = predict(glm.fit.train, newdata = test,type = "response")
glm.pred = rep("No",length(pred))
glm.pred[pred > 0.5] = "Yes"
mean(glm.pred != test$default)
## [1] 0.0276

The validation set error is now 2.76% for the 75-25 split.

index = sample(1:nrow(Default), 0.9 * nrow(Default))
train = Default[index,]
test = Default[-index,]
glm.fit.train = glm(default ~ income + balance, data = train, family = "binomial")
summary(glm.fit.train)
## 
## Call:
## glm(formula = default ~ income + balance, family = "binomial", 
##     data = train)
## 
## Deviance Residuals: 
##     Min       1Q   Median       3Q      Max  
## -2.4686  -0.1406  -0.0553  -0.0204   3.7360  
## 
## Coefficients:
##               Estimate Std. Error z value Pr(>|z|)    
## (Intercept) -1.159e+01  4.644e-01 -24.963  < 2e-16 ***
## income       1.951e-05  5.312e-06   3.673 0.000239 ***
## balance      5.691e-03  2.421e-04  23.509  < 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: 2630.6  on 8999  degrees of freedom
## Residual deviance: 1404.9  on 8997  degrees of freedom
## AIC: 1410.9
## 
## Number of Fisher Scoring iterations: 8
pred = predict(glm.fit.train, newdata = test,type = "response")
glm.pred = rep("No",length(pred))
glm.pred[pred > 0.5] = "Yes"
mean(glm.pred != test$default)
## [1] 0.026

The validation set error is now 2.6% for the 90-10 split.

From the above iterations, we can see that everytime a different split of the data is considered, the validation error keeps changing though it remains in the same range.

  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.
index = sample(1:nrow(Default), 0.8 * nrow(Default))
train = Default[index,]
test = Default[-index,]
glm.fit.train = glm(default ~ income + balance + student, data = train, family = "binomial")
summary(glm.fit.train)
## 
## Call:
## glm(formula = default ~ income + balance + student, family = "binomial", 
##     data = train)
## 
## Deviance Residuals: 
##     Min       1Q   Median       3Q      Max  
## -2.1723  -0.1400  -0.0543  -0.0198   3.5656  
## 
## Coefficients:
##               Estimate Std. Error z value Pr(>|z|)    
## (Intercept) -1.076e+01  5.556e-01 -19.376  < 2e-16 ***
## income      -1.959e-06  9.393e-06  -0.209  0.83477    
## balance      5.782e-03  2.651e-04  21.808  < 2e-16 ***
## studentYes  -7.684e-01  2.676e-01  -2.872  0.00408 ** 
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## (Dispersion parameter for binomial family taken to be 1)
## 
##     Null deviance: 2286.5  on 7999  degrees of freedom
## Residual deviance: 1240.1  on 7996  degrees of freedom
## AIC: 1248.1
## 
## Number of Fisher Scoring iterations: 8
pred = predict(glm.fit.train, newdata = test,type = "response")
glm.pred = rep("No",length(pred))
glm.pred[pred > 0.5] = "Yes"
mean(glm.pred != test$default)
## [1] 0.0245

After adding a dummy variable student, the validation set error is 2.45%. There is no reduction seen in the error because of addition of the dummy variable.

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

The estimated standard errors for the coefficients associated with income and balance in a multiple logistic regression model that uses both predictors are 4.348e-01 for the intercept, 4.985e-06 for income and 2.274e-04 for balance.

(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){
  coefficients(glm(default~income+balance, data=data, subset=index, family="binomial"))
}
boot.fn(Default,1:nrow(Default))
##   (Intercept)        income       balance 
## -1.154047e+01  2.080898e-05  5.647103e-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.

#boot(Default,boot.fn,1000)

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

There is not much of a difference between the estimated standard errors obtained using the glm() function and the bootstrap function. The estimated standard errors for the coefficients associated with income and balance in a multiple logistic regression model that uses both predictors are 4.348e-01 for the intercept, 4.985e-06 for income and 2.274e-04 for balance. The estimated errors provided by the bootstrap function are also in the same range (ie) 4.344722e-01, 4.866284e-06 and 2.298949e-04 for the intercept, income and balance respectively.

Question 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)
mu=mean(Boston$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.

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)?

library(boot)
boot.fn<-function(data,index){
  mean(data[index])
}
boot(Boston$medv,boot.fn,1000,parallel ="multicore")
## 
## ORDINARY NONPARAMETRIC BOOTSTRAP
## 
## 
## Call:
## boot(data = Boston$medv, statistic = boot.fn, R = 1000, parallel = "multicore")
## 
## 
## Bootstrap Statistics :
##     original      bias    std. error
## t1* 22.53281 0.007650791   0.4106622

Though not exactly the same, the estimate for standard error of μ^ is almost equal with 0.4106622 using the bootstrap in comparison with 0.4088611 using manual calculation.

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

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
mu=22.53
se=0.4016
mu-2*se
## [1] 21.7268
mu+2*se
## [1] 23.3332

The mean calculated using the one sample t-test falls in the range of the 95% confidence interval calculated for the mean of medv.

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

mumed=median(Boston$medv)
mumed
## [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(1)
boot.fn<-function(data,index){
  median(data[index])
}
boot(Boston$medv,boot.fn,1000,parallel ="multicore")
## 
## ORDINARY NONPARAMETRIC BOOTSTRAP
## 
## 
## Call:
## boot(data = Boston$medv, statistic = boot.fn, R = 1000, parallel = "multicore")
## 
## 
## Bootstrap Statistics :
##     original  bias    std. error
## t1*     21.2 0.02295   0.3778075

The estimated median value is the same as obtained with manual calculation with a value of 21.2. The estimate of standard error of the median calculated using the bootstrap is 0.3778075

(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_0.1 = quantile(Boston$medv,p=0.1)
mu_0.1
##   10% 
## 12.75

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

set.seed(1)
boot.fn<-function(data,index){
  quantile(data[index],p=0.1)
}
boot(Boston$medv,boot.fn,1000,parallel ="multicore")
## 
## ORDINARY NONPARAMETRIC BOOTSTRAP
## 
## 
## Call:
## boot(data = Boston$medv, statistic = boot.fn, R = 1000, parallel = "multicore")
## 
## 
## Bootstrap Statistics :
##     original  bias    std. error
## t1*    12.75  0.0339   0.4767526

The standard error estimated for tenth percentile of medv using the bootstrap function is 0.4767526