5. Resampling Methods - Exercises

 

Conceptual

 

1. Using basic statistical properties of the variance, as well as single-variable calculus, derive \(\alpha^2 \sigma_X^2 + \sigma_Y^2+\alpha^2\sigma_Y^2-2\alpha\sigma_Y^2 + 2\alpha \sigma_{XY} - 2\alpha^2 \sigma_{XY}\)(5.6). In other words, prove that \(\alpha\) given by (5.6) does indeed minimize \(Var(\alpha X + (1 - \alpha)Y)\)

\[ Var(\alpha X + (1-\alpha)Y) \\ = Var(\alpha X) + Var((1-\alpha)Y) +2 Cov(\alpha X, (1-\alpha)Y) \\ = \alpha^2 \sigma_X^2 + (1-\alpha)^2 \sigma_Y^2 + 2 \alpha (1-\alpha) \sigma_{XY} \\ = \alpha^2 \sigma_X^2 + (1+\alpha^2-2\alpha) \sigma_Y^2 + (2\alpha - 2\alpha^2) \sigma_{XY} \\ = \alpha^2 \sigma_X^2 + \sigma_Y^2+\alpha^2\sigma_Y^2-2\alpha\sigma_Y^2 + 2\alpha \sigma_{XY} - 2\alpha^2 \sigma_{XY} \]

\[ \frac{\partial }{\partial \alpha}: 2\alpha\sigma_X^2 + 0 + 2\alpha\sigma_Y^2 - 2\sigma_Y^2 + 2\sigma_{XY} - 4\alpha\sigma_{XY} = 0 \]

\[ (2\sigma_X^2 + 2\sigma_Y^2 - 4\sigma_{XY}) \alpha = 2\sigma_Y^2 - 2\sigma_{XY} \]

\[ \alpha = \frac{\sigma_Y^2 - \sigma_{XY}}{\sigma_X^2 + \sigma_Y^2 - 2\sigma_{XY}} \]

 

2. We will now derive the probability that a given observation is part of a bootstrap sample. Suppose that we obtain a bootstrap sample from a set of n observations.

  1. What is the probability that the first bootstrap observation is not the jth observation from the original sample? Justify your answer.
  • The probability that it is not the jth example is \(1- \frac{1}{n}\)
  1. What is the probability that the second bootstrap observation is not the jth observation from the original sample?
  • Since we use replacement the probability is the same as above: \((1- \frac{1}{n})\)
  1. Argue that the probability that the jth observation is not in the bootstrap sample is \((1−1/n)\)
  • Since we use replacement we can just multiply the probabilities n times which equals \((1−1/n)^n\)
  1. When n= 5, what is the probability that the jth observation is in the bootstrap sample?
  • \(1-((1−1/5)^5) = 0.672\)
  1. When n= 100, what is the probability that the jth observation is in the bootstrap sample?
  • \(1-((1−1/100)^{100}) = 0.634\)
  1. When n=10,000, what is the probability that the jth observation is in the bootstrap sample?
  • \(1-((1−1/10000)^{10000}) = 0.632\)
  1. Create a plot that displays, for each integer value of n from 1 to 100,000, the probability that the jth observation is in the bootstrap sample. Comment on what you observe.
x = 1:100000
plot(x, 1 - (1 - 1/x)^x)

 

  1. We will now investigate numerically the probability that a bootstrap sample of size n= 100 contains the jth observation. Here j=4. We repeatedly create bootstrap samples, and each time we record whether or not the fourth observation is contained in the bootstrap sample.
set.seed(42)
store=rep(NA, 10000)
for(i in 1:10000){
  store[i]=sum(sample(1:100, rep=TRUE)==4)>0
}
mean(store)
## [1] 0.6313
  • as we suspected from the plot above the probability converges to a value of around 0.63

 

3. We now review k-fold cross-validation.

  1. Explain how k-fold cross-validation is implemented.
  • the data is split into k folds of approximately equal size
  • the first fold is trated as validation set and the model is fit on the remaining k-1 folds
  • the MSE is computed on the observations in the held out fold
  • the whole process is repeated k times, each time with another fold left out
  • then the k MSE results are averaged to estimate the test error
  1. What are the advantages and disadvantages of k-fold cross-validation relative to:
  1. The validation set approach?
  • the validation set approach can overestimate the test error since model just uses half of the available oberservations
  • the validation set approach is highly variable in estamting the test error depending on which oberservations are in which set
  1. LOOCV?
  • LOOCV is computaionally more expensive because the model is fit k=n times
  • LOOCV has low bias but high variance k-fold with k=5 or k=10 has been shown empirically to yield the best results

 

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.

We can estimate the standard deviation of our prediction by using the bootstrap method. Since we often don’t have access to new data sets from the population we instead use repeated samples with replacement from the one data set available. With different results for the Y value we can estimate the standard deviation of our prediction.

 

Applied

 

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.
  1. Fit a logistic regression model that uses income and balance to predict default.
library(ISLR)
attach(Default)
set.seed(42)
glm.fit = glm(default~ balance+income, data=Default, family="binomial")
summary(glm.fit)
## 
## 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
  1. 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.
train = sample(nrow(Default), nrow(Default)*0.5)
  1. Fit a multiple logistic regression model using only the training observations.
glm.fit_val = glm(default~balance+income, data=Default, family=binomial, subset = train)
  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.
glm.probs = predict(glm.fit_val, Default[-train,], type="response")
glm.pred = ifelse(glm.probs > 0.5, "Yes", "No")
  1. Compute the validation set error, which is the fraction of the observations in the validation set that are misclassified.
table(glm.pred, Default[-train, ]$default)
##         
## glm.pred   No  Yes
##      No  4817  110
##      Yes   20   53
mean(glm.pred !=Default[-train,]$default)
## [1] 0.026
  1. 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(nrow(Default), nrow(Default)*0.5)
glm.fit_val = glm(default~balance+income, data=Default, family=binomial, subset = train)
glm.probs = predict(glm.fit_val, Default[-train,], type="response")
glm.pred = ifelse(glm.probs > 0.5, "Yes", "No")
table(glm.pred, Default[-train, ]$default)
##         
## glm.pred   No  Yes
##      No  4816  116
##      Yes   14   54
mean(glm.pred !=Default[-train,]$default)
## [1] 0.026
train = sample(nrow(Default), nrow(Default)*0.5)
glm.fit_val = glm(default~balance+income, data=Default, family=binomial, subset = train)
glm.probs = predict(glm.fit_val, Default[-train,], type="response")
glm.pred = ifelse(glm.probs > 0.5, "Yes", "No")
table(glm.pred, Default[-train, ]$default)
##         
## glm.pred   No  Yes
##      No  4802  135
##      Yes   12   51
mean(glm.pred !=Default[-train,]$default)
## [1] 0.0294
train = sample(nrow(Default), nrow(Default)*0.5)
glm.fit_val = glm(default~balance+income, data=Default, family=binomial, subset = train)
glm.probs = predict(glm.fit_val, Default[-train,], type="response")
glm.pred = ifelse(glm.probs > 0.5, "Yes", "No")
table(glm.pred, Default[-train, ]$default)
##         
## glm.pred   No  Yes
##      No  4817  109
##      Yes   20   54
mean(glm.pred !=Default[-train,]$default)
## [1] 0.0258

Since every train set has its own unique set of observations the error rate varies across every run.

  1. 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.
train = sample(nrow(Default), nrow(Default)*0.5)
glm.fit_val = glm(default~balance+income+student, data=Default, family=binomial, subset = train)
glm.probs = predict(glm.fit_val, Default[-train,], type="response")
glm.pred = ifelse(glm.probs > 0.5, "Yes", "No")
table(glm.pred, Default[-train, ]$default)
##         
## glm.pred   No  Yes
##      No  4810  128
##      Yes   11   51
mean(glm.pred !=Default[-train,]$default)
## [1] 0.0278

Adding a student dummy variable doesn’t seem to decrease the validation set estimate for the test error.

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.

  1. 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(42)
require(ISLR)
attach(Default)
## The following objects are masked from Default (pos = 3):
## 
##     balance, default, income, student
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
  1. 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~income+balance, data=Default, family="binomial", subset=index)))  
}
boot.fn(Default, 1:nrow(Default))
##   (Intercept)        income       balance 
## -1.154047e+01  2.080898e-05  5.647103e-03
  1. 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 -2.292405e-02 4.435269e-01
## t2*  2.080898e-05  2.737444e-08 5.073444e-06
## t3*  5.647103e-03  1.176249e-05 2.299133e-04
  1. Comment on the estimated standard errors obtained using the glm() function and using your bootstrap function.
  • both outputs are close to each other

 

7. In Sections 5.3.2 and 5.3.3, we saw that the cv.glm() function can be used in order to compute the LOOCV test error estimate. Alternatively, one could compute those quantities using just the predict.glm() functions, and a for loop. You will now take this approach in order to compute the LOOCV error for a simple logistic regression model on the Weekly data set. Recall that in the context of classification problems, the LOOCV error is given in (5.4).

  1. Fit a logistic regression model that predicts Direction using Lag1 and Lag2.
set.seed(1)
attach(Weekly)
glm.fit1 = glm(Direction ~ Lag1 + Lag2, data=Weekly, family="binomial")
summary(glm.fit1)
## 
## Call:
## glm(formula = Direction ~ Lag1 + Lag2, family = "binomial", data = Weekly)
## 
## Deviance Residuals: 
##    Min      1Q  Median      3Q     Max  
## -1.623  -1.261   1.001   1.083   1.506  
## 
## Coefficients:
##             Estimate Std. Error z value Pr(>|z|)    
## (Intercept)  0.22122    0.06147   3.599 0.000319 ***
## Lag1        -0.03872    0.02622  -1.477 0.139672    
## Lag2         0.06025    0.02655   2.270 0.023232 *  
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## (Dispersion parameter for binomial family taken to be 1)
## 
##     Null deviance: 1496.2  on 1088  degrees of freedom
## Residual deviance: 1488.2  on 1086  degrees of freedom
## AIC: 1494.2
## 
## Number of Fisher Scoring iterations: 4
  1. Fit a logistic regression model that predicts Direction using Lag1 and Lag2 using all but the first observation.
glm.fit2 = glm(Direction ~ Lag1 + Lag2, data=Weekly[-1, ], family="binomial")
summary(glm.fit2)
## 
## Call:
## glm(formula = Direction ~ Lag1 + Lag2, family = "binomial", data = Weekly[-1, 
##     ])
## 
## Deviance Residuals: 
##     Min       1Q   Median       3Q      Max  
## -1.6258  -1.2617   0.9999   1.0819   1.5071  
## 
## Coefficients:
##             Estimate Std. Error z value Pr(>|z|)    
## (Intercept)  0.22324    0.06150   3.630 0.000283 ***
## Lag1        -0.03843    0.02622  -1.466 0.142683    
## Lag2         0.06085    0.02656   2.291 0.021971 *  
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## (Dispersion parameter for binomial family taken to be 1)
## 
##     Null deviance: 1494.6  on 1087  degrees of freedom
## Residual deviance: 1486.5  on 1085  degrees of freedom
## AIC: 1492.5
## 
## Number of Fisher Scoring iterations: 4
  1. Use the model from (b) to predict the direction of the first observation. You can do this by predicting that the first observation will go up if P(Direction=“Up”|Lag1,Lag2)>0.5. Was this observation correctly classified?
predict(glm.fit2, Weekly[1, ], type="response")>0.5
##    1 
## TRUE
Weekly[1,]$Direction
## [1] Down
## Levels: Down Up

This oberservation was not correctly classified.

  1. Write a for loop from i=1 to i=n, where n is the number of observations in the data set, that performs each of the following steps:
  1. Fit a logistic regression model using all but the ith observation to predict Direction using Lag1 and Lag2.
error <- rep(0, nrow(Weekly))
for (i in 1:nrow(Weekly)){
 fit =  glm(Direction ~ Lag1+Lag2, data=Weekly[-i, ], family=binomial)
 pred = predict(fit, Weekly[i, ], type="response") > 0.5
 true <- Weekly[i, ]$Direction == "Up"
 if (pred != true)
   error[i] = 1
}
  1. Take the average of the n numbers obtained in (d)iv in order to obtain the LOOCV estimate for the test error. Comment on the results.
mean(error)
## [1] 0.4499541

 

8. We will now perform cross-validation on a simulated data set.

  1. Generate a simulated data set as follows:
set.seed(1)
x=rnorm(100)
y=x-2*x^2+rnorm(100)

In this data set, what is n and what is p? Write out the model used to generate the data in equation form.

n = 100 p = 2 *\(y =X -2X^2 + \epsilon\)

  1. Create a scatterplot of \(X\) against \(Y\). Comment on what you find.
plot(x, y)

  • quadratic parabola-like relationship
  1. Set a random seed, and then compute the LOOCV errors that result from fitting the following four models using least squares:
  1. \(Y = \beta_0 + \beta_1X + \epsilon\)
library(boot)
set.seed(1)
df <- data.frame(x, y)
glm.fit1 <- glm(y ~ x)
cv.glm(df, glm.fit1)$delta[1]
## [1] 7.288162
  1. \(Y = \beta_0 + \beta_1X + \beta_2X^2 + \epsilon\)
glm.fit2 <- glm(y ~ poly(x, 2))
cv.glm(df, glm.fit2)$delta[1]
## [1] 0.9374236
  1. \(Y = \beta_0 + \beta_1X + \beta_2X^2 + \beta_3X^3 +\epsilon\)
glm.fit3 <- glm(y ~ poly(x, 3))
cv.glm(df, glm.fit3)$delta[1]
## [1] 0.9566218
  1. \(Y = \beta_0 + \beta_1X + \beta_2X^2 + \beta_3X^3 + \beta_4X^4 +\epsilon\)
glm.fit4 <- glm(y ~ poly(x, 4))
cv.glm(df, glm.fit4)$delta[1]
## [1] 0.9539049
  1. Repeat (c) using another random seed, and report your results. Are your results the same as what you got in (c)? Why?
set.seed(42)
df <- data.frame(x, y)
glm.fit1 <- glm(y ~ x)
cv.glm(df, glm.fit1)$delta[1]
## [1] 7.288162
glm.fit2 <- glm(y ~ poly(x, 2))
cv.glm(df, glm.fit2)$delta[1]
## [1] 0.9374236
glm.fit3 <- glm(y ~ poly(x, 3))
cv.glm(df, glm.fit3)$delta[1]
## [1] 0.9566218
glm.fit4 <- glm(y ~ poly(x, 4))
cv.glm(df, glm.fit4)$delta[1]
## [1] 0.9539049

The results are the same because LOOCV evaluates the model n times over n-1 training observations.

  1. Which of the models in (c) had the smallest LOOCV error? Is this what you expected? Explain your answer.

The quadratic model performs best. This is exactly what I expected because we used a quadratic function to generate the data.

  1. Comment on the statistical significance of the coefficient estimates that results from fitting each of the models in (c) using least squares. Do these results agree with the conclusions drawn based on the cross-validation results?
summary(glm.fit4)
## 
## Call:
## glm(formula = y ~ poly(x, 4))
## 
## Deviance Residuals: 
##     Min       1Q   Median       3Q      Max  
## -2.0550  -0.6212  -0.1567   0.5952   2.2267  
## 
## Coefficients:
##              Estimate Std. Error t value Pr(>|t|)    
## (Intercept)  -1.55002    0.09591 -16.162  < 2e-16 ***
## poly(x, 4)1   6.18883    0.95905   6.453 4.59e-09 ***
## poly(x, 4)2 -23.94830    0.95905 -24.971  < 2e-16 ***
## poly(x, 4)3   0.26411    0.95905   0.275    0.784    
## poly(x, 4)4   1.25710    0.95905   1.311    0.193    
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## (Dispersion parameter for gaussian family taken to be 0.9197797)
## 
##     Null deviance: 700.852  on 99  degrees of freedom
## Residual deviance:  87.379  on 95  degrees of freedom
## AIC: 282.3
## 
## Number of Fisher Scoring iterations: 2

Only \(X\) and \(X^2\) are statistically significant. This is what we expected since the quadratic model performed best.

 

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

  1. Based on this data set, provide an estimate for the population mean of medv. Call this estimate \(\hat\mu\).
mu = mean(Boston$medv)
mu
## [1] 22.53281
  1. Provide an estimate of the standard error of \(\hat\mu\). Interpret this result.
se_mu = sd(Boston$medv)/sqrt(nrow(Boston))
se_mu
## [1] 0.4088611
  1. Now estimate the standard error of \(\hat\mu\) using the bootstrap. How does this compare to your answer from (b)?
set.seed(1)
boot.fn <- function(data, index) {
    mu <- mean(data[index])
    return (mu)
}
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* 22.53281 0.007650791   0.4106622

Both estimates are almost equal.

  1. 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(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
conf = c(22.53 - 2 * 0.4119, 22.53 + 2 * 0.4119)
conf
## [1] 21.7062 23.3538
  1. Based on this data set, provide an estimate, \(\hat\mu_{med}\), for the median value of medv in the population.
mu_med = median(Boston$medv)
mu_med
## [1] 21.2
  1. We now would like to estimate the standard error of \(\hat\mu_{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) {
    mu <- median(data[index])
    return (mu)
}
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.02295   0.3778075

Same value of 21.2 with a rather small standard error of 0.38.

  1. Based on this data set, provide an estimate for the tenth percentile of medv in Boston suburbs. Call this quantity \(\hat\mu_{0.1}\). (You can use the quantile() function.)
mu_01 = quantile(Boston$medv, c(0.1))
mu_01
##   10% 
## 12.75
  1. Use the bootstrap to estimate the standard error of \(\hat\mu_{0.1}\). Comment on your findings.
boot.fn <- function(data, index) {
    mu <- quantile(data[index], c(0.1))
    return (mu)
}
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.01455   0.4823468