We now review k-fold cross-validation.
Explain how k-fold cross-validation is implemented.
The data is split into k equal parts. We train the model k times, each time using k – 1 parts for training and 1 part for validation. The average of the k validation errors is used to estimate model performance.
What are the advantages and disadvantages of k-fold cross-validation relative to:
The validation set approach? Advantage: More Data efficiency and Less variance Disadvantage:High Computational Cost
LOOCV? Advantage: Less Computational Cost, Lower Variance of error Disadvantage: Higher bias
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.
library(ISLR2)
set.seed(1) # set Random Seed
#fit Logistic Regression Model
glm.fit <- glm(default ~ income + balance, data=Default, family = "binomial")
summary(glm.fit)
##
## 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:
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.
#set random seed
set.seed(1)
Select_idx <- sample(nrow(Default), nrow(Default) * 0.7) # Training 70%, Testing 30%
#Split DB to Testing and Training
Train_DB <- Default[Select_idx, ]
Test_DB <- Default[-Select_idx, ]
#fit a Multiple Logistic Regression Model
glm.train.fit <- glm(default ~ income + balance, data=Default, family="binomial")
#Prediction
glm.train.prob <- predict(glm.train.fit, Test_DB, type = "response")
Predicted_Default <- ifelse(glm.train.prob > 0.5, "Yes", "No")
#Compute the Validation set error
mean(Test_DB$default != Predicted_Default)
## [1] 0.02633333
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.
Answer: The each prediction error has differenct value. But, there is only in the first decimal place. 1st Try
#set random seed
set.seed(2)
Select_idx <- sample(nrow(Default), nrow(Default) * 0.7) # Training 70%, Testing 30%
#Split DB to Testing and Training
Train_DB <- Default[Select_idx, ]
Test_DB <- Default[-Select_idx, ]
#fit a Multiple Logistic Regression Model
glm.train.fit <- glm(default ~ income + balance, data=Default, family="binomial")
#Prediction
glm.train.prob <- predict(glm.train.fit, Test_DB, type = "response")
Predicted_Default <- ifelse(glm.train.prob > 0.5, "Yes", "No")
#Compute the Validation set error
mean(Test_DB$default != Predicted_Default)
## [1] 0.021
2nd Try
#set random seed
set.seed(3)
Select_idx <- sample(nrow(Default), nrow(Default) * 0.7) # Training 70%, Testing 30%
#Split DB to Testing and Training
Train_DB <- Default[Select_idx, ]
Test_DB <- Default[-Select_idx, ]
#fit a Multiple Logistic Regression Model
glm.train.fit <- glm(default ~ income + balance, data=Default, family="binomial")
#Prediction
glm.train.prob <- predict(glm.train.fit, Test_DB, type = "response")
Predicted_Default <- ifelse(glm.train.prob > 0.5, "Yes", "No")
#Compute the Validation set error
mean(Test_DB$default != Predicted_Default)
## [1] 0.02466667
3rd Try
#set random seed
set.seed(8)
Select_idx <- sample(nrow(Default), nrow(Default) * 0.7) # Training 70%, Testing 30%
#Split DB to Testing and Training
Train_DB <- Default[Select_idx, ]
Test_DB <- Default[-Select_idx, ]
#fit a Multiple Logistic Regression Model
glm.train.fit <- glm(default ~ income + balance, data=Default, family="binomial")
#Prediction
glm.train.prob <- predict(glm.train.fit, Test_DB, type = "response")
Predicted_Default <- ifelse(glm.train.prob > 0.5, "Yes", "No")
#Compute the Validation set error
mean(Test_DB$default != Predicted_Default)
## [1] 0.02433333
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.
Answer: The error rate was increased 1%point.
#set random seed
set.seed(1)
Select_idx <- sample(nrow(Default), nrow(Default) * 0.7) # Training 70%, Testing 30%
#Split DB to Testing and Training
Train_DB <- Default[Select_idx, ]
Test_DB <- Default[-Select_idx, ]
#fit a Multiple Logistic Regression Model
glm.train.fit <- glm(default ~ income + balance + student, data=Default, family="binomial")
#Prediction
glm.train.prob <- predict(glm.train.fit, Test_DB, type = "response")
Predicted_Default <- ifelse(glm.train.prob > 0.5, "Yes", "No")
#Compute the Validation set error
mean(Test_DB$default != Predicted_Default)
## [1] 0.02733333
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.
# Use glm() and summary() to get standard errors of coefficients
glm.fit <- glm(default ~ income + balance, data = Default, family = "binomial")
summary(glm.fit)
##
## 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
library(boot)
# Bootstrap Function
boot.fn <- function(data, index) {
fit <- glm(default ~ income + balance, data = data[index, ], family = "binomial")
return(coef(fit)[c("income", "balance")])
}
set.seed(1)
boot.out <- boot(Default, boot.fn, R = 100)
apply(boot.out$t, 2, sd)
## [1] 4.186088e-06 2.226242e-04
Comment on the estimated standard errors obtained using the glm() function and using your bootstrap function.
Answer: the Coefficient of Income is quite different between GLM and Bootstrap.
library(knitr)
library(kableExtra)
df <- data.frame(
Method = c("GLM", "Bootstrap"),
Income_SE = c(4.985e-06, 4.186088e-06),
Balance_SE = c(2.274e-04, 2.226242e-04)
)
kable(df, "html", caption = "Standard Error Comparison") %>%
kable_styling(
bootstrap_options = c("striped", "hover", "condensed", "responsive"),
full_width = FALSE,
position = "center"
) %>%
row_spec(0, bold = TRUE, background = "#DDEBF7") %>%
row_spec(1, background = "#F9F9F9") %>%
row_spec(2, background = "#F2F2F2")
Method | Income_SE | Balance_SE |
---|---|---|
GLM | 5.0e-06 | 0.0002274 |
Bootstrap | 4.2e-06 | 0.0002226 |
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 µ.
library(ISLR2)
Mu <- mean(Boston$medv)
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.
std <- sd(Boston$medv)
n <- length(Boston$medv)
# std error
stdError_Mu <- std / sqrt(n)
stdError_Mu
## [1] 0.4088611
Now estimate the standard error of µ using the bootstrap. How does this compare to your answer from (b)?
library(boot)
# Define Function
boot.fn <- function(data, index) {
return(mean(data[index]))
}
set.seed(1)
boot.out <- boot(data = Boston$medv, statistic = boot.fn, R = 100)
boot.out
##
## ORDINARY NONPARAMETRIC BOOTSTRAP
##
##
## Call:
## boot(data = Boston$medv, statistic = boot.fn, R = 100)
##
##
## Bootstrap Statistics :
## original bias std. error
## t1* 22.53281 0.009027668 0.3482331
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(ˆ µ)].
Low <- mean(Boston$medv) - 2 * sd(boot.out$t)
Up <- mean(Boston$medv) + 2 * sd(boot.out$t)
c(Low, Up)
## [1] 21.83634 23.22927
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
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
#Define Function
boot.fn <- function(data, index) {
return(median(data[index]))
}
set.seed(1)
boot.out <- boot(Boston$medv, boot.fn, R = 100)
boot.out
##
## ORDINARY NONPARAMETRIC BOOTSTRAP
##
##
## Call:
## boot(data = Boston$medv, statistic = boot.fn, R = 100)
##
##
## Bootstrap Statistics :
## original bias std. error
## t1* 21.2 -0.029 0.3461316
Mu_0.1 <- quantile(Boston$medv, probs = 0.1)
Mu_0.1
## 10%
## 12.75
Use the bootstrap to estimate the standard error ofˆµ0.1. Comment on your findings.
Answer: The estimated 10th percentile ㅑs about 12.75. The bootstrap standard error is approximately 0.54.
#Define Function
boot.fn <- function(data, index) {
quantile(data[index], probs = 0.1)
}
set.seed(1)
boot.out <- boot(Boston$medv, boot.fn, R = 100)
boot.out$t0 # 10th percentile
## 10%
## 12.75
sd(boot.out$t)
## [1] 0.5370477