Question 3:

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

The k-fold validation involves dividing a set of observations randomly and into equal groups, or folds. From there the first fold can be treated as the validation set, and the method is fit on the remaining folds. The mean-squared error (MSE) will then be computed on the observations in the hold-out fold. This will then be repeated k-amount of times, which results in k estimates of the test error. The average of these values are then used to compute the k-fold cross validation.

b. What are the advantages and disadvantages of k-fold cross-validation relative to:

-1.The validation set approach?

Advantages to the k-fold would include variability which is typically much lower than the variability in the test error estimates that result from the validation set approach. Disadvantages include the k-fold being more computationally expensive, fitting the model k amount of times. In comparison the validation set approach is much faster and simple than the k-fold cv, however there is higher variance and is not as reliable as the k-fold cv.

-2.LOOCV?

While the LOOCV is considered a special case of k-fold CV, the LOOCV requires fitting the statistical learning method n amount of times, while the k-fold CV performs best when k=5 or k=10, giving it a computational advantage over the LOOCV. Another advantage to the k-fold CV is that often times it will give more accurate statements of the test-error rate than the LOOCV. However when considering bias, the LOOCV outperforms the k-fold CV. The LOOCV will give approximately unbiased estimates of the test error, since the observations in each training set is n-1. Meanwhile the k-fold CV performs best at k=5 and k=10, which leads to an intermediate level of bias.

Question 5.

Estimate the test error of the logistic model using the validation set approach to predict the probability of default using income and balance on the Default data set.

a. Fit a logistic regression model that uses income and balance to predict default.

set.seed(1)

train <- sample(10000, 5000)

glm.fit <- glm(default ~ income + balance, data = Default, family = binomial, subset = train)

b. Using the validation set approach, estimate the test error of this model

glm.prob <- predict(glm.fit, newdata = Default[-train, ], type = "response")
glm.pred <- ifelse(glm.prob > 0.5, "Yes", "No")

err <- mean(glm.pred != Default$default[-train])

cat("Error:", err*100, "\n")
## Error: 2.54

c. repeat the process in (b) three times, using three different splits of the observations into a training set and validation set. Comment on the results obtained.

for (i in 1:3) {
  
set.seed(i)

train <- sample(10000, 5000)

glm.fit <- glm(default ~ income + balance, data = Default, family = binomial, subset = train)

glm.prob <- predict(glm.fit, newdata = Default[-train, ], type = "response")
glm.pred <- ifelse(glm.prob > 0.5, "Yes", "No")

err[i] <- mean(glm.pred != Default$default[-train])
}

data.frame(split = 1:3, error = err*100)
##   split error
## 1     1  2.54
## 2     2  2.38
## 3     3  2.64

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.

set.seed(1)

train <- sample(10000, 5000)

glm.fit2 <- glm(default ~ income + balance + student, data = Default, family = binomial, subset = train)


glm.prob2 <- predict(glm.fit2, newdata = Default[-train, ], type = "response")
glm.pred2 <- ifelse(glm.prob2 > 0.5, "Yes", "No")

err2 <- mean(glm.pred2 != Default$default[-train])

cat("Error:", err2*100, "\n")
## Error: 2.6

Adding the dummy variable, student, increased the error rate by .1 percent. Since the error rate showed little change, the variable student has little sway when predicting default.

Question 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 multiple logistic regression model that uses both predictors.

library(boot)
set.seed(1)

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

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 regression model.

boot.fn <- function(data, index) {
  coef(
    glm(default ~ income + balance, data = Default, family = binomial, subset = index)
  )
}

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(1)

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

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

summary(glm.fit)$coefficients
##                  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 bootstrap estimates of the standard errors(se) are similar to those of the glm() function. Both coefficients have small differences. The similarity between the two method suggest that the standard errors are reliable and the bootstrap confirms the stability of the coefficient estimates.

Question 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 ˆµ

set.seed(1)
mu.hat <- mean(Boston$medv)
mu.hat
## [1] 22.53281

b. Provide an estimate of the standard error of ˆµ Interpret this result.

se.mean <- sd(Boston$medv)/sqrt(nrow(Boston))
se.mean
## [1] 0.4088611

c. Now estimate the standard error of ˆµ using the bootstrap. How does this compare to your answer from (b)?

boot.mean <- function(data, index){
  mean(data[index])
}

boot.mean.out <- boot(Boston$medv, boot.mean, R = 1000)
boot.mean.out
## 
## ORDINARY NONPARAMETRIC BOOTSTRAP
## 
## 
## Call:
## boot(data = Boston$medv, statistic = boot.mean, R = 1000)
## 
## 
## Bootstrap Statistics :
##     original      bias    std. error
## t1* 22.53281 0.007650791   0.4106622
boot.se.mean <- sd(boot.mean.out$t)
boot.se.mean
## [1] 0.4106622

The standard error from part b and the bootstrap method are nearly identical. They show a difference less than .002 indicating roughly the same variability of medv, which would be about .41 units.

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 the t.test(Boston$medv).

lower <- mu.hat - 2*boot.se.mean
upper <- mu.hat + 2*boot.se.mean

c(lower, upper)
## [1] 21.71148 23.35413
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

Both produce similar confidence intervals.

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 your findings.

boot.med <- function(data, index) {
  median(data[index])
}

boot(Boston$medv, boot.med, R = 1000)
## 
## ORDINARY NONPARAMETRIC BOOTSTRAP
## 
## 
## Call:
## boot(data = Boston$medv, statistic = boot.med, R = 1000)
## 
## 
## Bootstrap Statistics :
##     original  bias    std. error
## t1*     21.2 -0.0386   0.3770241

Since the estimated standard error is small, this indicates that the median is stable.

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

mu.1 <- quantile(Boston$medv, .1)
mu.1
##   10% 
## 12.75

h. Use the bootstrap to estimate the standard error of ˆµ0.1. Comment on your findings.

boot.quantile <- function(data,index){
  quantile(data[index], .1)
}

boot.quant.out <- boot(Boston$medv, boot.quantile, R = 1000)
boot.quant.out
## 
## ORDINARY NONPARAMETRIC BOOTSTRAP
## 
## 
## Call:
## boot(data = Boston$medv, statistic = boot.quantile, R = 1000)
## 
## 
## Bootstrap Statistics :
##     original  bias    std. error
## t1*    12.75  0.0186   0.4925766
boot.se.quant <- sd(boot.quant.out$t)
boot.se.quant
## [1] 0.4925766

The bootstrap estimate shows that the 10th percentile has a sightly larger standard error than mean since quantiles are generally more variable than averages.