3. We now review k-fold cross-validation.

(a) Explain how k-fold cross-validation is implemented.

K-fold cross-validation is implemented by randomly divide the observations, n, into numbers of k folds of equal size. Each fold is treated as a validation set once only and the remainding folds are fitted for training at every k times. Then the test estimate is calulated from the average of MSE (mean squared error).

(b) What are the advantages and disadvantages of k-fold cross-validation relative to:
i. The validation set approach?

In the k-fold cross-validation process, the entire datatset is used for training and validation while the validation set only uses a single train-test slipt. Therefore, the k-fold cross-validation provides more reliable estimate and reduce bias compared to the validation set approach. However, since k-fold cross-validation requires training and testing the dataset multiple times, it can pose problems such as higher cost and overfitting.

ii. LOOCV?

In LOOCV, k=n, meaning n can be really large. So in such case, k-fold cross-validation approach would be less expensive, more efficient, less sensitive to outliers, and more stable performance. However, LOOCV provides more unbias estimate due to its larger run times.

5. 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.
d0 <- glm(default ~ income + balance, family = "binomial", data = Default)
summary(d0)
## 
## 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
(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.
set.seed(123)

d0_split <- sample(nrow(Default), 0.8 * nrow(Default), replace = F) # 80/20 split
d0_train <- Default[d0_split, ]
d0_test <- Default[-d0_split, ]
ii. Fit a multiple logistic regression model using only the training observations.
d1 <- glm(default ~ income + balance, family = "binomial", data = d0_train)
summary(d1)
## 
## Call:
## glm(formula = default ~ income + balance, family = "binomial", 
##     data = d0_train)
## 
## Coefficients:
##               Estimate Std. Error z value Pr(>|z|)    
## (Intercept) -1.161e+01  4.884e-01  -23.78  < 2e-16 ***
## income       2.174e-05  5.602e-06    3.88 0.000104 ***
## balance      5.677e-03  2.548e-04   22.28  < 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: 2340.6  on 7999  degrees of freedom
## Residual deviance: 1258.1  on 7997  degrees of freedom
## AIC: 1264.1
## 
## 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.
predprob <- predict(d1, newdata = d0_test, type = "response")
predclass <- ifelse(predprob > 0.5, "Yes", "No")
iv. Compute the validation set error, which is the fraction of the observations in the validation set that are misclassified.
mean(predclass != d0_test$default)
## [1] 0.026
(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.
set.seed(123)

c_split1 <- sample(nrow(Default), 0.7 * nrow(Default), replace = F) # 70/30 split
c_train1 <- Default[c_split1, ]
c_test1 <- Default[c_split1, ]

c1 <- glm(default ~ income + balance, family = "binomial", data = c_train1)

c_predprob1 <- predict(c1, newdata = c_test1, type = "response")
c_predclass1 <- ifelse(c_predprob1 > 0.5, "Yes", "No")

mean(c_predclass1 != c_test1$default)
## [1] 0.02628571
set.seed(123)

c_split2 <- sample(nrow(Default), 0.6* nrow(Default), replace = F) # 60/40 split
c_train2 <- Default[c_split2, ]
c_test2 <- Default[c_split2, ]

c2 <- glm(default ~ income + balance, family = "binomial", data = c_train2)

c_predprob2 <- predict(c2, newdata = c_test2, type = "response")
c_predclass2 <- ifelse(c_predprob2 > 0.5, "Yes", "No")

mean(c_predclass2 != c_test2$default)
## [1] 0.02633333
set.seed(123)

c_split3 <- sample(nrow(Default), 0.5* nrow(Default), replace = F) # 50/50 split
c_train3 <- Default[c_split3, ]
c_test3 <- Default[c_split3, ]

c3 <- glm(default ~ income + balance, family = "binomial", data = c_train3)

c_predprob3 <- predict(c3, newdata = c_test3, type = "response")
c_predclass3 <- ifelse(c_predprob3 > 0.5, "Yes", "No")

mean(c_predclass3 != c_test3$default)
## [1] 0.0258

For the 80/20 split - Validation set error: 0.026 For the 70/30 split - Validation set error: 0.02628571 For the 60/40 split - Validation set error: 0.02633333 For the 50/50 split - Validation set error: 0.0258 Comparing differenlt splits, the validation errors has slight variations depending on the dataset split.

(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.
Default$student_dummy <- ifelse(Default$student == "Yes", 1, 0)

set.seed(123)
d2_split <- sample(1:nrow(Default), 0.7 * nrow(Default))
d2_train <- Default[d2_split, ]
d2_test <- Default[-d2_split, ]

d2 <- glm(default ~ income + balance + student_dummy, family = "binomial", data = d2_train)

d2_pred <- predict(d2, newdata = d2_test, type = "response")
d2_predclass <- ifelse(d2_pred > 0.5, "Yes", "No")

mean(d2_predclass != d2_test$default)
## [1] 0.027

A student dummy variable was created where yes = 1, and no=0. I wanted to use the 70/30 split for this question and the testing error increased from 0.026 to 0.027 after including the student dummy variable. Therefore, it is suggested that including a dummy variable for student leads to a reduction in the test error rate.

6. 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.
d0 <- glm(default ~ income + balance, family = "binomial", data = Default)
summary(d0)
## 
## 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

Standard error for the coefficient: Intercept: 4.348e-01 Income: 4.985e-06 Balance: 2.274e-04

(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) {
  model <- glm(default ~ income + balance, family = "binomial", data = data, subset= index)
  return(coef(model))}
(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(data = Default, statistic = 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 -2.781464e-02 4.199862e-01
## t2*  2.080898e-05  1.610485e-07 4.733164e-06
## t3*  5.647103e-03  1.305788e-05 2.215018e-04
(d) Comment on the estimated standard errors obtained using the glm() function and using your bootstrap function.

Bootstrap result: Intercept: 4.335388e-01 Income: 4.885399e-06 Balance: 2.268373e-04 Comparing both methods, it is clear that the estimated standard errors are relatively close with small variation.

9. 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(length(Boston$medv))
## [1] 0.4088611
(c) Now estimate the standard error of μˆ using the bootstrap. How does this compare to your answer from (b)?
boot_fn1 <- function(data, index) {
  data_subset <- data[index, ]
  return(mean(data_subset$medv))
}

library(boot)
set.seed(123) 
boot(data = Boston, statistic = 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.01607372   0.4045557

Standard error from (b):0.4088611 compare to 0.4045557 from using the bootstrap, they have similar estimate of standard error and the difference is very small (0.004).

(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(μˆ)].
c(mean(Boston$medv)-2*0.4045557, mean(Boston$medv)+2*0.4045557)
## [1] 21.72369 23.34192
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

95 percent confidence intervalfrom t test: [21.72953, 23.33608] 95 percent confidence intervalfrom bootstrap: [21.72369, 23.34192] Both results are very close with little variation.

(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.
boot.fn2 <- function(data, index) 
  { return (median(data[index]))}
boot(Boston$medv, boot.fn2, 1000)
## 
## ORDINARY NONPARAMETRIC BOOTSTRAP
## 
## 
## Call:
## boot(data = Boston$medv, statistic = boot.fn2, R = 1000)
## 
## 
## Bootstrap Statistics :
##     original  bias    std. error
## t1*     21.2 -0.0264   0.3783996

The mdian std. error is 0.3783996, which is close to the mean std. error of 0.4045557 but still relatively small.

(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, c(0.1))
##   10% 
## 12.75
(h) Use the bootstrap to estimate the standard error of μˆ0.1. Comment on your findings.
boot.fn3 <- function(data, index)
  {return (quantile(data[index], c(0.1)))}
boot(Boston$medv, boot.fn3, 1000)
## 
## ORDINARY NONPARAMETRIC BOOTSTRAP
## 
## 
## Call:
## boot(data = Boston$medv, statistic = boot.fn3, R = 1000)
## 
## 
## Bootstrap Statistics :
##     original  bias    std. error
## t1*    12.75 0.02485   0.5082798

The std error for tenth percentile of medv is 0.5082798, which is very high compare to both mean and median std error.