We now review k-fold cross-validation.
(a) Explain how k-fold cross-validation is implemented.
K-fold cross-validation is implemented as the observations are divided into k different groups (folds). The first fold or group is used as the validation set and the model is fit with the remaining k-1 groups. The mean squared error (MSE) is computed across all folds used as the validation set and becomes the estimated test error. The k-fold cross-validation estimate is then averaged from the values of MSEs.
(b) What are the advantages and disadvantages of k-fold cross-validation relative to:
i. The validation set approach?
The validation set approach is simple and easily implemented. However, depending on the observations included in the validation set, the validation MSE can be highly variable. And since only a subset of observations are used to the fit the model, the validation set error rate may tend to overestimate the test error rate for the model fit on the entire data set. Statistical methods tend to perform worse when trained on fewer observations.
ii. LOOCV?
The LOOCV approach has less bias, using training data that contains n-1 observations. LOOCV also has a lesser variable MSE. However, LOOCV is computationally intensive since each model must be fit n times.
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.
library(ISLR)
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
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)
(a) Fit a logistic regression model that uses income and balance to predict default.
set.seed(1)
glm_fit <- glm(default ~ income + balance, family = binomial)
glm_fit
##
## Call: glm(formula = default ~ income + balance, family = binomial)
##
## Coefficients:
## (Intercept) income balance
## -1.154e+01 2.081e-05 5.647e-03
##
## Degrees of Freedom: 9999 Total (i.e. Null); 9997 Residual
## Null Deviance: 2921
## Residual Deviance: 1579 AIC: 1585
(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.
train <- sample(dim(Default)[1], dim(Default)[1]/2)
ii. Fit a multiple logistic regression model using only the training observations.
glm_fit2 <- glm(default ~ income + balance, family = binomial, subset = train)
summary(glm_fit2)
##
## Call:
## glm(formula = default ~ income + balance, family = binomial,
## 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
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_probs <- predict(glm_fit, Default[-train, ], type = "response")
glm_pred <- rep("No", dim(Default)[1]/2)
glm_pred[glm_probs > 0.5] = "Yes"
iv. 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.0248
The test error rate is 2.48%.
(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.
train2 <- sample(dim(Default)[1], dim(Default)[1]/2)
glm_fit3 <- glm(default ~ income + balance, family = binomial, subset = train2)
glm_probs3 <- predict(glm_fit3, Default[-train2, ], type = "response")
glm_pred3 <- rep("No", dim(Default)[1]/2)
glm_pred3[glm_probs3 > 0.5] = "Yes"
summary(glm_fit3)
##
## Call:
## glm(formula = default ~ income + balance, family = binomial,
## subset = train2)
##
## Deviance Residuals:
## Min 1Q Median 3Q Max
## -2.5420 -0.1329 -0.0512 -0.0176 3.7909
##
## Coefficients:
## Estimate Std. Error z value Pr(>|z|)
## (Intercept) -1.193e+01 6.379e-01 -18.709 < 2e-16 ***
## income 1.939e-05 6.953e-06 2.789 0.00528 **
## balance 5.918e-03 3.355e-04 17.641 < 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: 1490.52 on 4999 degrees of freedom
## Residual deviance: 774.41 on 4997 degrees of freedom
## AIC: 780.41
##
## Number of Fisher Scoring iterations: 8
mean(glm_pred3 != Default[-train2, ]$default)
## [1] 0.0274
train3 <- sample(dim(Default)[1], dim(Default)[1]/2)
glm_fit4 <- glm(default ~ income + balance, family = binomial, subset = train3)
glm_probs4 <- predict(glm_fit4, Default[-train3, ], type = "response")
glm_pred4 <- rep("No", dim(Default)[1]/2)
glm_pred4[glm_probs4 > 0.5] = "Yes"
summary(glm_fit4)
##
## Call:
## glm(formula = default ~ income + balance, family = binomial,
## subset = train3)
##
## Deviance Residuals:
## Min 1Q Median 3Q Max
## -2.1634 -0.1446 -0.0553 -0.0203 3.3281
##
## Coefficients:
## Estimate Std. Error z value Pr(>|z|)
## (Intercept) -1.158e+01 6.008e-01 -19.281 < 2e-16 ***
## income 1.975e-05 6.775e-06 2.916 0.00355 **
## balance 5.723e-03 3.180e-04 17.996 < 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: 1543.58 on 4999 degrees of freedom
## Residual deviance: 816.44 on 4997 degrees of freedom
## AIC: 822.44
##
## Number of Fisher Scoring iterations: 8
mean(glm_pred4 != Default[-train3, ]$default)
## [1] 0.0244
train4 <- sample(dim(Default)[1], dim(Default)[1]/2)
glm_fit5 <- glm(default ~ income + balance, family = binomial, subset = train4)
glm_probs5 <- predict(glm_fit5, Default[-train4, ], type = "response")
glm_pred5 <- rep("No", dim(Default)[1]/2)
glm_pred5[glm_probs5 > 0.5] = "Yes"
summary(glm_fit5)
##
## Call:
## glm(formula = default ~ income + balance, family = binomial,
## subset = train4)
##
## Deviance Residuals:
## Min 1Q Median 3Q Max
## -2.4027 -0.1517 -0.0624 -0.0233 3.6833
##
## Coefficients:
## Estimate Std. Error z value Pr(>|z|)
## (Intercept) -1.112e+01 5.816e-01 -19.120 <2e-16 ***
## income 1.638e-05 6.755e-06 2.425 0.0153 *
## balance 5.489e-03 3.067e-04 17.897 <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: 1503.85 on 4999 degrees of freedom
## Residual deviance: 831.51 on 4997 degrees of freedom
## AIC: 837.51
##
## Number of Fisher Scoring iterations: 8
mean(glm_pred5 != Default[-train4, ]$default)
## [1] 0.0244
Based on the models, the test error rate remained around .24 - .27.
(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.
train5 <- sample(dim(Default)[1], dim(Default)[1]/2)
glm_fit6 <- glm(default ~ income + balance + student, data = Default, family = binomial, subset = train5)
glm_probs6 <- predict(glm_fit6, Default[-train5, ], type = "response")
glm_pred6 <- rep("No", dim(Default)[1]/2)
glm_pred6[glm_probs6 > 0.5] = "Yes"
mean(glm_pred6 != Default[-train5, ]$default)
## [1] 0.0278
summary(glm_fit6)
##
## Call:
## glm(formula = default ~ income + balance + student, family = binomial,
## data = Default, subset = train5)
##
## Deviance Residuals:
## Min 1Q Median 3Q Max
## -2.3850 -0.1413 -0.0568 -0.0212 3.7409
##
## Coefficients:
## Estimate Std. Error z value Pr(>|z|)
## (Intercept) -1.042e+01 6.921e-01 -15.058 <2e-16 ***
## income -5.472e-06 1.205e-05 -0.454 0.6498
## balance 5.638e-03 3.276e-04 17.212 <2e-16 ***
## studentYes -8.286e-01 3.468e-01 -2.389 0.0169 *
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## (Dispersion parameter for binomial family taken to be 1)
##
## Null deviance: 1409.45 on 4999 degrees of freedom
## Residual deviance: 767.12 on 4996 degrees of freedom
## AIC: 775.12
##
## Number of Fisher Scoring iterations: 8
Based on the model glm_fit6 the dummy variable student did not decrease the test error rate.
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.
library(ISLR)
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
(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_fit7 <- glm(default ~ income + balance, data = Default, family = binomial)
summary(glm_fit7)
##
## 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(Default, index) return(coef(glm(default ~ income + balance, data = Default, family = binomial, subset = index)))
(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, 50)
##
## ORDINARY NONPARAMETRIC BOOTSTRAP
##
##
## Call:
## boot(data = Default, statistic = boot_fn, R = 50)
##
##
## Bootstrap Statistics :
## original bias std. error
## t1* -1.154047e+01 -5.661486e-02 4.847786e-01
## t2* 2.080898e-05 -7.436578e-08 4.456965e-06
## t3* 5.647103e-03 1.854126e-05 2.639029e-04
(d) Comment on the estimated standard errors obtained using the glm() function and using your bootstrap function.
Based on the results of the bootstrap function, the standard errors for income and balance are very close to the results of the logistic regression model.
detach(Default)
We will now consider the Boston housing data set, from the MASS library.
library(MASS)
set.seed(1)
attach(Boston)
summary(Boston)
## crim zn indus chas
## Min. : 0.00632 Min. : 0.00 Min. : 0.46 Min. :0.00000
## 1st Qu.: 0.08204 1st Qu.: 0.00 1st Qu.: 5.19 1st Qu.:0.00000
## Median : 0.25651 Median : 0.00 Median : 9.69 Median :0.00000
## Mean : 3.61352 Mean : 11.36 Mean :11.14 Mean :0.06917
## 3rd Qu.: 3.67708 3rd Qu.: 12.50 3rd Qu.:18.10 3rd Qu.:0.00000
## Max. :88.97620 Max. :100.00 Max. :27.74 Max. :1.00000
## nox rm age dis
## Min. :0.3850 Min. :3.561 Min. : 2.90 Min. : 1.130
## 1st Qu.:0.4490 1st Qu.:5.886 1st Qu.: 45.02 1st Qu.: 2.100
## Median :0.5380 Median :6.208 Median : 77.50 Median : 3.207
## Mean :0.5547 Mean :6.285 Mean : 68.57 Mean : 3.795
## 3rd Qu.:0.6240 3rd Qu.:6.623 3rd Qu.: 94.08 3rd Qu.: 5.188
## Max. :0.8710 Max. :8.780 Max. :100.00 Max. :12.127
## rad tax ptratio black
## Min. : 1.000 Min. :187.0 Min. :12.60 Min. : 0.32
## 1st Qu.: 4.000 1st Qu.:279.0 1st Qu.:17.40 1st Qu.:375.38
## Median : 5.000 Median :330.0 Median :19.05 Median :391.44
## Mean : 9.549 Mean :408.2 Mean :18.46 Mean :356.67
## 3rd Qu.:24.000 3rd Qu.:666.0 3rd Qu.:20.20 3rd Qu.:396.23
## Max. :24.000 Max. :711.0 Max. :22.00 Max. :396.90
## lstat medv
## Min. : 1.73 Min. : 5.00
## 1st Qu.: 6.95 1st Qu.:17.02
## Median :11.36 Median :21.20
## Mean :12.65 Mean :22.53
## 3rd Qu.:16.95 3rd Qu.:25.00
## Max. :37.97 Max. :50.00
(a) Based on this data set, provide an estimate for the population mean of medv. Call this estimate \(\hat{\mu}\).
mu_hat <- mean(medv)
mu_hat
## [1] 22.53281
(b) Provide an estimate of the standard error of \(\hat{\mu}\). 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(medv) / sqrt(length(medv))
se_hat
## [1] 0.4088611
The se_hat is the standard error for the mean of medv and is .4089.
(c) Now estimate the standard error of \(\hat{\mu}\) using the bootstrap. How does this compare to your answer from (b)?
library(boot)
boot_fn2 <- function(Boston, index){
return(mean(Boston[index]))
}
boot_medv <- boot(medv, boot_fn2, 1000)
boot_medv
##
## ORDINARY NONPARAMETRIC BOOTSTRAP
##
##
## Call:
## boot(data = medv, statistic = boot_fn2, R = 1000)
##
##
## Bootstrap Statistics :
## original bias std. error
## t1* 22.53281 0.007650791 0.4106622
Based on the bootstrap model boot_fn2 the standard error is .411 and close to the standard error se_hat calculated above.
(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 [\(\hat{\mu} − 2SE(\hat{\mu}), \hat{\mu} + 2SE(\hat{\mu})\)].
medv_CI_boot <- c(22.53281 - 2 * 0.4056861, 22.53281 + 2 * 0.4056861)
medv_CI_boot
## [1] 21.72144 23.34418
medv_CI <- t.test(medv)
medv_CI
##
## 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
(e) Based on this data set, provide an estimate, \(\hat{\mu}_{med}\), for the median value of medv in the population.
medv_median <- median(medv)
medv_median
## [1] 21.2
(f) We now would like to estimate the standard error of \(\hat{\mu}_{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_fn3 <- function(Boston, index){
return(median(Boston[index]))
}
boot_medv2 <- boot(medv, boot_fn3, 1000)
boot_medv2
##
## ORDINARY NONPARAMETRIC BOOTSTRAP
##
##
## Call:
## boot(data = medv, statistic = boot_fn3, R = 1000)
##
##
## Bootstrap Statistics :
## original bias std. error
## t1* 21.2 -0.0386 0.3770241
Based on the model boot_fn3, the standard error was .384 for the median of Boston medv.
(g) Based on this data set, provide an estimate for the tenth percentile of medv in Boston suburbs. Call this quantity \(\hat{\mu}_{0.1}\). (You can use the quantile() function.)
medv_tenth <- quantile(medv, c(0.1))
medv_tenth
## 10%
## 12.75
(h) Use the bootstrap to estimate the standard error of \(\hat{\mu}_{0.1}\). Comment on your findings.
boot_fn4 <- function(Boston,index){
return(quantile(Boston[index], c(0.1)))
}
medv_tenth_boot <- boot(medv, boot_fn4, 1000)
medv_tenth_boot
##
## ORDINARY NONPARAMETRIC BOOTSTRAP
##
##
## Call:
## boot(data = medv, statistic = boot_fn4, R = 1000)
##
##
## Bootstrap Statistics :
## original bias std. error
## t1* 12.75 0.0186 0.4925766
Based on the bootstrap model boot_fn4, I received the same estimate of 12.75 and the medv_tenth above.
detach(Boston)