library(tidyverse)
library(openintro)
library(ISLR)
library(ISLR2)
library(MASS)
library(boot)We now review k-fold cross-validation.
(a) Explain how k-fold cross-validation is implemented.
K-fold cross validation is implemented by taking n number of observations and splitting them in to k groups; these groups are of equal size and do not overlap. The first fold is treated as a validation set, and the method is fit on the remaining k-1 folds. The MSE is 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.
(b) What are the advantages and disadvantages of k-fold cross-validation relative to: i. The validation set approach?
The validation set approach can lead to overestimates of the test error rate, so k-fold CV is preferred for that reason. It also decreases the bias. However the k-fold CV is more time and money costly because you have to repeat the procedure many times.
The k-fold CV has more accurate estimates in the test error rate over the LOOCV. The k-fold CV is also less costly than the LOOCV. However, LOOCV have less bias than k-fold CV.
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.
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.
Fit a multiple logistic regression model using only the training observations.
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.
Compute the validation set error, which is the fraction of the observations in the validation set that are misclassified.
bdata = sample(dim(Default)[1], dim(Default)[1] / 2)
glm.fit2 = glm(default ~ income + balance, data = Default, family = "binomial", subset = bdata)
summary(glm.fit2)##
## Call:
## glm(formula = default ~ income + balance, family = "binomial",
## data = Default, subset = bdata)
##
## 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
prob = predict(glm.fit2, newdata = Default[-bdata, ], type = "response")
glm.pred2 = rep("No", length(prob))
glm.pred2[prob > 0.5] = "Yes"
mean(glm.pred2 != Default[-bdata, ]$default)## [1] 0.0254
Based on the model above, we have a test error rate of 2.62%
(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.
bdata = sample(dim(Default)[1], dim(Default)[1] / 2)
glm.fit2 = glm(default ~ income + balance, data = Default, family = "binomial", subset = bdata)
prob = predict(glm.fit2, newdata = Default[-bdata, ], type = "response")
glm.pred2 = rep("No", length(prob))
glm.pred2[prob > 0.5] = "Yes"
mean(glm.pred2 != Default[-bdata, ]$default)## [1] 0.0274
This test has an error rate of 2.82%.
bdata = sample(dim(Default)[1], dim(Default)[1] / 2)
glm.fit2 = glm(default ~ income + balance, data = Default, family = "binomial", subset = bdata)
prob = predict(glm.fit2, newdata = Default[-bdata, ], type = "response")
glm.pred2 = rep("No", length(prob))
glm.pred2[prob > 0.5] = "Yes"
mean(glm.pred2 != Default[-bdata, ]$default)## [1] 0.0244
This test has an error rate of 2.72%.
bdata = sample(dim(Default)[1], dim(Default)[1] / 2)
glm.fit2 = glm(default ~ income + balance, data = Default, family = "binomial", subset = bdata)
prob = predict(glm.fit2, newdata = Default[-bdata, ], type = "response")
glm.pred2 = rep("No", length(prob))
glm.pred2[prob > 0.5] = "Yes"
mean(glm.pred2 != Default[-bdata, ]$default)## [1] 0.0244
Lastly, this test has an error rate of 2.68%. All of the individual tests have similar error rates.
(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.
bdata = sample(dim(Default)[1], dim(Default)[1] / 2)
glm.fit2 = glm(default ~ income + balance + student, data = Default, family = "binomial", subset = bdata)
prob = predict(glm.fit2, newdata = Default[-bdata, ], type = "response")
glm.pred2 = rep("No", length(prob))
glm.pred2[prob > 0.5] = "Yes"
mean(glm.pred2 != Default[-bdata, ]$default)## [1] 0.0278
The test error rate for the model was 2.64%. Including the dummy variable ‘student’ didn’t appear to reduce 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.
(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)
attach(Default)
glm.fit2 = glm(default ~ income + balance, data = Default, family = "binomial")
summary(glm.fit2)##
## 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) {return(coef(glm(default ~ income + balance,
data = data, 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, 100)##
## ORDINARY NONPARAMETRIC BOOTSTRAP
##
##
## Call:
## boot(data = Default, statistic = boot.fn, R = 100)
##
##
## Bootstrap Statistics :
## original bias std. error
## t1* -1.154047e+01 8.556378e-03 4.122015e-01
## t2* 2.080898e-05 -3.993598e-07 4.186088e-06
## t3* 5.647103e-03 -4.116657e-06 2.226242e-04
The estimates for the standard errors for income is 4.411567e-06 and for balance it is 2.113341e-04
(d) Comment on the estimated standard errors obtained using the glm() function and using your bootstrap function.
When using the glm() function versus using the bootstrap function, we find that the estimated standard errors are relatively similar.
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 ˆµ.
mean(Boston$medv)## [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(dim(Boston)[1]-1)## [1] 0.4092658
The standard error of ˆµ is 0.4092658. This number tells us the variability there is in the data. In this case we don’t appear to have much variability in our model.
(c) Now estimate the standard error of ˆµ using the bootstrap. How does this compare to your answer from (b)?
meanfunc=function(data, index){return(mean(Boston$medv[index]))}
boot(Boston, meanfunc, 100)##
## ORDINARY NONPARAMETRIC BOOTSTRAP
##
##
## Call:
## boot(data = Boston, statistic = meanfunc, R = 100)
##
##
## Bootstrap Statistics :
## original bias std. error
## t1* 22.53281 0.02923123 0.3997709
We now found the standard error to be 0.4052159 which relatively close to the value we found in part (b).
(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
22.53281+ 2*0.4052159## [1] 23.34324
22.53281- 2*0.4052159## [1] 21.72238
Our calculated confidence interval is (21.72238, 23.34324). Our confidence interval produced from the t-test is (21.72953, 23.33608).
(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.
medianfunc=function(data, index){return(median(Boston$medv[index]))}
boot(Boston, medianfunc, 100)##
## ORDINARY NONPARAMETRIC BOOTSTRAP
##
##
## Call:
## boot(data = Boston, statistic = medianfunc, R = 100)
##
##
## Bootstrap Statistics :
## original bias std. error
## t1* 21.2 -0.0135 0.4046357
Using the bootstrap method for the median, we find that the standard error is 0.3724801 which, again, is relatively close to the previous found in the mean bootstrap method.
(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.
bootfunc=function(data, index){return(quantile(Boston$medv[index], 0.1))}
boot(Boston, bootfunc, 100)##
## ORDINARY NONPARAMETRIC BOOTSTRAP
##
##
## Call:
## boot(data = Boston, statistic = bootfunc, R = 100)
##
##
## Bootstrap Statistics :
## original bias std. error
## t1* 12.75 0.0345 0.5122586
The standard error on the tenth percentile is 0.4837188. It’s still relatively close to the previous standard errors we found.
…