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.
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.
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.
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
# 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])
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.028
Validation set error: 2.8%
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%
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)
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
boot.fn <- function(Data, index){
coefs <- coef(glm(default ~ income + balance, data = Data, subset = index,
family = "binomial"))[c("income", "balance")]
return(coefs)
}
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.
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.
ˆμ <- mean(Boston$medv)
ˆμ
## [1] 22.53281
s_err <- sd(Boston$medv)/sqrt(length(Boston$medv))
s_err
## [1] 0.4088611
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.
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)
med_ˆμ <- median(Boston$medv)
med_ˆμ
## [1] 21.2
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.
ˆμ0.1 <- quantile(Boston$medv, 0.1)
ˆμ0.1
## 10%
## 12.75
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.