library(ISLR2)
library(MASS)
library(class)

3

We now review k-fold cross-validation.

(a) Explain how k-fold cross-validation is implemented.
Divide the set of observations into a “K” number of multiple random groups, or “folds”, that are approximately equal in size. The first fold is treated as a validation set. The method is fit on the remaining folds. The MSE is computed on the held out fold. Then the procedure is repeated K times, resulting in a K number of estimate errors; the measured performance is then averaged together.

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

i. The validation set approach?
The advantage in K-Fold over the validation set approach is that K-Fold has lower variability. In validation set approach, the fact that its only ever divided into two data sets, randomness plays a greater chance in our outcome, as we could happen to select a set of observations that drives particularly good or particularly poor performance on our test set. As a result, the validation set approach can over estimate the test error. The disadvantage here is that there is a little bit more computation requirements for K-Fold, and it is a little more complex to explain.

ii. LOOCV?
LOOCV is a special case of K-fold cross-validation. The advantage of using K is 5 or 10 is computational. LOOCV will fit a learning method for as many times as you have observations in your data set. LOOCV thus is more computationally expensive. The disadvantage is that there is still randomness in the observations selected in K-Fold. Additionally, there are situations where LOOCV doesn’t have the computational disadvantage discussed above.

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.

set.seed(1)
attach(Default)
head(Default)
##   default student   balance    income
## 1      No      No  729.5265 44361.625
## 2      No     Yes  817.1804 12106.135
## 3      No      No 1073.5492 31767.139
## 4      No      No  529.2506 35704.494
## 5      No      No  785.6559 38463.496
## 6      No     Yes  919.5885  7491.559

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

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

(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.
First, lets do a 75/25 split. Interestingly, a 60/40 split kept giving me a warning in step b.iii. longer object length is not a multiple of shorter object length, but 75/25 works without warning.

train=sample(dim(Default)[1], .75*dim(Default)[1])
head(train)
## [1] 1017 8004 4775 9725 8462 4050

ii. Fit a multiple logistic regression model using only the training observations.

glm.fit2=glm(default ~ income + balance, data = Default, subset = train, family = "binomial")
summary(glm.fit2)
## 
## Call:
## glm(formula = default ~ income + balance, family = "binomial", 
##     data = Default, subset = train)
## 
## Deviance Residuals: 
##     Min       1Q   Median       3Q      Max  
## -2.4675  -0.1399  -0.0557  -0.0207   3.3511  
## 
## Coefficients:
##               Estimate Std. Error z value Pr(>|z|)    
## (Intercept) -1.171e+01  5.071e-01 -23.098  < 2e-16 ***
## income       2.515e-05  5.803e-06   4.334 1.47e-05 ***
## balance      5.622e-03  2.612e-04  21.526  < 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: 2178.7  on 7499  degrees of freedom
## Residual deviance: 1157.7  on 7497  degrees of freedom
## AIC: 1163.7
## 
## 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.

glm.probs = predict(glm.fit2, Default[-train, ], type = "response")
glm.preds = rep("No", dim(Default)[1])
glm.preds[glm.probs > 0.5] = "Yes"

To conduct this step, we filled the variable full of “No” and then changed it to “Yes” when the posterior probability of default was over 50%.

iv. Compute the validation set error, which is the fraction of the observations in the validation set that are mis-classified.

mean(glm.preds != Default[-train, "default"])
## [1] 0.026

2.6% of our data on this split are mis-classified.

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

train=sample(dim(Default)[1], .75*dim(Default)[1])
glm.probs = predict(glm.fit2, Default[-train, ], type = "response")
glm.preds = rep("No", dim(Default)[1])
glm.preds[glm.probs > 0.5] = "Yes"
mean(glm.preds != Default[-train, "default"])
## [1] 0.028

Combining the code blocks from the previous section and running it again will generate a different set of data being included in the training and set data. The second run was 2.8%

train=sample(dim(Default)[1], .75*dim(Default)[1])
glm.probs = predict(glm.fit2, Default[-train, ], type = "response")
glm.preds = rep("No", dim(Default)[1])
glm.preds[glm.probs > 0.5] = "Yes"
mean(glm.preds != Default[-train, "default"])
## [1] 0.0244

The third run was 2.44%

train=sample(dim(Default)[1], .75*dim(Default)[1])
glm.probs = predict(glm.fit2, Default[-train, ], type = "response")
glm.preds = rep("No", dim(Default)[1])
glm.preds[glm.probs > 0.5] = "Yes"
mean(glm.preds != Default[-train, "default"])
## [1] 0.024

The final run was 2.4%. All runs were between 2.4 and 2.8%.

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

To do this, we’ll make a new variable for isStudent that takes 0 for no and 1 for yes, by using an ifelse statement to build the variable, and then stick that into a new dataset we’ll call Default2.

isStudent = ifelse(Default$student == 'Yes',1,0)
Default2= data.frame(default=default, isStudent=isStudent, balance=balance, income=income)
head(Default2)
##   default isStudent   balance    income
## 1      No         0  729.5265 44361.625
## 2      No         1  817.1804 12106.135
## 3      No         0 1073.5492 31767.139
## 4      No         0  529.2506 35704.494
## 5      No         0  785.6559 38463.496
## 6      No         1  919.5885  7491.559

We can see the new variable seems to have worked. Now to rerun the code block with the new dataset and variable.

train=sample(dim(Default2)[1], .75*dim(Default2)[1])
glm.fit3=glm(default ~ income + balance + isStudent, data = Default2, subset = train, family = "binomial")
glm.probs = predict(glm.fit3, Default2[-train, ], type = "response")
glm.preds = rep("No", dim(Default2)[1])
glm.preds[glm.probs > 0.5] = "Yes"
mean(glm.preds != Default2[-train, "default"])
## [1] 0.0288

Adding in this variable appears to have slightly increased our error rate. In reviewing other analysts work on this problem, I see that the community appears split on small decrease or increase. Lets rerun it a couple of times.

train=sample(dim(Default2)[1], .75*dim(Default2)[1])

glm.probs = predict(glm.fit3, Default2[-train, ], type = "response")
glm.preds = rep("No", dim(Default2)[1])
glm.preds[glm.probs > 0.5] = "Yes"
mean(glm.preds != Default2[-train, "default"])
## [1] 0.0248
train=sample(dim(Default2)[1], .75*dim(Default2)[1])

glm.probs = predict(glm.fit3, Default2[-train, ], type = "response")
glm.preds = rep("No", dim(Default2)[1])
glm.preds[glm.probs > 0.5] = "Yes"
mean(glm.preds != Default2[-train, "default"])
## [1] 0.0308

After several runs, adding in a dummy variable for student appears to slightly increase the 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.

set.seed(1)

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

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

The estimated standard error for the coefficient of income is \(4.985 x 10^{-6}\)
The estimated standard error for the coefficient of balance is \(2.274 x 10^{-4}\)

(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){
    coefs = coef(glm(default ~ income + balance, data = data, subset = index, family = "binomial"))[c("income", "balance")]
    return(coefs)
}

(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(Default,boot.fn, 50)
## 
## ORDINARY NONPARAMETRIC BOOTSTRAP
## 
## 
## Call:
## boot(data = Default, statistic = boot.fn, R = 50)
## 
## 
## Bootstrap Statistics :
##         original        bias     std. error
## t1* 2.080898e-05 -7.436578e-08 4.456965e-06
## t2* 5.647103e-03  1.854126e-05 2.639029e-04

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

When running boot, the standard error for income become \(4.346 x 10^{-6}\) and balance became \(2.076 x 10^{-4}\). These values are close to when we ran just the glm() function. This could indicate the assumptions for the standard error estimates are satisfactory.

9

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

detach(Default)
attach(Boston)

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

mean(medv)
## [1] 22.53281

Estimate of the population mean for medv is 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(medv) / sqrt(length(medv))
## [1] 0.4088611

The estimate of the standard error of ˆµ is .4088611. With a small standard error, it means that ˆµ of medv is close to the true mean.

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

set.seed(1)
boot.fn = function(data,index){
  return(mean(data[index]))
}
se = boot(medv, boot.fn, 1000)
se
## 
## ORDINARY NONPARAMETRIC BOOTSTRAP
## 
## 
## Call:
## boot(data = medv, statistic = boot.fn, R = 1000)
## 
## 
## Bootstrap Statistics :
##     original      bias    std. error
## t1* 22.53281 0.007650791   0.4106622

The standard error is very close, but different. With boot, it is .4107 and without, it is .4089.

(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(se$t0 - 2 * 0.4107, se$t0 + 2 * 0.4107)
## [1] 21.71141 23.35421
t.test(medv)
## 
##  One Sample t-test
## 
## data:  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

The lower value for the t-test is 21.7295, and with boot it is 21.7114. The upper value of t-test is 23.3361, and with boot it is 23.3542. In both cases, the values are very close.

(e) Based on this data set, provide an estimate, ˆµmed, for the median value of medv in the population.

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

set.seed(1)
boot.fn = function(data,index){
  return(median(data[index]))
}
se = boot(medv, boot.fn, 1000)
se
## 
## ORDINARY NONPARAMETRIC BOOTSTRAP
## 
## 
## Call:
## boot(data = medv, statistic = boot.fn, R = 1000)
## 
## 
## Bootstrap Statistics :
##     original  bias    std. error
## t1*     21.2 0.02295   0.3778075

Reusing code in part c but with median instead of mean, we get .3778 standard error. Once again, the result is 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.)

mu_hat_0.1=quantile(medv, 0.1)
mu_hat_0.1
##   10% 
## 12.75

As we are looking for the tenth percentile, we’ll use .1 with quantile.

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

set.seed(1)
boot.fn.quan = function(data, index){
  return(quantile(data[index], c(0.1)))}

se = boot(medv, boot.fn.quan, 1000)
se
## 
## ORDINARY NONPARAMETRIC BOOTSTRAP
## 
## 
## Call:
## boot(data = medv, statistic = boot.fn.quan, R = 1000)
## 
## 
## Bootstrap Statistics :
##     original  bias    std. error
## t1*    12.75  0.0339   0.4767526

This standard error is still small, albeit not as small as with mean and median at .4768.