library("ISLR2")
## Warning: package 'ISLR2' was built under R version 4.5.3
library("boot")
data("Default")
data("Boston")

3. We now review k-fold cross-validation. (a) Explain how k-fold cross-validation is implemented. K fold cross-validation is implemented by randomly dividing a set of observations into k groups/folds of close to equivalent sizes.

The first fold is treated as a validation set and fit on the remaining folds.

The MSE is then compute on the the held out fold observations.

The process completes K times. The test error estimates are then averaged together which yields the k-fold CV error value.

(b) What are the advantages and disadvantages of k-fold cross validation relative to: i. The validation set approach? The validation set approach is simple and easy to implement. However, the validation MSE can be highly variable and only a subset of observations are used to fit the model.

K-fold cross-validation is more stable and less variable, but is more intensive and can take longer due to the sampling needing to occur K times.

ii. LOOCV? For LOOCV, it produces a less variable MSE and has low bias. However, it is computationally expensive.

K-fold cross-validation has a higher bias, but is less computationally 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.

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

set.seed(137)

glm.fitDef = glm(default~income+balance, data = Default, family = "binomial" )

summary(glm.fitDef)
## 
## Call:
## glm(formula = default ~ income + balance, family = "binomial", 
##     data = Default)
## 
## 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: i. Split the sample set into a training set and a validation set.

set.seed(137)

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

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

glm.fitTrain = glm(default~income+balance, data = Default, subset = 
                   train.Def,family = "binomial")

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.

glm.probsDefault = predict(glm.fitTrain, 
                           newdata = Default[-train.Def, ], 
                           type = "response")

glm.predDefault = rep("No", length(glm.probsDefault))
glm.predDefault[glm.probsDefault > 0.5] = "Yes"

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

mean(glm.predDefault != Default$default[-train.Def])
## [1] 0.0296

The validation set error is 2.96%

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

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

glm.fitTrain = glm(default~income+balance, data = Default, subset = 
                   train.Def,family = "binomial")

glm.probsDefault = predict(glm.fitTrain, 
                           newdata = Default[-train.Def, ], 
                           type = "response")

glm.predDefault = rep("No", length(glm.probsDefault))
glm.predDefault[glm.probsDefault > 0.5] = "Yes"

mean(glm.predDefault != Default$default[-train.Def])
## [1] 0.027
train.Def = sample(dim(Default)[1], dim(Default)[1]/2)

glm.fitTrain = glm(default~income+balance, data = Default, subset = 
                   train.Def,family = "binomial")

glm.probsDefault = predict(glm.fitTrain, 
                           newdata = Default[-train.Def, ], 
                           type = "response")

glm.predDefault = rep("No", length(glm.probsDefault))
glm.predDefault[glm.probsDefault > 0.5] = "Yes"

mean(glm.predDefault != Default$default[-train.Def])
## [1] 0.0254
train.Def = sample(dim(Default)[1], dim(Default)[1]/2)

glm.fitTrain = glm(default~income+balance, data = Default, subset = 
                   train.Def,family = "binomial")

glm.probsDefault = predict(glm.fitTrain, 
                           newdata = Default[-train.Def, ], 
                           type = "response")

glm.predDefault = rep("No", length(glm.probsDefault))
glm.predDefault[glm.probsDefault > 0.5] = "Yes"

mean(glm.predDefault != Default$default[-train.Def])
## [1] 0.0276

The validation set errors appear to range from 2.50% to 3%.

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

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

glm.fitTrain = glm(default~income+balance+student, data = Default, subset = 
                   train.Def,family = "binomial")

glm.probsDefault = predict(glm.fitTrain, 
                           newdata = Default[-train.Def, ], 
                           type = "response")

glm.predDefault = rep("No", length(glm.probsDefault))
glm.predDefault[glm.probsDefault > 0.5] = "Yes"

mean(glm.predDefault != Default$default[-train.Def])
## [1] 0.0252

The validation set error does not appear to have dropped below the expected range of between 2.5% and 3%.

Adding a dummy variable for student does not appear to lead to a reduction in the test error rate.

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.

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

glm.fitTrain16 = glm(default~income+balance, data = Default, 
                     family = "binomial")

summary(glm.fitTrain16)
## 
## Call:
## glm(formula = default ~ income + balance, family = "binomial", 
##     data = Default)
## 
## 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) 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=data, 
                  subset=index, family = binomial)))
}

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

(d) Comment on the estimated standard errors obtained using the glm() function and using your bootstrap function The estimated standard errors coefficients for both the bootstrap function and glm()) function yielded similar low results.

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

mu_hat = mean(Boston$medv)
mu_hat
## [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.

sd_medv = sd(Boston$medv)

st_error_mu = sd_medv/(sqrt(length(Boston$medv)))
st_error_mu
## [1] 0.4088611

The estimated SD (Standard Deviation) of mu hat is approximately 0.41. This means that the SD in dollars is about $410.

This means that the population mean medv value when calculated is usually about $410 off.

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

boot.fn=function(data,index){
  return(mean(data[index]))
}

set.seed(3)

boot.fn(Boston$medv,sample(506,506, replace = TRUE))
## [1] 22.80099
boot(Boston$medv,boot.fn,300)
## 
## ORDINARY NONPARAMETRIC BOOTSTRAP
## 
## 
## Call:
## boot(data = Boston$medv, statistic = boot.fn, R = 300)
## 
## 
## Bootstrap Statistics :
##     original     bias    std. error
## t1* 22.53281 0.02176285   0.3910333

The coefficient I pulled from the boot function was not too far from the SD calculated through the manual SD I calculated.

(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(ˆµ)].

ConfInfa95 = 22.5328 + c(-2,2) * 0.3910
ConfInfa95
## [1] 21.7508 23.3148
t.test(Boston$medv)$conf.int
## [1] 21.72953 23.33608
## attr(,"conf.level")
## [1] 0.95

The results are pretty similar, only differing by the value in the hundredths place in the decimal values. This means the bootstrap gave a good estimate for the confidence interval, in comparison to a traditional t test.

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

mu_med = median(Boston$medv)
mu_med
## [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.fn2=function(data,index){
  return(median(data[index]))
}

set.seed(3)

boot.fn2(Boston$medv,sample(506,506, replace = TRUE))
## [1] 21.2
boot(Boston$medv,boot.fn2,300)
## 
## ORDINARY NONPARAMETRIC BOOTSTRAP
## 
## 
## Call:
## boot(data = Boston$medv, statistic = boot.fn2, R = 300)
## 
## 
## Bootstrap Statistics :
##     original  bias    std. error
## t1*     21.2  -0.003   0.3657919

The standard error of the median using the bootstrap is 0.3658.

This means tgar the estimated median value is usually off by $366.

This low SD signifies that the median is not an unreasonable value.

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

mu_hat_10per <- quantile(Boston$medv, probs = 0.1)

mu_hat_10per
##   10% 
## 12.75

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

boot.fn3=function(data,index){
  return(quantile(data[index], probs = 0.1))
}

set.seed(3)

boot.fn3(Boston$medv,sample(506,506, replace = TRUE))
##  10% 
## 13.8
boot(Boston$medv,boot.fn3,300)
## 
## ORDINARY NONPARAMETRIC BOOTSTRAP
## 
## 
## Call:
## boot(data = Boston$medv, statistic = boot.fn3, R = 300)
## 
## 
## Bootstrap Statistics :
##     original     bias    std. error
## t1*    12.75 0.05383333   0.4961325

The determined bootstrap SD approximates gar the 10th percentile of medv varies by about $495 to $500.

Since this is the 10th percentile, more then likely representing a tail, it’s not too surprising that the SD appears to be a bit larger then some of the other SDs run across in this problem.