Question 3

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

K-fold cross-validation is a statistcal learning technique impleented in machine learning. THe process involves splitting a dataset into ‘k’ number of groups. You then fit a statistical model using 1 group as a training datset and the rest of the groups as the validation dataset. You then repreat the process using each of the groups as the training dataset, and calculating the performace of the model each time.

  1. What are the advantages and disadvantages of k-fold cross- validation relative to:
  1. The validation set approach? Advatages: K-fold cross-validation averages results over multiple splits, leading to more stable and reliable error estimates, while the validation set approach produces highly variable estimates of test error because the results depend on the specific random split of the data Disadvantages: K-fold cross-validation requires fitting the model k times which can be computationally expensive, especially for complex models or large datasets. With the validation set approach, the data only requires fitting once, which saves a lot of computational resources.

  2. LOOCV? Advatages: Similar to how the validation set approach saves more computational power than k-fold cross-validation due to the number of time the model is fitted, the k-fold cross-validation approach saves more computational power than LOOCV because in that approach the model needs to be fit n number of times where n is the number of observations in the dataset.

Disadvantages: K-fold cross validation can have slightly more bias since it does not use as much training data in each fold as LOOCV does. For the same reason, k-fold cross validation can also give different results depending on how the data is partitioned, while in LOOCV the result will always be consistent.

Question 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.

library(ISLR2)
  1. Fit a logistic regression model that uses income and balance to predict default.
d1 = Default
logit_model = glm(default~ income + balance, data = d1, family = binomial)
summary(logit_model)
## 
## Call:
## glm(formula = default ~ income + balance, family = binomial, 
##     data = d1)
## 
## 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
  1. Using the validation set approach, estimate the test error of this model. In order to do this, you must perform the following steps:
  1. Split the sample set into a training set and a validation set.
set.seed(69)

train = sample(x = c(TRUE, FALSE), size = nrow(d1), replace = TRUE)
train_data = d1[train, ]
validation_data = d1[!train, ]
  1. Fit a multiple logistic regression model using only the training observations.
logit_model = glm(default~ income + balance, data = train_data, family = binomial)
summary(logit_model)
## 
## Call:
## glm(formula = default ~ income + balance, family = binomial, 
##     data = train_data)
## 
## Coefficients:
##               Estimate Std. Error z value Pr(>|z|)    
## (Intercept) -1.118e+01  5.774e-01 -19.361  < 2e-16 ***
## income       2.070e-05  6.595e-06   3.139  0.00169 ** 
## balance      5.488e-03  3.002e-04  18.283  < 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: 1570.66  on 5010  degrees of freedom
## Residual deviance:  853.82  on 5008  degrees of freedom
## AIC: 859.82
## 
## Number of Fisher Scoring iterations: 8
  1. 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.
preds = predict(logit_model, newdata = validation_data, type =  "response")
pred_class = ifelse(preds > 0.5, "Yes", "No")
pred_class = factor(pred_class, levels = levels(Default$default))
validation_data$pred_class = pred_class
head(validation_data[, c("default", "pred_class")])
##    default pred_class
## 1       No         No
## 4       No         No
## 5       No         No
## 6       No         No
## 11      No         No
## 14      No         No
  1. Compute the validation set error, which is the fraction of the observations in the validation set that are misclassified.
test_error = mean(pred_class != validation_data$default)
test_error
## [1] 0.0244538
  1. 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(69)

train = sample(x = c(TRUE, FALSE), size = nrow(d1), replace = TRUE, prob = c(0.7, 0.3))
train_data = d1[train, ]
validation_data = d1[!train, ]

logit_model = glm(default~ income + balance, data = train_data, family = binomial)


preds = predict(logit_model, newdata = validation_data, type =  "response")
pred_class = ifelse(preds > 0.5, "Yes", "No")
pred_class = factor(pred_class, levels = levels(Default$default))
validation_data$pred_class = pred_class


test_error = mean(pred_class != validation_data$default)
test_error
## [1] 0.02610169
set.seed(69)

train = sample(x = c(TRUE, FALSE), size = nrow(d1), replace = TRUE, prob = c(0.8, 0.2))
train_data = d1[train, ]
validation_data = d1[!train, ]

logit_model = glm(default~ income + balance, data = train_data, family = binomial)
summary(logit_model)
## 
## Call:
## glm(formula = default ~ income + balance, family = binomial, 
##     data = train_data)
## 
## Coefficients:
##               Estimate Std. Error z value Pr(>|z|)    
## (Intercept) -1.170e+01  4.950e-01 -23.628  < 2e-16 ***
## income       2.625e-05  5.668e-06   4.632 3.62e-06 ***
## balance      5.609e-03  2.547e-04  22.026  < 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: 2283.5  on 8058  degrees of freedom
## Residual deviance: 1248.1  on 8056  degrees of freedom
## AIC: 1254.1
## 
## Number of Fisher Scoring iterations: 8
preds = predict(logit_model, newdata = validation_data, type =  "response")
pred_class = ifelse(preds > 0.5, "Yes", "No")
pred_class = factor(pred_class, levels = levels(Default$default))
validation_data$pred_class = pred_class


test_error = mean(pred_class != validation_data$default)
test_error
## [1] 0.0303967
set.seed(69)

train = sample(x = c(TRUE, FALSE), size = nrow(d1), replace = TRUE, prob = c(0.6, 0.4))
train_data = d1[train, ]
validation_data = d1[!train, ]

logit_model = glm(default~ income + balance, data = train_data, family = binomial)


preds = predict(logit_model, newdata = validation_data, type =  "response")
pred_class = ifelse(preds > 0.5, "Yes", "No")
pred_class = factor(pred_class, levels = levels(Default$default))
validation_data$pred_class = pred_class


test_error = mean(pred_class != validation_data$default)
test_error
## [1] 0.02499362
  1. 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(69)

train = sample(x = c(TRUE, FALSE), size = nrow(d1), replace = TRUE)
train_data = d1[train, ]
validation_data = d1[!train, ]

logit_model = glm(default~ income + balance + student, data = train_data, family = binomial)
summary(logit_model)
## 
## Call:
## glm(formula = default ~ income + balance + student, family = binomial, 
##     data = train_data)
## 
## Coefficients:
##               Estimate Std. Error z value Pr(>|z|)    
## (Intercept) -1.064e+01  6.549e-01 -16.248   <2e-16 ***
## income       6.487e-06  1.085e-05   0.598   0.5501    
## balance      5.569e-03  3.069e-04  18.145   <2e-16 ***
## studentYes  -5.326e-01  3.224e-01  -1.652   0.0985 .  
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## (Dispersion parameter for binomial family taken to be 1)
## 
##     Null deviance: 1570.66  on 5010  degrees of freedom
## Residual deviance:  851.11  on 5007  degrees of freedom
## AIC: 859.11
## 
## Number of Fisher Scoring iterations: 8
preds = predict(logit_model, newdata = validation_data, type =  "response")
pred_class = ifelse(preds > 0.5, "Yes", "No")
pred_class = factor(pred_class, levels = levels(Default$default))
validation_data$pred_class = pred_class
head(validation_data[, c("default", "pred_class")])
##    default pred_class
## 1       No         No
## 4       No         No
## 5       No         No
## 6       No         No
## 11      No         No
## 14      No         No
test_error = mean(pred_class != validation_data$default)
test_error
## [1] 0.02485468

Adding the student variable into the model resulted in a nearly identical test error as when it was not included.

Question 6

library(boot)

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.

logit_model2 = glm(default ~ income + balance, data = d1, family = binomial)
summary(logit_model2)
## 
## Call:
## glm(formula = default ~ income + balance, family = binomial, 
##     data = d1)
## 
## 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

The estimated standard error for income is 4.985e-06, and the estimated standard error for balance is 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) + coef(glm(default ~ income + balance, data = d1, subset = index, family = binomial))
set.seed(23)
boot.fn(d1, 1:10000)
##   (Intercept)        income       balance 
## -1.154047e+01  2.080898e-05  5.647103e-03

(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.

set.seed(23)
boot(d1, boot.fn, 1000)
## 
## ORDINARY NONPARAMETRIC BOOTSTRAP
## 
## 
## Call:
## boot(data = d1, statistic = boot.fn, R = 1000)
## 
## 
## Bootstrap Statistics :
##          original        bias     std. error
## t1* -1.154047e+01 -6.425518e-03 4.252997e-01
## t2*  2.080898e-05 -4.567628e-08 4.571768e-06
## t3*  5.647103e-03 -3.014214e-07 2.228104e-04

(d) Comment on the estimated standard errors obtained using the glm() function and using your bootstrap function.

The standard error for income using the bootstrap function is 4.571768e-06 which is smaller than using the glm() function. The standard error for balance using the bootstrap function is 2.228104e-04 which is smaller than using the glm() function.

Question 9

We will now consider the Boston housing data set, from the ISLR2 library.

Boston = Boston

(a) Based on this data set, provide an estimate for the population mean of medv. Call this estimate μˆ.

μ = mean(Boston$medv)
μ
## [1] 22.53281
  1. 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_medv = sd(Boston$medv)
n = nrow(Boston)
se = sd_medv / sqrt(n)
se
## [1] 0.4088611
  1. Now estimate the standard error of μˆ using the bootstrap. How does this compare to your answer from (b)?
boot.fn = function(data, index) {mean(data[index])}
set.seed(23)
boot_se = boot(Boston$medv, boot.fn, 1000)
boot_se
## 
## ORDINARY NONPARAMETRIC BOOTSTRAP
## 
## 
## Call:
## boot(data = Boston$medv, statistic = boot.fn, R = 1000)
## 
## 
## Bootstrap Statistics :
##     original      bias    std. error
## t1* 22.53281 -0.01904763   0.4000822

The standard error of μˆ was slightly smaller when estimated using bootstrap.

  1. 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*sd(boot_se$t), mean(Boston$medv) + 2*sd(boot_se$t))
## [1] 21.73264 23.33297
  1. Based on this data set, provide an estimate, μˆmed, for the median value of medv in the population.
μˆmed = median(Boston$medv)
μˆmed
## [1] 21.2
  1. 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.fn = function(data, index) {median(data[index])}
set.seed(23)
boot_se = boot(Boston$medv, boot.fn, 1000)
boot_se
## 
## ORDINARY NONPARAMETRIC BOOTSTRAP
## 
## 
## Call:
## boot(data = Boston$medv, statistic = boot.fn, R = 1000)
## 
## 
## Bootstrap Statistics :
##     original   bias    std. error
## t1*     21.2 -0.02375   0.3647828

The estimated standard error for the median value of medv is .3647828.

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

The estimated standard error for the 10th percentile of medv is .4964549 which is significatnly higher than the standard error for median.