5.4 EXERCISE: 3 (Conceptual)

We now review k-fold cross-validation

(3.0) We now review k-fold cross-validation
(3.a) Explain how k-fold cross-validation is implemented. (3.a) Answer: k-fold cross-validation is implemented by dividing the dataset of into k subsets of approximately equal size. In the first interation the first subset is treated as a held out test set, and the remaining k − 1 subsets are considered the train subset and used for the fit. 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.

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

(3.b.i) The validation set approach?
(3.b.i) Answer: The advantage of k-fold cross validation relative to the validation set approach is less bias and produces less variable MSE. k-fold cross validation can work better in situations where there are not many observations in a dataset and performing a large test train split will harm the accuracy. Also, the validation set approach estimate of the test error rate can be highly variable and can dependent on how homogeneous the train set is to the test set. The disadvantage of k-fold cross validation relative to the validation set approach is that the validation set approach is conceptually more simple and easier to implement.

(3.b.ii) LOOCV?
(3.b.ii) Answer: The advantages of k-fold cross validation relative to LOOCV is less bias. k-fold cross validation with k<n has a computational advantage to LOOCV and k-fold Cross validation usually gives more accurate estimates of the test error rate than LOOCV
The disadvantages of k-fold cross validation relative to LOOCV is more variance. With k<<n => increase in variability in the test error rate.

(3.4) Suppose that we use some statistical learning method to make a prediction for the response Y for a particular value of the predictor X. Carefully describe how we might estimate the standard deviation of our prediction.

(3.4) Answer: We might estimate the standard deviation of our prediction response Y (Y-hat) for a particular value of the predictor X by subtracting it from the mean of the Y-hats then square it. Then divide the squared difference by number of Y-hats minus 1. Finally, take the square root of that.
\[\sigma = \sqrt{\frac{\sum\limits_{i=1}^{n} \left(y_{i} - \bar{y}\right)^{2}} {n-1}}\]

5.4 EXERCISE: 5 (Applied)

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.

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

data(Default)

default_glm=glm(default~balance + income, Default,family=binomial)

(5.b) Using the validation set approach, estimate the test error of this model. In order to do this, you must perform the following steps

(5.b.i) Split the sample set into a training set and a validation set.

set.seed(1)

train_index2= sample(1:nrow(Default), nrow(Default)/2)
train2 = Default[train_index2, ]
test2= Default[-train_index2, ]

(5.b.ii) Fit a multiple logistic regression model using only the training observations.

default_train_glm2=glm(default~balance + income, train2,family=binomial)

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

pred2 = predict.glm(default_train_glm2, test2, type="response")

y_hats2 = ifelse(pred2>0.5, 2,1)

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

mean(as.numeric(test2$default) != y_hats2)  ## error rate
## [1] 0.0254

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

train_index5= sample(1:nrow(Default), nrow(Default)/5)
train5 = Default[train_index5, ]
test5= Default[-train_index5, ]
default_train_glm5=glm(default~balance + income, train5,family=binomial)
pred5 = predict.glm(default_train_glm5, test5, type="response")
y_hats5 = ifelse(pred5>0.5, 2,1)
mean(as.numeric(test5$default) != y_hats5)  ## error rate
## [1] 0.027
train_index10= sample(1:nrow(Default), nrow(Default)/10)
train10 = Default[train_index10, ]
test10= Default[-train_index10, ]
default_train_glm10=glm(default~balance + income, train10,family=binomial)
pred10 = predict.glm(default_train_glm10, test10, type="response")
y_hats10 = ifelse(pred10>0.5, 2,1)
mean(as.numeric(test10$default) != y_hats10)  ## error rate
## [1] 0.02877778
train_index20= sample(1:nrow(Default), nrow(Default)/20)
train20 = Default[train_index20, ]
test20= Default[-train_index20, ]
default_train_glm20=glm(default~balance + income, train20,family=binomial)
pred20 = predict.glm(default_train_glm20, test20, type="response")
y_hats20 = ifelse(pred20>0.5, 2,1)
mean(as.numeric(test20$default) != y_hats20)  ## error rate
## [1] 0.02873684

(5.c) Answer: When I repeated the process in (5.b) three times, using three different splits of the observations into a training set and a validation set I noticed that the error rate increased as the number of observations in the test set decreased.

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

library(fastDummies)
Default2 = dummy_cols(Default, select_columns = "student", remove_first_dummy = TRUE)

train3 = Default2[train_index2, ]
test3= Default2[-train_index2, ]
  
default_train_glm3=glm(default~balance + income + student_Yes, train3,family=binomial)
pred3 = predict.glm(default_train_glm3, test3, type="response")
y_hats3 = ifelse(pred3>0.5, 2,1)
mean(as.numeric(test3$default) != y_hats3)  ## error rate
## [1] 0.026

(5.d) Answer: Including a dummy variable for student leads to a increase in the test error rate

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

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

default_train_glm2=glm(default~balance + income, train2,family=binomial)
summary(default_train_glm2)
## 
## Call:
## glm(formula = default ~ balance + income, family = binomial, 
##     data = train2)
## 
## Deviance Residuals: 
##     Min       1Q   Median       3Q      Max  
## -2.5830  -0.1428  -0.0573  -0.0213   3.3395  
## 
## Coefficients:
##               Estimate Std. Error z value Pr(>|z|)    
## (Intercept) -1.194e+01  6.178e-01 -19.333  < 2e-16 ***
## balance      5.689e-03  3.158e-04  18.014  < 2e-16 ***
## income       3.262e-05  7.024e-06   4.644 3.41e-06 ***
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## (Dispersion parameter for binomial family taken to be 1)
## 
##     Null deviance: 1523.8  on 4999  degrees of freedom
## Residual deviance:  803.3  on 4997  degrees of freedom
## AIC: 809.3
## 
## Number of Fisher Scoring iterations: 8

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

(6.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 ,R=1000)
## 
## ORDINARY NONPARAMETRIC BOOTSTRAP
## 
## 
## Call:
## boot(data = Default, statistic = boot.fn, R = 1000)
## 
## 
## Bootstrap Statistics :
##          original        bias     std. error
## t1* -1.154047e+01 -3.893131e-02 4.348222e-01
## t2*  5.647103e-03  1.840984e-05 2.300926e-04
## t3*  2.080898e-05  1.595130e-07 4.863374e-06

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

(6.d) Answer: The estimated standard errors obtained using the glm() function are: SE(β0) = 0.6178, SE(β1) = 0.0003158, and SE(β2) = 0.000007024 The estimated standard errors obtained using the bootstrap function are: SE(β0) = 0.4525581, SE(β1) = 0.0002405548, and SE(β2) = 0.000004846872

5.4 EXERCISE: 9 (Applied)

(9.0) We will now consider the Boston housing data set, from the MASS library.

library(MASS)
data("Boston")
Boston=na.omit(Boston)

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

μ_hat=mean(Boston$medv); μ_hat
## [1] 22.53281

(9.b) Provide an estimate of the standard error of μ-hat. 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

SE = sd(Boston$medv)/sqrt(length(Boston$medv)); SE
## [1] 0.4088611

(9.c) Now estimate the standard error of μ-hat using the bootstrap. How does this compare to your answer from (9.b)?

#library(boot)

boot.fn=function (data ,index){
  return(mean(data[index]))}


bstrap = boot(Boston$medv, boot.fn, R=1000); bstrap
## 
## ORDINARY NONPARAMETRIC BOOTSTRAP
## 
## 
## Call:
## boot(data = Boston$medv, statistic = boot.fn, R = 1000)
## 
## 
## Bootstrap Statistics :
##     original     bias    std. error
## t1* 22.53281 0.01158913   0.4089034

(9.c) Answer: The estimated standard errors obtained in (9.b) is : \(\hat μ_{medv}=0.4088611\) The estimated standard errors obtained using the bootstrap is $μ_{medv}=0.4012126 $ … pretty close.

(9.d) Based on your bootstrap estimate from (9.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 [μ-hat − 2SE(μ-hat), μ-hat + 2SE(μ-hat)].

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
c(bstrap$t0 - 2 * 0.4119, bstrap$t0 + 2 * 0.4119) #[μ-hat − 2SE(μ-hat), μ-hat + 2SE(μ-hat)]
## [1] 21.70901 23.35661

(9.d) Answer: Bootstrap estimate is only 0.02053 away for t.test estimate.

(9.e) Based on this data set, provide an estimate, $μ_{medv} $ for the median value of medv in the population

medv_median = median(Boston$medv); medv_median
## [1] 21.2

(9.f) We now would like to estimate the standard error of $μ_{medv} $. 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){
  return(median(data[index]))}

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

(9.f) Answer: $μ_{medv}=21.2 $standard error of median of medv=0.3686977.

(9.g) Based on this data set, provide an estimate for the tenth percentile of medv in Boston suburbs. Call this quantity $μ_.1 $** (You can use the quantile() function.)**

μ_tilde_10percentile = quantile(Boston$medv, c(0.1)); μ_tilde_10percentile
##   10% 
## 12.75

(9.h) Use the bootstrap to estimate the standard error of $μ_.1 $Comment on your findings.

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

boot(Boston$medv, boot.fn, 1000)
## 
## ORDINARY NONPARAMETRIC BOOTSTRAP
## 
## 
## Call:
## boot(data = Boston$medv, statistic = boot.fn, R = 1000)
## 
## 
## Bootstrap Statistics :
##     original  bias    std. error
## t1*    12.75  0.0238   0.5103617

(9.h) Answer: The estimate for the tenth percentile of medv in Boston suburbs is 12.75 with a standard error of0.5053927.