Q3.

We now review k-fold cross-validation.

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

The k-fold cross validation is implemented by taking the amount of observations, n, and randomly splitting them into k, non-overlapping groups of length of approximately n/k. These groups act as a validation set, and the remainder acts as a training set.

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

  1. The validation set approach? Advantage is that this is simple approach, disadvantage is that test error rate can be highly variable, and validation set error rate may tend to overestimate the test error rate for the model fit on the entire data set.

  2. LOOCV? Advantage, LOOCV has less bias. The validation approach produces 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. each time. But because it is performed multiple times, this can be computationally expensive.

Q5.

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.

library(ISLR)
library(MASS)
set.seed(1)
fit.glm = glm(default ~ income + balance, data = Default, family = "binomial")
summary(fit.glm)
## 
## 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
pred<-predict(fit.glm,Default,type="response")
pred.class<-ifelse(pred>0.5,"Yes","No")
round(mean(Default$default!=pred.class),4)
## [1] 0.0263

The model gives us a misclassification rate of 2.6%

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.

train = sample(dim(Default)[1], dim(Default)[1] / 2)

ii.)

Fit a multiple logistic regression model using only the train- ing observations.

fit.glm1 = glm(default ~ income + balance, data = Default[train,], family = "binomial")
summary(fit.glm1)
## 
## Call:
## glm(formula = default ~ income + balance, family = "binomial", 
##     data = Default[train, ])
## 
## 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 ***
## income       3.262e-05  7.024e-06   4.644 3.41e-06 ***
## balance      5.689e-03  3.158e-04  18.014  < 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: 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

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.

pred1<-predict(fit.glm1,Default[-train, ],type="response")
class1<-ifelse(pred1>0.5,"Yes","No")

iv.)

table(Default[-train, ]$default,class1,dnn=c("Actual","Predicted"))
##       Predicted
## Actual   No  Yes
##    No  4824   19
##    Yes  108   49
round(mean(class1!=Default[-train, ]$default),4)
## [1] 0.0254

The validation approach gives us a 2.54% test error.

c.)

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

80/20 split
set.seed(1)
subset8<-sample(nrow(Default),nrow(Default)*0.8)
default.train8<-Default[subset8,]
default.test8<-Default[-subset8,]
fit.glm8<-glm(default~income+balance,family = binomial,data=default.train8)
pred8<-predict(fit.glm8,default.test8,type="response")
class8<-ifelse(pred8>0.5,"Yes","No")
mean8<-round(mean(class8!=default.test8$default),4)
print(mean8)
## [1] 0.026
70/30 split
set.seed(1)
subset7<-sample(nrow(Default),nrow(Default)*0.7)
default.train7<-Default[subset7,]
default.test7<-Default[-subset7,]
fit.glm7<-glm(default~income+balance,family = binomial,data=default.train7)
pred7<-predict(fit.glm7,default.test7,type="response")
class7<-ifelse(pred7>0.5,"Yes","No")
mean7<-round(mean(class7!=default.test7$default),4)
print(mean8)
## [1] 0.026
50/50 split
set.seed(1)
subset5<-sample(nrow(Default),nrow(Default)*0.5)
default.train5<-Default[subset5,]
default.test5<-Default[-subset5,]
fit.glm5<-glm(default~income+balance,family = binomial,data=default.train5)
pred5<-predict(fit.glm5,default.test5,type="response")
class5<-ifelse(pred5>0.5,"Yes","No")
mean5<-round(mean(class5!=default.test5$default),4)
print(mean5)
## [1] 0.0254

The error rate for all 3 different splits is almost the same, except the 50/50 split has an error rate of 2.54% and the 80/20 and 70/30 split has an error rate of 2.6%.

d.)

Now consider a logistic regression model that predicts the prob- ability 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)
subset_dummy<-sample(nrow(Default),nrow(Default)*0.5)
default.train_dummy<-Default[subset_dummy,]
default.test_dummy<-Default[-subset_dummy,]
fit.glm_dummy<-glm(default~income+balance+student,family = binomial,data=default.train_dummy)

summary(fit.glm_dummy)
## 
## Call:
## glm(formula = default ~ income + balance + student, family = binomial, 
##     data = default.train_dummy)
## 
## Deviance Residuals: 
##     Min       1Q   Median       3Q      Max  
## -2.5823  -0.1419  -0.0554  -0.0210   3.3961  
## 
## Coefficients:
##               Estimate Std. Error z value Pr(>|z|)    
## (Intercept) -1.134e+01  6.937e-01 -16.346   <2e-16 ***
## income       1.686e-05  1.122e-05   1.502   0.1331    
## balance      5.767e-03  3.213e-04  17.947   <2e-16 ***
## studentYes  -5.992e-01  3.324e-01  -1.803   0.0715 .  
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## (Dispersion parameter for binomial family taken to be 1)
## 
##     Null deviance: 1523.77  on 4999  degrees of freedom
## Residual deviance:  800.07  on 4996  degrees of freedom
## AIC: 808.07
## 
## Number of Fisher Scoring iterations: 8
pred_dummy<-predict(fit.glm_dummy,default.test_dummy,type="response")
class_dummy<-ifelse(pred_dummy>0.5,"Yes","No")

table(default.test_dummy$default,class_dummy,dnn=c("Actual","Predicted"))
##       Predicted
## Actual   No  Yes
##    No  4825   18
##    Yes  112   45
round(mean(class_dummy!=default.test_dummy$default),4)
## [1] 0.026

The mis-classification rate when introducing a dummy variable 0.026, or 2.6%, which is similar to the previous models.

Q6.

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)
fit.glm_new<-glm(default~income+balance,family = binomial,data=Default)
summary(fit.glm_new)
## 
## 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 errors for the coefficients are 4.348e-01, 4.985e-06, 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){
  fit_boot<-glm(default~income+balance,data=data,family="binomial",subset=index)
  return(coef(fit_boot))
}

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,100)
## 
## ORDINARY NONPARAMETRIC BOOTSTRAP
## 
## 
## Call:
## boot(data = Default, statistic = boot.fn, R = 100)
## 
## 
## Bootstrap Statistics :
##          original        bias     std. error
## t1* -1.154047e+01  8.556378e-03 4.122015e-01
## t2*  2.080898e-05 -3.993598e-07 4.186088e-06
## t3*  5.647103e-03 -4.116657e-06 2.226242e-04

d.)

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

The standard errors obtained with both methods are very similar.

Q9.

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 μˆ.

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

sample_se<-sd(medv)/sqrt(nrow(Boston))
sample_se
## [1] 0.4088611

c.)

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

library(boot)
set.seed(1)
boot.fn<-function(data,index){
  mu<-mean(data[index])
  return(mu)
}
set.seed(1)
boot(medv,boot.fn,100)
## 
## ORDINARY NONPARAMETRIC BOOTSTRAP
## 
## 
## Call:
## boot(data = medv, statistic = boot.fn, R = 100)
## 
## 
## Bootstrap Statistics :
##     original      bias    std. error
## t1* 22.53281 0.009027668   0.3482331

The standard error from bootstraping looks to be lower than before.

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(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
ci.mu<-c(sample_mu-2*0.3815554,sample_mu+2*0.3815554)
ci.mu
## [1] 21.76970 23.29592

The confidence interval is similar to the t-test.

e.)

Based on this data set, provide an estimate, μˆ value of medv in the population.

mu_median<-median(medv)
mu_median
## [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.

library(boot)
set.seed(1)
boot.fn<-function(data,index){
  mu.median<-median(data[index])
  return(mu.median)
}
set.seed(1)
boot(medv,boot.fn,100)
## 
## ORDINARY NONPARAMETRIC BOOTSTRAP
## 
## 
## Call:
## boot(data = medv, statistic = boot.fn, R = 100)
## 
## 
## Bootstrap Statistics :
##     original  bias    std. error
## t1*     21.2  -0.029   0.3461316

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

mu.quantile<-quantile(medv,c(0.1))
mu.quantile
##   10% 
## 12.75

h.)

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

boot.fn <- function(data, index) {
  mu.quantile <- quantile(data[index], c(0.1))
  return (mu.quantile)
}
boot(medv, boot.fn, 1000)
## 
## ORDINARY NONPARAMETRIC BOOTSTRAP
## 
## 
## Call:
## boot(data = medv, statistic = boot.fn, R = 1000)
## 
## 
## Bootstrap Statistics :
##     original  bias    std. error
## t1*    12.75  0.0285   0.4861472

The standard error of .48614 from the bootstrap method is small compared to the tenth percentile we obtained.