We now review k-fold cross-validation.
Explain how k-fold cross-validation is implemented.
K-fold cross-validation is used to assess the performance of a predictive model. The process involves splitting the dataset into k equal-sized folds(or subsets). The model is trained k times, each time its trained it uses k-1 folds as the training set and the remaining fold as the validation set. For each iteration, one of the k subsets is held as the validation set, the model is then trained on the remaining k-1 subsets, finally the model’s performance is evaluated on the validation set.
What are the advantages and disadvantages of k-fold cross-validation relative to:
i. The validation set approach?
ii. LOOCV?
K-fold cross-validation VS validation set approach:
One advantage that k-fold cross-validation has when compared to a validation set approach, is that every data point is used for both training and validation data. Whereas with the validation set approach, one portion is solely for validation leading to less efficient use of the dataset. A disadvantage is that there may be more variance in performance estimates when using k-fold cross-validation on smaller datasets or if the dataset exhibits significant variability.
K-fold cross-validation VS LOOCV:
K-fold cross-validation has a few advantages when compared to LOOCV. One advantage of K-fold cross-validation is that it’s typically less computationally expensive than LOOCV since it usually involves fewer iterations. Also, K-fold cross-validation often provides a better balance between bias and variance by training on multiple subsets of the data. However, its prior disadvantage still persists when compared to LOOCV; k-fold cross-validation may have more variance in performance estimates when using a small dataset. K-folds cross-validation may also exhibit overfitting or underfitting depending on what the value of k is.
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.
set.seed(1)
model <- glm(default ~ income + balance, data = Default, family = "binomial")
summary(model)
##
## 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:
i. Split the sample set into a training set and a validation set.
set.seed(1)
train <- sample(nrow(Default),nrow(Default)*0.7)
default.train <- Default[train,]
default.test <- Default[-train,]ii. Fit a multiple logistic regression model using only the training observations.
model2 <- glm(default ~ income + balance, data = default.train, family = "binomial")
summary(model2)
##
## Call:
## glm(formula = default ~ income + balance, family = "binomial",
## data = default.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: 8iii. 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.
predictions <- predict(model2,default.test,type="response")
post_prob <- ifelse(predictions>0.5,"Yes","No")iv. Compute the validation set error, which is the fraction of the observations in the validation set that are misclassified.
table(default.test$default, post_prob, dnn=c("Actual","Predicted"))
## Predicted
## Actual No Yes
## No 2896 2
## Yes 78 24
round(mean(post_prob != default.test$default),4)
## [1] 0.0267Repeat 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(1)
train <- sample(nrow(Default),nrow(Default)*0.8)
default.train <- Default[train,]
default.test <- Default[-train,]
model3 <- glm(default ~ income + balance, data = default.train, family = "binomial")
predictions <- predict(model3,default.test,type="response")
post_prob <- ifelse(predictions>0.5,"Yes","No")
table(default.test$default, post_prob, dnn=c("Actual","Predicted"))
## Predicted
## Actual No Yes
## No 1928 2
## Yes 50 20
round(mean(post_prob != default.test$default),4)
## [1] 0.026
train <- sample(nrow(Default),nrow(Default)*0.6)
default.train <- Default[train,]
default.test <- Default[-train,]
model4 <- glm(default ~ income + balance, data = default.train, family = "binomial")
predictions <- predict(model4,default.test,type="response")
post_prob <- ifelse(predictions>0.5,"Yes","No")
table(default.test$default, post_prob, dnn=c("Actual","Predicted"))
## Predicted
## Actual No Yes
## No 3851 10
## Yes 95 44
round(mean(post_prob != default.test$default),4)
## [1] 0.0262
train <- sample(nrow(Default),nrow(Default)*0.5)
default.train <- Default[train,]
default.test <- Default[-train,]
model5 <- glm(default ~ income + balance, data = default.train, family = "binomial")
predictions <- predict(model5, default.test, type="response")
post_prob <- ifelse(predictions>0.5, "Yes", "No")
table(default.test$default, post_prob, dnn=c("Actual","Predicted"))
## Predicted
## Actual No Yes
## No 4817 21
## Yes 106 56
round(mean(post_prob != default.test$default),4)
## [1] 0.0254
Test Error Rates on different splits:
80/20: 0.026
60/40: 0.0262
50/50: 0.254
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(1)
train <- sample(nrow(Default),nrow(Default)*0.7)
default.train <- Default[train,]
default.test <- Default[-train,]
model6 <- glm(default ~ ., data = default.train, family = "binomial")
predictions <- predict(model6, default.test, type="response")
post_prob <- ifelse(predictions>0.5, "Yes", "No")
table(default.test$default, post_prob, dnn=c("Actual","Predicted"))
## Predicted
## Actual No Yes
## No 2896 2
## Yes 81 21
round(mean(post_prob != default.test$default),4)
## [1] 0.0277
We can see that the model with the dummy student variable included has a test error rate of 0.0277. This is higher than all the other models that do not include the student variable; there is not a reduction in 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.
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)
default.model <- glm(default ~ income + balance, data = Default, family = "binomial")
summary(default.model)
##
## 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
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)
+ coef(
glm(default ~ income + balance, data = data, subset = index, family = "binomial")
)
boot.fn(Default, 1:10000)
## (Intercept) income balance
## -1.154047e+01 2.080898e-05 5.647103e-03
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)
##
## 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
Comment on the estimated standard errors obtained using the glm() function and using your bootstrap function.
summary(
glm(default ~ income + balance, data = Default, family = "binomial")
)$coef
## Estimate Std. Error z value Pr(>|z|)
## (Intercept) -1.154047e+01 4.347564e-01 -26.544680 2.958355e-155
## income 2.080898e-05 4.985167e-06 4.174178 2.990638e-05
## balance 5.647103e-03 2.273731e-04 24.836280 3.638120e-136
The standard errors in both the bootstrap function and the glm() function are very similar. When comparing standard errors, the biggest difference we encounter is only 0.12. The differences are so small that we can assume that the results for both functions are fairly accurate. The consistency across these two functions only reinforces our results.
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 μˆ.
population_mu <- mean(Boston$medv)
population_mu
## [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.
sd(Boston$medv) / sqrt(length(Boston$medv))
## [1] 0.4088611
Now estimate the standard error of μˆ using the bootstrap. How does this compare to your answer from (b)?
set.seed(2)
boot.fn <- function(data, index) +
mean(data[index])
results <- boot(Boston$medv, boot.fn, R = 1000)
results
##
## ORDINARY NONPARAMETRIC BOOTSTRAP
##
##
## Call:
## boot(data = Boston$medv, statistic = boot.fn, R = 1000)
##
##
## Bootstrap Statistics :
## original bias std. error
## t1* 22.53281 -0.008232806 0.407299
My previous value for standard error when dividing the sample standard deviation by the square root of the number of observations was 0.4088611. Using bootstrapping, the standard error came out to 0.407299. Like stated prior, the difference between these two is very small, so we can assume that the standard error lies somewhere around these values. Using multiple estimation methods and achieving similar results can indicate, consistency, robustness, and reliability.
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).
results_SD <- sd(results$t)
round(c(mean(Boston$medv) - 2*results_SD, mean(Boston$medv) + 2*results_SD), 4)
## [1] 21.7182 23.3474
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
We can see that the calculated confidence interval and the t test confidence interval are nearly identical.
Calculation: 21.7182 23.3474
T-test: 21.72953 23.33608
Based on this data set, provide an estimate, μˆmed, for the median value of medv in the population.
mu_med <- median(Boston$medv)
mu_med
## [1] 21.2
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(2)
boot.fn <- function(data, index) +
median(data[index])
results <- boot(Boston$medv, boot.fn, R = 1000)
results
##
## ORDINARY NONPARAMETRIC BOOTSTRAP
##
##
## Call:
## boot(data = Boston$medv, statistic = boot.fn, R = 1000)
##
##
## Bootstrap Statistics :
## original bias std. error
## t1* 21.2 -0.02465 0.3879954
Similar to the mean, the standard error is relatively small compared to the estimate.
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.)
quantity_mu <- quantile(Boston$medv, 0.1)
quantity_mu
## 10%
## 12.75
Use the bootstrap to estimate the standard error of μˆ0.1. Comment on your findings.
set.seed(2)
boot.fn <- function(data, index) +
quantile(data[index], 0.1)
results <- boot(Boston$medv, boot.fn, R = 1000)
results
##
## ORDINARY NONPARAMETRIC BOOTSTRAP
##
##
## Call:
## boot(data = Boston$medv, statistic = boot.fn, R = 1000)
##
##
## Bootstrap Statistics :
## original bias std. error
## t1* 12.75 0.00275 0.5159129
The standard error obtained via bootstrapping is fairly small when compared to the tenth percentile which indicates that the estimate is representing the population pretty accurately