library(tidyverse)
## ── Attaching packages ─────────────────────────────────────── tidyverse 1.3.2 ──
## ✔ ggplot2 3.4.0      ✔ purrr   0.3.5 
## ✔ tibble  3.1.8      ✔ dplyr   1.0.10
## ✔ tidyr   1.2.1      ✔ stringr 1.5.0 
## ✔ readr   2.1.3      ✔ forcats 0.5.2 
## ── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
## ✖ dplyr::filter() masks stats::filter()
## ✖ dplyr::lag()    masks stats::lag()
library(readxl)
library(tinytex)
library(ISLR)
library(ISLR2)
## 
## Attaching package: 'ISLR2'
## 
## The following objects are masked from 'package:ISLR':
## 
##     Auto, Credit
library(MASS)
## 
## Attaching package: 'MASS'
## 
## The following object is masked from 'package:ISLR2':
## 
##     Boston
## 
## The following object is masked from 'package:dplyr':
## 
##     select
library(class)
library(e1071)
library(boot)
library(caret)
## Loading required package: lattice
## 
## Attaching package: 'lattice'
## 
## The following object is masked from 'package:boot':
## 
##     melanoma
## 
## 
## Attaching package: 'caret'
## 
## The following object is masked from 'package:purrr':
## 
##     lift

PROBLEM 3

We now review k-fold cross-validation.

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

“This approach involves randomly k-fold CV dividing the set of observations into k groups, or folds, of approximately equal size. The first fold is treated as a validation set, and the method is fit on the remaining k − 1 folds. The mean squared error, MSE1, is then computed on the observations in the held-out fold. This procedure is repeated k times; each time, a different group of observations is treated as a validation set. This process results in k estimates of the test error, MSE1,MSE2, . . . ,MSEk. The k-fold CV estimate is computed by averaging these values.” (James 203)

  1. What are the advantages and disadvantages of k-fold crossvalidation relative to:
  1. The validation set approach?
  2. LOOCV?
  1. The validation set approach can lead to overestimates of the test error rate, while the k-fold CV can introduce “intermediate bias”. However, k-fold CV has a lower variance.

  2. K-fold CV has a computational advantage but also provides more accurate estimates of the test error rate. But again k-fold CV can introduce more bias than LOOCV which is relatively unbiased estimates of the test error rate.

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

  1. Fit a logistic regression model that uses income and balance to predict default.
log.default <- glm(default~income+balance, data=Default, family = 'binomial')

summary(log.default)
## 
## Call:
## glm(formula = default ~ income + balance, family = "binomial", 
##     data = Default)
## 
## Deviance Residuals: 
##     Min       1Q   Median       3Q      Max  
## -2.4725  -0.1444  -0.0574  -0.0211   3.7245  
## 
## 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(1)

index <- createDataPartition(y = Default$default, p = .75, list = FALSE)

train <- Default[index,]
test <- Default[-index,]
  1. Fit a multiple logistic regression model using only the training observations.
trainlog.default <- glm(default~income+balance, data=train, family = 'binomial')

summary(trainlog.default)
## 
## Call:
## glm(formula = default ~ income + balance, family = "binomial", 
##     data = train)
## 
## Deviance Residuals: 
##     Min       1Q   Median       3Q      Max  
## -2.4142  -0.1450  -0.0581  -0.0219   3.7082  
## 
## Coefficients:
##               Estimate Std. Error z value Pr(>|z|)    
## (Intercept) -1.128e+01  4.961e-01 -22.730   <2e-16 ***
## income       1.679e-05  5.802e-06   2.895   0.0038 ** 
## balance      5.558e-03  2.580e-04  21.539   <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: 2192.2  on 7500  degrees of freedom
## Residual deviance: 1184.4  on 7498  degrees of freedom
## AIC: 1190.4
## 
## 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.
glm.probs <- predict(trainlog.default, newdata=test, type = 'response')
glm.predict <- rep("No", length(glm.probs))
glm.predict[glm.probs >.5] <- "Yes"
  1. Compute the validation set error, which is the fraction of the observations in the validation set that are misclassified.
mean(glm.predict != test)
## [1] 0.5833333
  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.
index1 <- createDataPartition(y=Default$default, p = .99, list = FALSE)

train1 <- Default[index1,]
test1 <- Default[-index1,]

trainlog.default1 <- glm(default~income+balance, data=train1, family = 'binomial')

glm.probs1 <- predict(trainlog.default1, newdata =  test1, type = 'response')
glm.predict1 <- rep("No", length(glm.probs1))
glm.predict1[glm.probs1 >.5] <- "Yes"

mean(glm.predict1 != test1)
## [1] 0.5757576
index2 <- createDataPartition(y = Default$default, p = .7, list = FALSE)

train2 <- Default[index2,]
test2 <- Default[-index2,]

trainlog.default2 <- glm(default~income+balance, data=train2, family = 'binomial')

glm.probs2 <- predict(trainlog.default2, newdata =  test2, type = 'response')
glm.predict2 <- rep("No", length(glm.probs2))
glm.predict2[glm.probs2 >.5] <- "Yes"

mean(glm.predict2 != test2)
## [1] 0.581944
index3 <- createDataPartition(y = Default$default, p = .25, list = FALSE)

train3 <- Default[index3,]
test3 <- Default[-index3,]

trainlog.default3 <- glm(default~income+balance, data=train3, family = 'binomial')

glm.probs3 <- predict(trainlog.default3, newdata =  test3, type = 'response')
glm.predict3 <- rep("No", length(glm.probs3))
glm.predict3[glm.probs >.5] <- "Yes"

mean(glm.predict3 != test3)
## [1] 0.5854447

Using p=.99, .7, and .25 yields error results that are between 57% to 59%

  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.
index4 <- createDataPartition(y = Default$default, p = .75, list = FALSE)

train4 <- Default[index4,]
test4 <- Default[-index4,]


trainlog.default4 <- glm(default~income+balance+student, data=train4, family = 'binomial')

glm.probs4 <- predict(trainlog.default4, newdata =  test4, type = 'response')
glm.predict4 <- rep("No", length(glm.probs4))
glm.predict4[glm.probs >.5] <- "Yes"

mean(glm.predict4 != test4)
## [1] 0.5833333

We get about the same error rate with or without the dummy variable.

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

set.seed(1)

fit6 <- glm(default~income+balance, data=Default, family = 'binomial')

summary(fit6)$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
  1. 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) {
  fit1 <- glm(default~income+balance, data=data, family = 'binomial', subset = index)
  return(coef(fit1))
}

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

boot(Default, boot.fn, 500)
## 
## ORDINARY NONPARAMETRIC BOOTSTRAP
## 
## 
## Call:
## boot(data = Default, statistic = boot.fn, R = 500)
## 
## 
## Bootstrap Statistics :
##          original        bias     std. error
## t1* -1.154047e+01 -2.298134e-02 4.212334e-01
## t2*  2.080898e-05 -2.053140e-07 5.184890e-06
## t3*  5.647103e-03  1.678038e-05 2.178846e-04
  1. Comment on the estimated standard errors obtained using the glm() function and using your bootstrap function.

The bootstrap function with using the glm function return values for std. error of t1=4.212, t2=5.184, and t3=2.179

PROBLEM 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 ˆµ.

muhat <- mean(Boston$medv)
muhat
## [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.

stderrhat <- sd(Boston$medv) / sqrt(dim(Boston)[1])
stderrhat
## [1] 0.4088611

We compute that our sample will be .409 deviations from the population mean.

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

bootfn <- function(data, index) 
{
    muhat <- mean(data[index])
    return (muhat)
}

bootst <- boot(Boston$medv, bootfn, 500)
bootst
## 
## ORDINARY NONPARAMETRIC BOOTSTRAP
## 
## 
## Call:
## boot(data = Boston$medv, statistic = bootfn, R = 500)
## 
## 
## Bootstrap Statistics :
##     original       bias    std. error
## t1* 22.53281 -0.008388933   0.4106569

It is on the lower end but only marginally.

(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(ˆµ)].

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
confintr <- c(bootst$t0 - 2 * .408, bootst$t0 + 2 * .408)
confintr
## [1] 21.71681 23.34881
  1. Based on this data set, provide an estimate, ˆµmed, for the median value of medv in the population.
medianhat <- median(Boston$medv)
medianhat
## [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.
bootfn <- function(data, index) 
{
    medianhat <- median(data[index])
    return (medianhat)
}

boot(Boston$medv, bootfn, 500)
## 
## ORDINARY NONPARAMETRIC BOOTSTRAP
## 
## 
## Call:
## boot(data = Boston$medv, statistic = bootfn, R = 500)
## 
## 
## Bootstrap Statistics :
##     original  bias    std. error
## t1*     21.2 -0.0403    0.393396

The results return values that would lead us to believe the medians are similar and not statistically different.

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

Using the results from the test we can conclude a C.I. of (12.25, 13.25)