Exercise 3

We now review k-fold cross-validation.

(A)) Explain how k-fold cross-validation is implemented.

K-fold cross-validation is impemented as follows:

  1. Randomly divide the data set into K different groupd, or folds, of approximately equal size
  2. The first fold is treated as the validations set, and the method is fit on the remaining k-1 folds
  3. Compute the Mean Squared Error (MSE), for the held-out fold
  4. Repeat the above process k times; each time, a different group of observation is treated as the validation set
  5. Calculate the Cross-Validation (CV) by averaging the k estimates of the test error

(B) What are the advantages and disadvantages of k-fold crossvalidation relative to:

(i) The validation set approach?

      Advantages: This approach is conceptually simple and is easy to implement
      Disadvantages: The validation MSE can be highly variable and only one subset of the observations are used to fit the model which can lead to the MSE being overestimated.

(ii) LOOCV? | Advantages: First, this approach has less bias than the validation approach. Second, this approach yields` different MSE when applied repeatedly due to randomness in the splitting process, while performing LOOCV multiple times will always yield the same results, because we split based on 1 obs.

      Disadvantages: Leave-One-Out Cross-Validation has the potential to be computationally intensive and expensive to implement.

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

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

#Load the "Default" data set and produce a summary 
data("Default")
summary(Default)
##  default    student       balance           income     
##  No :9667   No :7056   Min.   :   0.0   Min.   :  772  
##  Yes: 333   Yes:2944   1st Qu.: 481.7   1st Qu.:21340  
##                        Median : 823.6   Median :34553  
##                        Mean   : 835.4   Mean   :33517  
##                        3rd Qu.:1166.3   3rd Qu.:43808  
##                        Max.   :2654.3   Max.   :73554
#Fit logistic regression model

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

  1. Split the sample set into a training set and a validation set.
set.seed(1)
lrm_split = initial_split(Default, strata = "default", prop = .8)
lrm_train = training(lrm_split)
lrm_test= testing (lrm_split)
  1. Fit a multiple logistic regression model using only the training observations.
lrm2 = glm(default~income+balance, data= lrm_train, family = "binomial")
summary(lrm2)
## 
## Call:
## glm(formula = default ~ income + balance, family = "binomial", 
##     data = lrm_train)
## 
## Deviance Residuals: 
##     Min       1Q   Median       3Q      Max  
## -2.4768  -0.1413  -0.0572  -0.0211   3.7332  
## 
## Coefficients:
##               Estimate Std. Error z value Pr(>|z|)    
## (Intercept) -1.165e+01  4.905e-01 -23.750  < 2e-16 ***
## income       2.320e-05  5.648e-06   4.107 4.01e-05 ***
## balance      5.647e-03  2.547e-04  22.173  < 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: 2306.8  on 7999  degrees of freedom
## Residual deviance: 1236.3  on 7997  degrees of freedom
## AIC: 1242.3
## 
## 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.
lrm_probs=predict(lrm2,lrm_test, type="response")
lrm_pred=ifelse(lrm_probs>.5,"Yes", "No")

(lrm_cm=table(lrm_pred, lrm_test$default))
##         
## lrm_pred   No  Yes
##      No  1919   55
##      Yes   10   16
  1. Compute the validation set error, which is the fraction of the observations in the validation set that are miss-classified.
(1-sum(diag(lrm_cm))/sum(lrm_cm))
## [1] 0.0325

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

First run with a 80/30 split.

set.seed(1)
lrm_split = initial_split(Default, strata = "default", prop = .7)
lrm_train = training(lrm_split)
lrm_test= testing (lrm_split)

lrm2 = glm(default~income+balance, data= lrm_train, family = "binomial")
summary(lrm2)
## 
## Call:
## glm(formula = default ~ income + balance, family = "binomial", 
##     data = lrm_train)
## 
## Deviance Residuals: 
##     Min       1Q   Median       3Q      Max  
## -2.1040  -0.1382  -0.0549  -0.0199   3.7311  
## 
## Coefficients:
##               Estimate Std. Error z value Pr(>|z|)    
## (Intercept) -1.190e+01  5.313e-01 -22.388  < 2e-16 ***
## income       2.529e-05  6.013e-06   4.206  2.6e-05 ***
## balance      5.776e-03  2.747e-04  21.029  < 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: 2084.0  on 6999  degrees of freedom
## Residual deviance: 1088.3  on 6997  degrees of freedom
## AIC: 1094.3
## 
## Number of Fisher Scoring iterations: 8
lrm_probs=predict(lrm2,lrm_test, type="response")
lrm_pred=ifelse(lrm_probs>.5,"Yes", "No")

(lrm_cm=table(lrm_pred, lrm_test$default))
##         
## lrm_pred   No  Yes
##      No  2895   71
##      Yes   11   23
(1-sum(diag(lrm_cm))/sum(lrm_cm))
## [1] 0.02733333

The error rate using a 70/30 split is 2.73%.

Second run with a 60/40 split

# First run with 70/30 split
set.seed(1)
lrm_split = initial_split(Default, strata = "default", prop = .6)
lrm_train = training(lrm_split)
lrm_test= testing (lrm_split)

lrm2 = glm(default~income+balance, data= lrm_train, family = "binomial")
summary(lrm2)
## 
## Call:
## glm(formula = default ~ income + balance, family = "binomial", 
##     data = lrm_train)
## 
## Deviance Residuals: 
##     Min       1Q   Median       3Q      Max  
## -2.0727  -0.1394  -0.0557  -0.0206   3.7090  
## 
## Coefficients:
##               Estimate Std. Error z value Pr(>|z|)    
## (Intercept) -1.186e+01  5.628e-01 -21.073  < 2e-16 ***
## income       2.704e-05  6.402e-06   4.224  2.4e-05 ***
## balance      5.725e-03  2.911e-04  19.668  < 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: 1813.94  on 5999  degrees of freedom
## Residual deviance:  943.73  on 5997  degrees of freedom
## AIC: 949.73
## 
## Number of Fisher Scoring iterations: 8
lrm_probs=predict(lrm2,lrm_test, type="response")
lrm_pred=ifelse(lrm_probs>.5,"Yes", "No")

(lrm_cm=table(lrm_pred, lrm_test$default))
##         
## lrm_pred   No  Yes
##      No  3863   91
##      Yes   13   33
(1-sum(diag(lrm_cm))/sum(lrm_cm))
## [1] 0.026

The error rate using a 60/40 split is 2.6%.

Third run with a 90/10 split.

# First run with 70/30 split
set.seed(1)
lrm_split = initial_split(Default, strata = "default", prop = .75)
lrm_train = training(lrm_split)
lrm_test= testing (lrm_split)

lrm2 = glm(default~income+balance, data= lrm_train, family = "binomial")
summary(lrm2)
## 
## Call:
## glm(formula = default ~ income + balance, family = "binomial", 
##     data = lrm_train)
## 
## Deviance Residuals: 
##     Min       1Q   Median       3Q      Max  
## -2.5127  -0.1391  -0.0556  -0.0203   3.7293  
## 
## Coefficients:
##               Estimate Std. Error z value Pr(>|z|)    
## (Intercept) -1.176e+01  5.094e-01  -23.09  < 2e-16 ***
## income       2.315e-05  5.831e-06    3.97 7.18e-05 ***
## balance      5.735e-03  2.648e-04   21.65  < 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: 2198.9  on 7499  degrees of freedom
## Residual deviance: 1156.6  on 7497  degrees of freedom
## AIC: 1162.6
## 
## Number of Fisher Scoring iterations: 8
lrm_probs=predict(lrm2,lrm_test, type="response")
lrm_pred=ifelse(lrm_probs>.5,"Yes", "No")

(lrm_cm=table(lrm_pred, lrm_test$default))
##         
## lrm_pred   No  Yes
##      No  2408   63
##      Yes   10   19
(1-sum(diag(lrm_cm))/sum(lrm_cm))
## [1] 0.0292

The error rate using a 90/10 split is 2.92%

The results identify that the validation estimate of the test error rate can be variable. This variability is a result of random selection of observations for the training set and the validation set.

(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)
lrm_split = initial_split(Default, strata = "default", prop = .8)
lrm_train = training(lrm_split)
lrm_test= testing (lrm_split)

lrm2 = glm(default~income+balance+student, data= lrm_train, family = "binomial")
summary(lrm2)
## 
## Call:
## glm(formula = default ~ income + balance + student, family = "binomial", 
##     data = lrm_train)
## 
## Deviance Residuals: 
##     Min       1Q   Median       3Q      Max  
## -2.4737  -0.1402  -0.0558  -0.0206   3.7343  
## 
## Coefficients:
##               Estimate Std. Error z value Pr(>|z|)    
## (Intercept) -1.106e+01  5.583e-01 -19.810   <2e-16 ***
## income       7.672e-06  9.331e-06   0.822    0.411    
## balance      5.724e-03  2.595e-04  22.056   <2e-16 ***
## studentYes  -5.672e-01  2.705e-01  -2.097    0.036 *  
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## (Dispersion parameter for binomial family taken to be 1)
## 
##     Null deviance: 2306.8  on 7999  degrees of freedom
## Residual deviance: 1232.0  on 7996  degrees of freedom
## AIC: 1240
## 
## Number of Fisher Scoring iterations: 8
lrm_probs=predict(lrm2,lrm_test, type="response")
lrm_pred=ifelse(lrm_probs>.5,"Yes", "No")

(lrm_cm=table(lrm_pred, lrm_test$default))
##         
## lrm_pred   No  Yes
##      No  1919   57
##      Yes   10   14
(1-sum(diag(lrm_cm))/sum(lrm_cm))
## [1] 0.0335

The error rate is 3.35%. The addition of the dummy variable student did not have a significant affect on the estamated error rate.

Exercise 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 computes 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.

lrm3=glm(default~income+balance, data= Default, family = "binomial")
summary(lrm3)
## 
## 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 income standard error is 4.985e-06. The balance standard error 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){
  boot_model = glm(default ~ income + balance, data = data, family = "binomial", subset = index)

return (coef(boot_model))
}

(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.143565e-02 4.227110e-01
## t2*  2.080898e-05 -2.321050e-07 5.175976e-06
## t3*  5.647103e-03  1.626487e-05 2.188357e-04

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

The estimated standard errors obtained by the two methods are very close.

Exercise 9

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

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

data(Boston)

(mean_estimate = mean (Boston$medv))
## [1] 22.53281

(B) Provide an estimate of the standard error of ˆµ. Interpret this result.

(se_estimate = sd(Boston$medv)/sqrt(nrow(Boston)))
## [1] 0.4088611

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

boot.fn2 = function(data, index){
 se_estimate = sd(Boston$medv[index])/sqrt(nrow(Boston))

return (se_estimate)
}

boot(Boston, boot.fn2,1000)
## 
## ORDINARY NONPARAMETRIC BOOTSTRAP
## 
## 
## Call:
## boot(data = Boston, statistic = boot.fn2, R = 1000)
## 
## 
## Bootstrap Statistics :
##      original        bias    std. error
## t1* 0.4088611 -0.0003119504  0.01606233

The standard errors of mean for a single mean and using the bootstrap method are the same.

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

(CI = c(22.53281 - 2 * 0.01671901,  22.53281 + 2 * 0.01671901))
## [1] 22.49937 22.56625
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

In the t-test the confidence interval is wider than using boot stap. Using the bootstrap is more precise because it delivers the same confidence level in a narrower range.

Note: I can trust that the average population of medv is between the range of 0.3754231 and 0.4422991. If i repeat this same process with different samples of the same size, I will be wrong only 5%.

Note:The standard error is the standard deviation of the average distribution

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

(med = 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 on your findings.

boot.fn3 = function(data, index){
 med_boot = median(Boston$medv[index])

return (med_boot)
}

boot(Boston, boot.fn3,1000)
## 
## ORDINARY NONPARAMETRIC BOOTSTRAP
## 
## 
## Call:
## boot(data = Boston, statistic = boot.fn3, R = 1000)
## 
## 
## Bootstrap Statistics :
##     original  bias    std. error
## t1*     21.2 0.02055   0.3779922

The average variation of the median of medv is 0.3804337

(G) Based on this data set, provide an estimate for the tenth percentile of medv in Boston suburbs. Call this quantity ˆµ0.1. (You can use the quantile() function.)

(tenth_quan = quantile(Boston$medv, .10))
##   10% 
## 12.75

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

boot.fn4 = function(data, index){
 tenth_quan_boot = quantile(Boston$medv[index], .10)

return (tenth_quan_boot)
}

boot(Boston, boot.fn4,1000)
## 
## ORDINARY NONPARAMETRIC BOOTSTRAP
## 
## 
## Call:
## boot(data = Boston, statistic = boot.fn4, R = 1000)
## 
## 
## Bootstrap Statistics :
##     original  bias    std. error
## t1*    12.75 -0.0213   0.5272611

The standard error for the 10th percentile of medv is 0.4950111