Introduction This lab will explore various re sampling methods such as:
Question 3 will cover the conceptual side of the re sampling techniques while questions 5,6, and 9 will cover the applied side. The Default data set and the Boston housing data set will be used from the ISLR2 and MASS packages.
library(tidyverse)
library(ISLR2)
library(MASS)
library(boot)
We now review k-fold cross-validation.
Question: Explain how k-fold cross-validation is implemented.
Answer: K-fold cross-validation is implemented by splitting your data into folds consisting of a validation set and a training set. Typically people use k=5 or k=10 to split their data. Each split of the validation set can eventually be combined to make up the entire dataset. Once the folds are collected, they are averaged out to get the Mean Squared Error (MSE). K-fold remains a popular method because you get to choose what you want K to be, this makes k-fold a computationally affordable method while still being an accurate one.
Question: What are the advantages and disadvantages of k-fold cross-validation relative to:
Advantages: K-Fold cross-validation is a more detailed method that results in a more accurate calculation of the MSE than the validation set approach would. This method covers all the records of the dataset and uses them all to calculate MSE rather than just using a segment of the data set like the validation set approach does.
Disadvantages: It costs more and is more complex.
Advantages: K-fold cross validation provides the option of defining K. Since you can set K to just 5 or 10 you have the computational freedom to not have to run through every since record of your data set like LOOCV does. This makes k-fold a much less time consuming for resampling method. Additionally, K-fold has less variance than LOOCV. Because LOOCV runs its training sets on such large datasets, LOOCV has datapoints that are highly correlated with each other. K-fold overs more balance in its selection process leading to less variance.
Disadvantages: LOOCV has the lowest bias of all the methods because the sample sizes that are as numerous as the data set itself. There is a bias/variance trade-off between K-fold and LOOCV.
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.
Fit a logistic regression model that uses income and balance to predict default.
Default
default_logistic <- glm(default ~ income + balance, data = Default, family = binomial)
summary(default_logistic)
##
## Call:
## glm(formula = default ~ income + balance, family = binomial,
## data = Default)
##
## 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
Using the validation set approach, estimate the test error of this model. In order to do this, you must perform the following steps:
set.seed(1) #Setting the random sample at 1, anyone who runs this code will get the same random sample.
train <- sample(10000, 7000) #1000 is the number of records in the dataset, 600 is the size of the train sample
Fit a multiple logistic regression model using only the training observations.
default_logistic1 <- glm(default ~ income + balance, data = Default, family = binomial, subset = train)
summary(default_logistic1)
##
## Call:
## glm(formula = default ~ income + balance, family = binomial,
## data = Default, subset = train)
##
## Coefficients:
## Estimate Std. Error z value Pr(>|z|)
## (Intercept) -1.167e+01 5.214e-01 -22.379 < 2e-16 ***
## income 2.560e-05 6.012e-06 4.258 2.06e-05 ***
## balance 5.574e-03 2.678e-04 20.816 < 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: 1079.6 on 6997 degrees of freedom
## AIC: 1085.6
##
## Number of Fisher Scoring iterations: 8
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.
probability <- predict(default_logistic1,
newdata = Default[-train, ],
type="response")
prediction = if_else(probability > 0.5,"Yes","No")
Compute the validation set error, which is the fraction of the observations in the validation set that are misclassified.
error_logistic <- mean(prediction != Default$default[-train])
error_logistic
## [1] 0.02666667
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)
train1 <- sample(10000, 6000)
default_logistic2 <- glm(default ~ income + balance, data = Default, family = binomial, subset = train1)
summary(default_logistic2)
##
## Call:
## glm(formula = default ~ income + balance, family = binomial,
## data = Default, subset = train1)
##
## Coefficients:
## Estimate Std. Error z value Pr(>|z|)
## (Intercept) -1.097e+01 5.283e-01 -20.771 <2e-16 ***
## income 1.580e-05 6.311e-06 2.504 0.0123 *
## balance 5.414e-03 2.793e-04 19.381 <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: 1780.6 on 5999 degrees of freedom
## Residual deviance: 1009.4 on 5997 degrees of freedom
## AIC: 1015.4
##
## Number of Fisher Scoring iterations: 8
probability1 <- predict(default_logistic2,
newdata = Default[-train, ],
type="response")
prediction1 = if_else(probability1 > 0.5,"Yes","No")
error_logistic1 <- mean(prediction1 != Default$default[-train1])
error_logistic1
## [1] 0.0415
set.seed(3)
train2 <- sample(10000, 8500)
default_logistic3 <- glm(default ~ income + balance, data = Default, family = binomial, subset = train2)
summary(default_logistic3)
##
## Call:
## glm(formula = default ~ income + balance, family = binomial,
## data = Default, subset = train2)
##
## Coefficients:
## Estimate Std. Error z value Pr(>|z|)
## (Intercept) -1.170e+01 4.772e-01 -24.527 < 2e-16 ***
## income 2.175e-05 5.388e-06 4.038 5.4e-05 ***
## balance 5.737e-03 2.485e-04 23.086 < 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: 2535.9 on 8499 degrees of freedom
## Residual deviance: 1345.0 on 8497 degrees of freedom
## AIC: 1351
##
## Number of Fisher Scoring iterations: 8
probability2 <- predict(default_logistic2,
newdata = Default[-train2, ],
type="response")
prediction2 = if_else(probability2 > 0.5,"Yes","No")
error_logistic2 <- mean(prediction2 != Default$default[-train2])
error_logistic2
## [1] 0.02333333
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.
set.seed(4)
train3 <- sample(10000, 8400)
default_logistic4 <- glm(default ~ income + balance + student, data = Default, family = binomial, subset = train3)
summary(default_logistic4)
##
## Call:
## glm(formula = default ~ income + balance + student, family = binomial,
## data = Default, subset = train3)
##
## Coefficients:
## Estimate Std. Error z value Pr(>|z|)
## (Intercept) -1.099e+01 5.399e-01 -20.351 < 2e-16 ***
## income 1.944e-07 8.834e-06 0.022 0.98244
## balance 5.928e-03 2.610e-04 22.707 < 2e-16 ***
## studentYes -7.392e-01 2.549e-01 -2.900 0.00373 **
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## (Dispersion parameter for binomial family taken to be 1)
##
## Null deviance: 2515.5 on 8399 degrees of freedom
## Residual deviance: 1328.0 on 8396 degrees of freedom
## AIC: 1336
##
## Number of Fisher Scoring iterations: 8
probability3 <- predict(default_logistic3,
newdata = Default[-train3, ],
type="response")
prediction3 = if_else(probability3 > 0.5,"Yes","No")
error_logistic3 <- mean(prediction3 != Default$default[-train3])
error_logistic3
## [1] 0.025625
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.
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.
summary(default_logistic3)$coef
## Estimate Std. Error z value Pr(>|z|)
## (Intercept) -1.170321e+01 4.771588e-01 -24.526875 7.635370e-133
## income 2.175420e-05 5.387883e-06 4.037616 5.399709e-05
## balance 5.736663e-03 2.484930e-04 23.085815 6.428398e-118
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) {
default_logistic3 <- glm(default ~ income + balance,
data = data,
family = binomial,
subset = index)
return(coef(default_logistic3))
}
Use the boot() function together with your boot.fn() function to estimate the standard errors of the logistic regression coefficients for income and balance.
#This calculates standard error using 1000 bootstrap iterations
set.seed(1)
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.945460e-02 4.344722e-01
## t2* 2.080898e-05 1.680317e-07 4.866284e-06
## t3* 5.647103e-03 1.855765e-05 2.298949e-04
#This calculates standard error using the GLM() logistic mathematics
summary(default_logistic3)$coef
## Estimate Std. Error z value Pr(>|z|)
## (Intercept) -1.170321e+01 4.771588e-01 -24.526875 7.635370e-133
## income 2.175420e-05 5.387883e-06 4.037616 5.399709e-05
## balance 5.736663e-03 2.484930e-04 23.085815 6.428398e-118
Comment on the estimated standard errors obtained using the glm() function and using your bootstrap function.
We will now consider the Boston housing data set, from the ISLR2 library.
Based on this data set, provide an estimate for the population mean of medv. Call this estimate µˆ.
µˆ = mean(Boston$medv)
print(µˆ)
## [1] 22.53281
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.
# Number of obs
obs = nrow(506)
sd(Boston$medv) / sqrt(506)
## [1] 0.4088611
Now estimate the standard error of µˆ using the bootstrap. How does this compare to your answer from (b)?
boot.fn1 <- function(data,index) {
mean(data$medv[index])
}
#This calculates standard error using 1000 bootstrap iterations
set.seed(1)
boot(Boston, boot.fn1, R=1000)
##
## ORDINARY NONPARAMETRIC BOOTSTRAP
##
##
## Call:
## boot(data = Boston, statistic = boot.fn1, R = 1000)
##
##
## Bootstrap Statistics :
## original bias std. error
## t1* 22.53281 0.007650791 0.4106622
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(ˆµ)].
SE=sd(Boston$medv) / sqrt(506)
µˆ - 2*SE
## [1] 21.71508
µˆ + 2*SE
## [1] 23.35053
Based on this data set, provide an estimate, µˆmed, for the median value of medv in the population.
µˆmed = median(Boston$medv)
SE=sd(Boston$medv) / sqrt(506)
µˆmed - 2*SE
## [1] 20.38228
µˆmed + 2*SE
## [1] 22.01772
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.
boot.fn2 <- function(data,index) {
median(data$medv[index])
}
#This calculates standard error using 1000 bootstrap iterations
set.seed(1)
boot(Boston, boot.fn2, R=1000)
##
## ORDINARY NONPARAMETRIC BOOTSTRAP
##
##
## Call:
## boot(data = Boston, statistic = boot.fn2, R = 1000)
##
##
## Bootstrap Statistics :
## original bias std. error
## t1* 21.2 0.02295 0.3778075
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.)
µˆ0.1=quantile(Boston$medv, 0.10)
print(µˆ0.1)
## 10%
## 12.75
Use the bootstrap to estimate the standard error of µˆ0.1. Comment on your findings.
boot.fn3 <- function(data,index) {
quantile(Boston$medv[index], probs = 0.10)
}
#This calculates standard error using 1000 bootstrap iterations
set.seed(1)
boot(Boston, boot.fn3, R=1000)
##
## ORDINARY NONPARAMETRIC BOOTSTRAP
##
##
## Call:
## boot(data = Boston, statistic = boot.fn3, R = 1000)
##
##
## Bootstrap Statistics :
## original bias std. error
## t1* 12.75 0.0339 0.4767526