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, MSE\(_1\), 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, MSE\(_1\), MSE\(_2\), . . . , MSE\(_k\). The k-fold CV estimate is computed by averaging these values,

\(CV_k = 1/kΣ\)MSE\(_k\)

(b) What are the advantages and disadvantages of k-fold cross-validation relative to:
i. The validation set approach?
ii. LOOCV?
LOOCV can be expensive computationally and it will have more variance while CV is a very general approach that can be applied to almost any statistical learning method and in addition to that is more accurate.

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)

str(Default)
## 'data.frame':    10000 obs. of  4 variables:
##  $ default: Factor w/ 2 levels "No","Yes": 1 1 1 1 1 1 1 1 1 1 ...
##  $ student: Factor w/ 2 levels "No","Yes": 1 2 1 1 1 2 1 2 1 1 ...
##  $ balance: num  730 817 1074 529 786 ...
##  $ income : num  44362 12106 31767 35704 38463 ...
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

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

set.seed(1)

index = sample(nrow(Default), .7*nrow(Default), replace = FALSE)
train = Default[index,]
validation_set = Default[-index,]

dim(validation_set)
## [1] 3000    4

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

glm.fit1 = glm(default ~ income + balance, data = train, family = "binomial")

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.

glm.prob = predict(glm.fit1, newdata = validation_set, type = "response")
glm.pred = rep("No", 3000 )
glm.pred[glm.prob > .5] = "Yes"
table(glm.pred, validation_set$default)
##         
## glm.pred   No  Yes
##      No  2896   78
##      Yes    2   24
(2885+42)/3684
## [1] 0.7945168
glm.pred[1:10]
##  [1] "No" "No" "No" "No" "No" "No" "No" "No" "No" "No"

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

mean(validation_set$default != glm.pred)
## [1] 0.02666667

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

index2 = sample(nrow(Default), 0.7*nrow(Default), replace = FALSE)
train2 = Default[index2, ]
validation_set2 = Default[-index2, ]

glm.fit2 = glm(default ~ income + balance, data = train2, family = "binomial")

glm.prob2 = predict(glm.fit2, newdata = validation_set2, type = "response")
glm.pred2 = rep("No", 3000 )
glm.pred2[glm.prob2 > .5] = "Yes"

mean(validation_set2$default != glm.pred2)
## [1] 0.02133333
set.seed(3)

index3 = sample(nrow(Default), 0.7*nrow(Default), replace = FALSE)
train3 = Default[index3, ]
validation_set3 = Default[-index3, ]

glm.fit3 = glm(default ~ income + balance, data = train3, family = "binomial")

glm.prob3 = predict(glm.fit3, newdata = validation_set3, type = "response")
glm.pred3 = rep("No", 3000 )
glm.pred3[glm.prob3 > .5] = "Yes"

mean(validation_set3$default != glm.pred3)
## [1] 0.02466667
set.seed(4)

index4 = sample(nrow(Default), 0.7*nrow(Default), replace = FALSE)
train4 = Default[index4, ]
validation_set4 = Default[-index4, ]

glm.fit4 = glm(default ~ income + balance, data = train4, family = "binomial")

glm.prob4 = predict(glm.fit4, newdata = validation_set4, type = "response")
glm.pred4 = rep("No", 3000 )
glm.pred4[glm.prob4 > .5] = "Yes"

mean(validation_set4$default != glm.pred4)
## [1] 0.02366667

They do not yonder to far off but they do vary a little bit.

(d) Now consider a logistic regression model that predicts the prob- ability 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.

set.seed(5)

index5 = sample(nrow(Default), 0.7*nrow(Default), replace = FALSE)
train5 = Default[index5, ]
validation_set5 = Default[-index5, ]

glm.fit5 = glm(default ~ income + balance + student, data = train5, family = "binomial")

glm.prob5 = predict(glm.fit5, newdata = validation_set5, type = "response")
glm.pred5 = rep("No", 3000 )
glm.pred5[glm.prob5 > .5] = "Yes"

mean(validation_set5$default != glm.pred5)
## [1] 0.025

When adding student there wasn’t much of a difference, but you can note it has the highest error rate so far.

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.

set.seed(6)
glm.fit6 = glm(default ~ income + balance, data = Default, family = "binomial")

(a) Using the summary() and glm() functions, determine the esti- mated standard errors for the coefficients associated with income and balance in a multiple logistic regression model that uses both predictors.

summary(glm.fit6)$coefficients[, 2]
##  (Intercept)       income      balance 
## 4.347564e-01 4.985167e-06 2.273731e-04

(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 = 1:nrow(data)) {
  coef(glm(default ~ income + balance, data = data, subset = index, family = "binomial"))[2:3]
}

boot.fn(Default)
##       income      balance 
## 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.

library(boot)
set.seed(7)

estimate = boot(data = Default, boot.fn, R = 1000)
estimate
## 
## ORDINARY NONPARAMETRIC BOOTSTRAP
## 
## 
## Call:
## boot(data = Default, statistic = boot.fn, R = 1000)
## 
## 
## Bootstrap Statistics :
##         original        bias     std. error
## t1* 2.080898e-05 -1.335117e-07 4.680548e-06
## t2* 5.647103e-03  8.045655e-06 2.262036e-04

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

summary(glm.fit6)$coefficients[, 2]
##  (Intercept)       income      balance 
## 4.347564e-01 4.985167e-06 2.273731e-04

There’s not a whole lot of difference but since bootstraps doesn’t make any assumptions its more likely accurate.

Question 9

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

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

library(MASS)

sample_mean = mean(Boston$medv)
sample_mean
## [1] 22.53281

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

std_error = sd(Boston$medv) / sqrt(length(Boston$medv))
std_error
## [1] 0.4088611

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

set.seed(8)

boot.fn <- function(vector, index) {
  mean(vector[index])
}

se = boot(data = Boston$medv, boot.fn, R = 1000)
se
## 
## ORDINARY NONPARAMETRIC BOOTSTRAP
## 
## 
## Call:
## boot(data = Boston$medv, statistic = boot.fn, R = 1000)
## 
## 
## Bootstrap Statistics :
##     original      bias    std. error
## t1* 22.53281 0.007920751   0.3990518

Not going to lie its closer than expected.

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

sd_bootstrap = sd(se$t)

c(mean(Boston$medv) - 2 * sd_bootstrap, mean(Boston$medv) + 2 * sd_bootstrap)
## [1] 21.73470 23.33091
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

Honestly could not tell the difference bettween them until looking at them closely.

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

median(Boston$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(8)

boot.fn <- function(vector, index) {
  median(vector[index])
}

se_median = boot(data = Boston$medv, boot.fn, R = 1000)
se_median
## 
## ORDINARY NONPARAMETRIC BOOTSTRAP
## 
## 
## Call:
## boot(data = Boston$medv, statistic = boot.fn, R = 1000)
## 
## 
## Bootstrap Statistics :
##     original   bias    std. error
## t1*     21.2 -0.01645   0.3725328

It was spot on.

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

quantile(Boston$medv, 0.1)
##   10% 
## 12.75

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

set.seed(8)

boot.fn <- function(vector, index) {
  quantile(vector[index], 0.1)
}

quantile = boot(data = Boston$medv, boot.fn, R = 1000)
quantile
## 
## ORDINARY NONPARAMETRIC BOOTSTRAP
## 
## 
## Call:
## boot(data = Boston$medv, statistic = boot.fn, R = 1000)
## 
## 
## Bootstrap Statistics :
##     original  bias    std. error
## t1*    12.75 -0.0031   0.5117786

It was spot on again.