Chapter 5

Exercise 3

We now review k-fold cross-validation.

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

This approach involves randomly dividing the sample data into k parts, 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. This approach uses k-1 of the parts for training and 1 for testing. This procedure is repeated k times, rotating the test set. Each time a different group of observations is treated as a validation set. This process results in k estimates of the test error. The k-fold CV estimate is computed by averaging these values.

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

i. The validation set approach?

Advantages:The validation set approach is conceptually simple and is easy to implement.

Disadvantages: The estimate of the test error rate can be highly variable depending on which observations are included in the training and validation sets. The validation set error rate may tend to overestimate the test error rate for the model fit on the entire data set.

ii. LOOCV?

Advantages: LOOCV have lower bias than k-fold CV. 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.

Disadvantage: LOOCV is computationally intensive

Exercise 5

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

library(ISLR)
data('Default') #Read the default data
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
logmodel1 = glm(default ~ balance + income, data = Default, family = binomial) #Fit a logistic regression model that uses income and balance to predict default

summary(logmodel1)
## 
## Call:
## glm(formula = default ~ balance + income, 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 ***
## balance      5.647e-03  2.274e-04  24.836  < 2e-16 ***
## income       2.081e-05  4.985e-06   4.174 2.99e-05 ***
## ---
## 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.

In the validation set approach, before we begin, we use the set.seed() function in order to set a for R’s random number generator. Then We begin by using the sample() function to split the set of observations into two halves. We refer to these observations as the training set.

set.seed(1)
train <- sample(dim(Default)[1], dim(Default)[1]*0.50)  # Training set 
valid <- Default[-train, ]   #Validation set

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

We use the subset option in glm() to fit a multiple logistic regression model using only the observations corresponding to the training set.

mod = glm(default ~ balance + income, data = Default, family = binomial, subset = train)

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.

We use the predict() function to estimate the response for validation set.

pred = predict(mod, valid, type = "response")
pred_def = rep("No", dim(Default)[1]*0.50)
pred_def[pred > 0.5] = "Yes"
table(pred_def, valid$default)
##         
## pred_def   No  Yes
##      No  4824  108
##      Yes   19   49

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

we use the mean() function to calculate the MSE of the validation set. Note that the valid index below selects only the observations that are not in the training set.

mean(pred_def !=valid$default)
## [1] 0.0254

(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 trial
train <- sample(dim(Default)[1], dim(Default)[1]*0.80)  # Training set 
valid <- Default[-train, ]   #Validation set
mod = glm(default ~ balance + income, data = Default, family = binomial, subset = train)
pred = predict(mod, valid, type = "response")
pred_def <-ifelse(pred>0.5,"Yes","No")
MSE1 = mean(pred_def !=valid$default)
#second trial
train <- sample(dim(Default)[1], dim(Default)[1]*0.70)  # Training set 
valid <- Default[-train, ]   #Validation set
mod = glm(default ~ balance + income, data = Default, family = binomial, subset = train)
pred = predict(mod, valid, type = "response")
pred_def <-ifelse(pred>0.5,"Yes","No")
MSE2 = mean(pred_def !=valid$default)
#third trial
train <- sample(dim(Default)[1], dim(Default)[1]*0.60)  # Training set 
valid <- Default[-train, ]   #Validation set
mod = glm(default ~ balance + income, data = Default, family = binomial, subset = train)
pred = predict(mod, valid, type = "response")
pred_def <-ifelse(pred>0.5,"Yes","No")
MSE3 = mean(pred_def !=valid$default)

cat(MSE1,MSE2,MSE3) #print 3 different MSEs
## 0.0265 0.01833333 0.024
  • The data set is splitted into three different ratios and the model is fitted on training set and the misclassification rate is calculated on test set.

Missclassification rate (Train:Test–80:20): 0.0245

Missclassification rate (Train:Test–70:30): 0.0277

Missclassification rate (Train:Test–60:40): 0.0270

It is observed that error rate is different for different samples.

(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)
train <- sample(dim(Default)[1], dim(Default)[1]*0.70)  # Training set 
valid <- Default[-train, ]   #Validation set
fit <- glm(default ~ income + balance + student, data = Default, family = "binomial", subset = train)
pred = predict(fit, valid, type = "response")
pred_def <-ifelse(pred>0.7,"Yes","No")
table(valid$default,pred_def,dnn=c("Actual","Predicted"))
##       Predicted
## Actual   No  Yes
##    No  2898    0
##    Yes   94    8
mean(pred_def !=valid$default)
## [1] 0.03133333

It doesn’t seem that adding the “student” dummy variable leads to a reduction in the validation set estimate of the test error rate.

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

summary(logmodel1)
## 
## Call:
## glm(formula = default ~ balance + income, 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 ***
## balance      5.647e-03  2.274e-04  24.836  < 2e-16 ***
## income       2.081e-05  4.985e-06   4.174 2.99e-05 ***
## ---
## 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 glm() estimates of the standard errors for the coefficients \(\beta_0\), \(\beta_1\) and \(\beta_2\) are respectively 0.4348, 2.2737 × 10-4 and 4.9852 × 10-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) {
    fit <- glm(default ~ income + balance, data = data, family = "binomial", subset = index)
    return (coef(fit))
}

This function returns, or outputs, an estimate for \(\alpha\) to the observations indexed by the argument index.

(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, 1000)
## 
## ORDINARY NONPARAMETRIC BOOTSTRAP
## 
## 
## Call:
## boot(data = Default, statistic = boot.fn, R = 1000)
## 
## 
## Bootstrap Statistics :
##          original        bias     std. error
## t1* -1.154047e+01 -3.900813e-02 4.347702e-01
## t2*  2.080898e-05  1.595620e-07 4.862429e-06
## t3*  5.647103e-03  1.847244e-05 2.300787e-04

The bootstrap estimates of the standard errors for the coefficients \(\beta_0\), \(\beta_1\) and \(\beta_2\) are respectively 0.4348, 2.3 × 10-4 and 4.8624 × 10-6 .

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

Exercise 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 \(\hat{µ}\) .

library(MASS)
attach(Boston)
mean(medv)
## [1] 22.53281

So, the estimated \(\hat{µ}\) = 22.53 .

(b). Provide an estimate of the standard error of \(\hat{µ}\) . Interpret this result.

sd(medv)/sqrt(length(medv))
## [1] 0.4088611

The estimated standard error of mean of medv, \(\hat{µ}\) is 0.4089.

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

boot.fn=function(data, index) return(mean(data[index]))
bstrap=boot(medv, boot.fn, 1000)
bstrap
## 
## ORDINARY NONPARAMETRIC BOOTSTRAP
## 
## 
## Call:
## boot(data = medv, statistic = boot.fn, R = 1000)
## 
## 
## Bootstrap Statistics :
##     original     bias    std. error
## t1* 22.53281 0.01111957   0.4113188

The bootstrap estimated standard error of \(\hat{\mu}\) of 0.4113 is very close to the estimate found in (b) of 0.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).

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

t.test confidence interval is simmilar to the bootstap confidence interval.

(e). Based on this data set, provide an estimate, \(\hat{µ_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.

boot.fn= function(data, index) return(median(data[index]))
boot(medv, boot.fn, 1000)
## 
## ORDINARY NONPARAMETRIC BOOTSTRAP
## 
## 
## Call:
## boot(data = medv, statistic = boot.fn, R = 1000)
## 
## 
## Bootstrap Statistics :
##     original  bias    std. error
## t1*     21.2 -0.0201   0.3712867

The estimated median value of 21.2 from bootstrap which is sames as the value in (e), and a standard error of 0.37 which is relatively small.

(g). ) Based on this data set, provide an estimate for the tenth percentile of medv in Boston census tracts. Call this quantity \(\hat{µ_0.1}\) (You can use the quantile() function.)

quantile(medv, c(0.1))
##   10% 
## 12.75

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

boot.fn= function(data, index) return(quantile(data[index], c(0.1)))
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.02635   0.5058795

The estimated tenth percentile value of 12.75 from bootstap is same as the value in (g), and the standard error of 0.505 which is relatively small compared to percentile value.