library(ISLR2)

#3 We now review k-fold cross-validation. (a) Explain how k-fold cross-validation is implemented.

By dividing the data set into k different and equal subsets, we can choose one set k1 of length 1/k ,set it apart, and fit the method in the remaining k-1 sets. The MSE is the used in the held out set (k1). By repeating this process, alternating the held out set so every Kn set will be held out once, we obtain k different MSE which are then averaged.

  1. What are the advantages and disadvantages of k-fold crossvalidation relative to:
  1. The validation set approach?

Advantage of the validation set approach with respect to the k-fold is its simplicity and ease to understand and use. At the same time, due to being a simpler method and because it is calculated using one subset of training observations, it will tend to overestimate the validation MSE and is more variable than the k-fold crossvalidation.

  1. LOOCV?

LOOCV is a case of k-fold, where k=n. As such, the K-fold validation is a great approach to the MSE calculated by the LOOCV, which fits the method n times, where n is the number of observations, instead of k subsets. An advantage of the k-fold is that since it fits the model in fewer training sets, its less computer intensive.

#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.
log_fit <- glm(default ~ income + balance, family = "binomial", data = Default)
summary(log_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. 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.
# A ratio of 0.6 is used to define the training set.
set.seed (99)
training <-  sample(dim(Default)[1], 0.6* dim(Default)[1])
  1. Fit a multiple logistic regression model using only the training observations.
train_fit <-  glm(default ~ income + balance, family = "binomial", data = Default, subset = training)
  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.
probs <- predict(train_fit, Default[-training, ], type = "response")
preds <- rep("No", dim(Default)[1])
preds[probs > 0.5] = "Yes"
  1. Compute the validation set error, which is the fraction of the observations in the validation set that are misclassified.
mean(preds != Default[-training, "default"])
## Warning in `!=.default`(preds, Default[-training, "default"]): longer object
## length is not a multiple of shorter object length
## Warning in is.na(e1) | is.na(e2): longer object length is not a multiple of
## shorter object length
## [1] 0.028

Validation set error: 2.8%

  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.
set.seed (1)
training <-  sample(dim(Default)[1], 0.6* dim(Default)[1])
train_fit <-  glm(default ~ income + balance, family = "binomial", data = Default, subset = training)
probs <- predict(train_fit, Default[-training, ], type = "response")
preds <- rep("No", dim(Default)[1])
preds[probs > 0.5] = "Yes"
mean(preds != Default[-training, "default"])
## Warning in `!=.default`(preds, Default[-training, "default"]): longer object
## length is not a multiple of shorter object length
## Warning in is.na(e1) | is.na(e2): longer object length is not a multiple of
## shorter object length
## [1] 0.0248

Validation set error: 2.48%

set.seed (33)
training <-  sample(dim(Default)[1], 0.6* dim(Default)[1])
train_fit <-  glm(default ~ income + balance, family = "binomial", data = Default, subset = training)
probs <- predict(train_fit, Default[-training, ], type = "response")
preds <- rep("No", dim(Default)[1])
preds[probs > 0.5] = "Yes"
mean(preds != Default[-training, "default"])
## Warning in `!=.default`(preds, Default[-training, "default"]): longer object
## length is not a multiple of shorter object length
## Warning in is.na(e1) | is.na(e2): longer object length is not a multiple of
## shorter object length
## [1] 0.0261

Validation set error: 2.61%

set.seed (55)
training <-  sample(dim(Default)[1], 0.6* dim(Default)[1])
train_fit <-  glm(default ~ income + balance, family = "binomial", data = Default, subset = training)
probs <- predict(train_fit, Default[-training, ], type = "response")
preds <- rep("No", dim(Default)[1])
preds[probs > 0.5] = "Yes"
mean(preds != Default[-training, "default"])
## Warning in `!=.default`(preds, Default[-training, "default"]): longer object
## length is not a multiple of shorter object length
## Warning in is.na(e1) | is.na(e2): longer object length is not a multiple of
## shorter object length
## [1] 0.0234

Validation set error: 2.34%

  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.
set.seed(99)
training <- sample(dim(Default)[1], dim(Default)[1] / 2)
glm_fit <- glm(default ~ income + balance + student, data = Default, family = "binomial", subset = training)
glm_pred <- rep("No", length(probs))
glm_prob <- predict(glm_fit, newdata = Default[-training, ], type = "response")
glm_pred[glm_prob > 0.5] <- "Yes"
mean(glm_pred != Default[-training, ]$default)
## [1] NA

Validation set error: 2.82%. Including a dummy variable did not help to reduce 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.

library(boot)
  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(99)
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){
    coefs <- coef(glm(default ~ income + balance, data = Data, subset = index,
                      family = "binomial"))[c("income", "balance")]
    return(coefs)
}
  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.
boot(Default, boot.fn, 1000)
## 
## ORDINARY NONPARAMETRIC BOOTSTRAP
## 
## 
## Call:
## boot(data = Default, statistic = boot.fn, R = 1000)
## 
## 
## Bootstrap Statistics :
##         original        bias     std. error
## t1* 2.080898e-05 -5.220494e-08 4.796239e-06
## t2* 5.647103e-03  1.191112e-05 2.334481e-04
#boot using 1000 bootstrap samples.
  1. Comment on the estimated standard errors obtained

         glm Std. Error.   Bootstrap

    income 4.985e-06 4.752332e-06 balance 2.274e-04 2.300795e-04

The standard errors for both glm and bootstrap are very similar. The Bootstrap results corroborates the assumptions of the gl model for the data set.

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

  1. Based on this data set, provide an estimate for the population mean of medv. Call this estimate ˆμ.
ˆμ <- mean(Boston$medv)
ˆμ
## [1] 22.53281
  1. 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.
s_err <- sd(Boston$medv)/sqrt(length(Boston$medv))
s_err
## [1] 0.4088611
  1. Now estimate the standard error of ˆμ using the bootstrap. How does this compare to your answer from (b)?
set.seed(99)
boot.fn <- function(data, index) {
    μ <- mean(data[index])
    return (μ)
}
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.01791186   0.4305781

Std. error (b) = 0.4088611 Std. error (c) = 0.4305781

Standard errors from both parts differ by 0.021717.

  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). Hint: You can approximate a 95% confidence interval using the formula [ˆμ − 2SE(ˆμ), ˆμ + 2SE(ˆμ)].
se_boot <- c(ˆμ - 2 * 0.4305781, ˆμ + 2 * 0.4305781)
se_boot
## [1] 21.67165 23.39396
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

(21.67165,23.39396) and (21.72953,23.33608)

  1. Based on this data set, provide an estimate, ˆμmed, for the median value of medv in the population.
med_ˆμ <- median(Boston$medv)
med_ˆμ
## [1] 21.2
  1. 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.
set.seed(99)
boot.fn <- function(data, index) {
    med_μ <- median(data[index])
    return (med_μ)
}
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.01915   0.3837748

The standard error for the median value of 21.2, is 0.3837748, which is relatively small compared to the median value.

  1. Based on this data set, provide an estimate for the tenth percentile of medv in Boston census tracts. Call this quantity ˆμ0.1. (You can use the quantile() function.)
ˆμ0.1 <- quantile(Boston$medv, 0.1)
ˆμ0.1
##   10% 
## 12.75
  1. Use the bootstrap to estimate the standard error of ˆμ0.1. Comment on your findings.
set.seed(99)

boot.fn <- function(data, index) {
    μ0.1 <- quantile(data[index], c(0.1))
    return (μ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.0168   0.4973632

The standard error for the 10 percentile value of 12.75 is 0.4973632.