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

(a) Explain how k-fold cross-validation is implemented. With k-fold cross-validation, your data is randomly divided into k folds. Then repeats the following process k times: one of the folds is selected as test data, the other K-1 are selected as training data. Once every fold has had a chance to be test data, the combined results are presented.
(b) What are the advantages and disadvantages of k-fold crossvalidation relative to the validation approach and LOOCV?
For the validation set approach, it doesn’t take as much time and is less computationally intense, but will create a less accurate result. For the LOOCV, it takes much longer and is much more computationally intense, but will create a more accurate result.
### 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.

library(ISLR)
glm.fit <- glm(default ~ income + balance, data = Default, family = "binomial")

(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(1)
rand_obs <- sample.int(nrow(Default), nrow(Default)*.7)
train_set <- Default[rand_obs,]
test_set <- Default[-rand_obs,]

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

glm.fit.train <- glm(default ~ income + balance, data = train_set, 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.probs <- predict(glm.fit.train, newdata = test_set, type="response")
glm.pred <- rep("No", length(glm.probs))
glm.pred[glm.probs>.5]="Yes"

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

(table(glm.pred, test_set$default)[1]+table(glm.pred, test_set$default)[3])/
  (table(glm.pred, test_set$default)[1]+table(glm.pred, test_set$default)[2]+
     table(glm.pred, test_set$default)[3]+table(glm.pred, test_set$default)[4])
## [1] 0.9913333

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

set.seed(2)
rand_obs <- sample.int(nrow(Default), nrow(Default)*.7)
train_set <- Default[rand_obs,]
test_set <- Default[-rand_obs,]
glm.fit.train <- glm(default ~ income + balance, data = train_set, family = "binomial")
glm.probs <- predict(glm.fit.train, newdata = test_set, type="response")
glm.pred <- rep("No", 3000)#length(glm.probs))
glm.pred[glm.probs>.5]="Yes"
(table(glm.pred, test_set$default)[1]+table(glm.pred, test_set$default)[3])/
  (table(glm.pred, test_set$default)[1]+table(glm.pred, test_set$default)[2]+
     table(glm.pred, test_set$default)[3]+table(glm.pred, test_set$default)[4])
## [1] 0.9823333
set.seed(3)
rand_obs <- sample.int(nrow(Default), nrow(Default)*.7)
train_set <- Default[rand_obs,]
test_set <- Default[-rand_obs,]
glm.fit.train <- glm(default ~ income + balance, data = train_set, family = "binomial")
glm.probs <- predict(glm.fit.train, newdata = test_set, type="response")
glm.pred <- rep("No", 3000)#nrow(glm.probs))
glm.pred[glm.probs>.5]="Yes"
(table(glm.pred, test_set$default)[1]+table(glm.pred, test_set$default)[3])/
  (table(glm.pred, test_set$default)[1]+table(glm.pred, test_set$default)[2]+
     table(glm.pred, test_set$default)[3]+table(glm.pred, test_set$default)[4])
## [1] 0.9883333

(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)
rand_obs <- sample.int(nrow(Default), nrow(Default)*.7)
train_set <- Default[rand_obs,]
test_set <- Default[-rand_obs,]
glm.fit.train <- glm(default ~ income + balance + student, data = train_set, family = "binomial")
glm.probs <- predict(glm.fit.train, newdata = test_set, type="response")
glm.pred <- rep("No", 3000)#nrow(glm.probs))
glm.pred[glm.probs>.5]="Yes"
table(glm.pred, test_set$default)
##         
## glm.pred   No  Yes
##      No  2896   81
##      Yes    2   21

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

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

(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(lm(default~income + balance,data=data,subset=index)))
boot.fn(Default ,1:10000)
## Warning in model.response(mf, "numeric"): using type = "numeric" with a factor
## response will be ignored
## Warning in Ops.factor(y, z$residuals): '-' not meaningful for factors
##  (Intercept)       income      balance 
## 9.077603e-01 4.604568e-07 1.318050e-04

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

(d) Comment on the estimated standard errors obtained using the glm() function and using your bootstrap function. ### 9. 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 \(μ\).

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

(b) Provide an estimate of the standard error of ˆμ. Interpret this result.

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

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

# boot.fn <- function(data, index) 
#   return(mean(data[index]))
# boot(Default,boot.fn,1000)