(a) Explain how k-fold cross-validation is implemented.
According to G. James et al., k-Fold Cross_validation involves randomly dividing the set of observation into k groups of approximately equal size. The first fold is treated as validation set, the rest \(k-1\) is used to fit the method. The MSE is computed on the observations in the validation set. This procedure is repeated \(k\) times where each time a different group of observations is treated as a validation set. This process will result in \(k\) estimated of test errors. The k-fold CV estimate is computed by averaging these values.
(b) What are the advantages and disadvantages of k-fold cross-validation relative to:
i. The validation set approach?
ii. LOOCV?
One of the advantage of k-fold CV is computational.. It can be applied to almost any statistical learning method. Another advantage involves the bias-variance trade-off. For instance, k-fold CV gives more accurate estimates of the test error than does LOOCV. However, from the perspective of bias reduction, LOOCV is better.But, k-fold CV has lower variance than the test error resulting from LOOCV. Comparing k-fold CV to the validation set, it has lower variability than validation set. The validation set method can overestimate the test error. However the validation set has a computational advantages because a model is only train once and tested once.
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.
str(Default)
## 'data.frame': 10000 obs. of 4 variables:
## $ default: Factor w/ 2 levels "No","Yes": 1 1 1 1 1 1 1 1 1 1 ...
## $ student: Factor w/ 2 levels "No","Yes": 1 2 1 1 1 2 1 2 1 1 ...
## $ balance: num 730 817 1074 529 786 ...
## $ income : num 44362 12106 31767 35704 38463 ...
attach(Default)
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) 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)
index = sample(nrow(Default), 0.7*nrow(Default), replace = FALSE)
train = Default[index, ]
validation_set = Default[-index, ]
dim(validation_set)
## [1] 3000 4
ii. Fit a multiple logistic regression model using only the training observations.
glm.fit1 = glm(default ~ income + balance, data = train, family = "binomial")
summary(glm.fit1)
##
## Call:
## glm(formula = default ~ income + balance, family = "binomial",
## data = train)
##
## Deviance Residuals:
## Min 1Q Median 3Q Max
## -2.4481 -0.1402 -0.0561 -0.0211 3.3484
##
## Coefficients:
## Estimate Std. Error z value Pr(>|z|)
## (Intercept) -1.167e+01 5.214e-01 -22.379 < 2e-16 ***
## income 2.560e-05 6.012e-06 4.258 2.06e-05 ***
## balance 5.574e-03 2.678e-04 20.816 < 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: 2030.3 on 6999 degrees of freedom
## Residual deviance: 1079.6 on 6997 degrees of freedom
## AIC: 1085.6
##
## Number of Fisher Scoring iterations: 8
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.prob = predict(glm.fit1, newdata = validation_set, type = "response")
glm.pred = rep("No", 3000 )
glm.pred[glm.prob > .5] = "Yes"
table(glm.pred, validation_set$default)
##
## glm.pred No Yes
## No 2896 78
## Yes 2 24
glm.pred[1:10]
## [1] "No" "No" "No" "No" "No" "No" "No" "No" "No" "No"
iv. Compute the validation set error, which is the fraction of the observations in the validation set that are misclassified.
mean(validation_set$default != glm.pred)
## [1] 0.02666667
(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(10)
index1 = sample(nrow(Default), 0.7*nrow(Default), replace = FALSE)
train1 = Default[index1, ]
validation_set1 = Default[-index1, ]
glm.fit2 = glm(default ~ income + balance, data = train1, family = "binomial")
glm.prob1 = predict(glm.fit2, newdata = validation_set1, type = "response")
glm.pred1 = rep("No", 3000 )
glm.pred1[glm.prob1 > .5] = "Yes"
mean(validation_set1$default != glm.pred1)
## [1] 0.027
set.seed(42)
index2 = sample(nrow(Default), 0.7*nrow(Default), replace = FALSE)
train2 = Default[index2, ]
validation_set2 = Default[-index2, ]
glm.fit3 = glm(default ~ income + balance, data = train2, family = "binomial")
glm.prob2 = predict(glm.fit3, newdata = validation_set2, type = "response")
glm.pred2 = rep("No", 3000 )
glm.pred2[glm.prob2 > .5] = "Yes"
mean(validation_set2$default != glm.pred2)
## [1] 0.026
set.seed(123)
index3 = sample(nrow(Default), 0.7*nrow(Default), replace = FALSE)
train3 = Default[index3, ]
validation_set3 = Default[-index3, ]
glm.fit4 = glm(default ~ income + balance, data = train3, family = "binomial")
glm.prob3 = predict(glm.fit4, newdata = validation_set3, type = "response")
glm.pred3 = rep("No", 3000 )
glm.pred3[glm.prob3 > .5] = "Yes"
mean(validation_set3$default != glm.pred3)
## [1] 0.02633333
Average_test_error = (0.02666667 + 0.027 + 0.026 + 0.02633333)/4
Average_test_error
## [1] 0.0265
There is some variation as expected.
(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(150)
index4 = sample(nrow(Default), 0.7*nrow(Default), replace = FALSE)
train4 = Default[index4, ]
validation_set4 = Default[-index4, ]
glm.fit5 = glm(default ~ income + balance + student, data = train4, family = "binomial")
glm.prob4 = predict(glm.fit5, newdata = validation_set4, type = "response")
glm.pred4 = rep("No", 3000 )
glm.pred4[glm.prob4 > .5] = "Yes"
mean(validation_set4$default != glm.pred4)
## [1] 0.02733333
Including a dummy variable for student leads to a increase of the test error rate.
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.set.seed(50)
glm.fit6 = glm(default ~ income + balance, data = Default, family = "binomial")
(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.
summary(glm.fit6)$coefficients[, 2]
## (Intercept) income balance
## 4.347564e-01 4.985167e-06 2.273731e-04
(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 = 1:nrow(data)) {
coef(glm(default ~ income + balance, data = data, subset = index, family = "binomial"))[-1]
}
boot.fn(Default)
## income balance
## 2.080898e-05 5.647103e-03
(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.
set.seed(200)
SE_estimate = boot(data = Default, statistic = boot.fn, R = 1000)
SE_estimate
##
## ORDINARY NONPARAMETRIC BOOTSTRAP
##
##
## Call:
## boot(data = Default, statistic = boot.fn, R = 1000)
##
##
## Bootstrap Statistics :
## original bias std. error
## t1* 2.080898e-05 3.615921e-07 4.889933e-06
## t2* 5.647103e-03 1.128926e-05 2.268953e-04
(d) Comment on the estimated standard errors obtained using the glm() function and using your bootstrap function.
summary(glm.fit6)$coefficients[2:3, 2]
## income balance
## 4.985167e-06 2.273731e-04
sapply(data.frame(income = SE_estimate$t[ ,1], balance = SE_estimate$t[ ,2]), sd)
## income balance
## 4.889933e-06 2.268953e-04
Difference = summary(glm.fit6)$coefficients[2:3, 2] - sapply(data.frame(income = SE_estimate$t[ ,1], balance = SE_estimate$t[ ,2]), sd)
Difference
## income balance
## 9.523396e-08 4.778048e-07
The results are closed, but small difference. So we can assume that the logistic standards error is good.
Boston housing data set, from the MASS library.str(Boston)
## 'data.frame': 506 obs. of 14 variables:
## $ crim : num 0.00632 0.02731 0.02729 0.03237 0.06905 ...
## $ zn : num 18 0 0 0 0 0 12.5 12.5 12.5 12.5 ...
## $ indus : num 2.31 7.07 7.07 2.18 2.18 2.18 7.87 7.87 7.87 7.87 ...
## $ chas : int 0 0 0 0 0 0 0 0 0 0 ...
## $ nox : num 0.538 0.469 0.469 0.458 0.458 0.458 0.524 0.524 0.524 0.524 ...
## $ rm : num 6.58 6.42 7.18 7 7.15 ...
## $ age : num 65.2 78.9 61.1 45.8 54.2 58.7 66.6 96.1 100 85.9 ...
## $ dis : num 4.09 4.97 4.97 6.06 6.06 ...
## $ rad : int 1 2 2 3 3 3 5 5 5 5 ...
## $ tax : num 296 242 242 222 222 222 311 311 311 311 ...
## $ ptratio: num 15.3 17.8 17.8 18.7 18.7 18.7 15.2 15.2 15.2 15.2 ...
## $ black : num 397 397 393 395 397 ...
## $ lstat : num 4.98 9.14 4.03 2.94 5.33 ...
## $ medv : num 24 21.6 34.7 33.4 36.2 28.7 22.9 27.1 16.5 18.9 ...
(a) Based on this data set, provide an estimate for the population mean of medv. Call this estimate \(\hat{μ}\).
sample_mean = mean(Boston$medv)
sample_mean
## [1] 22.53281
(b) Provide an estimate of the standard error of \(\hat{μ}\). 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.
Standard_Error = sd(Boston$medv) / sqrt(length(Boston$medv))
Standard_Error
## [1] 0.4088611
(c) Now estimate the standard error of \(\hat{μ}\) using the bootstrap. How does this compare to your answer from (b)?
set.seed(42)
boot.fn <- function(vector, index) {
mean(vector[index])
}
SE = boot(data = Boston$medv, statistic = boot.fn, R = 1000)
SE
##
## ORDINARY NONPARAMETRIC BOOTSTRAP
##
##
## Call:
## boot(data = Boston$medv, statistic = boot.fn, R = 1000)
##
##
## Bootstrap Statistics :
## original bias std. error
## t1* 22.53281 0.02671186 0.4009216
0.4088611 - 0.4009216
## [1] 0.0079395
There is a small difference of 0.008. They are the same up to the 2nd decimal place.
(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 \([\hat{μ} − 2SE(\hat{μ}), \hat{μ} + 2SE(\hat{μ})]\).
SD_bootstrap = sd(SE$t)
c(mean(Boston$medv) - 2 * SD_bootstrap, mean(Boston$medv) + 2 * SD_bootstrap)
## [1] 21.73096 23.33465
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
The confidence interval estimates are the same, but small difference.
(e) Based on this data set, provide an estimate, \(\hat{μ}_{med}\), for the median value of medv in the population.
median(Boston$medv)
## [1] 21.2
(f) We now would like to estimate the standard error of \(\hat{μ}_{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(42)
boot.fn <- function(vector, index) {
median(vector[index])
}
SE_median = boot(data = Boston$medv, statistic = boot.fn, R = 1000)
SE_median
##
## ORDINARY NONPARAMETRIC BOOTSTRAP
##
##
## Call:
## boot(data = Boston$medv, statistic = boot.fn, R = 1000)
##
##
## Bootstrap Statistics :
## original bias std. error
## t1* 21.2 0.0106 0.3661785
The standard error is also small.
(g) Based on this data set, provide an estimate for the tenth percentile of medv in Boston suburbs. Call this quantity \(\hat{μ}_{0.1}\). (You can use the quantile() function.)
quantile(Boston$medv, 0.1)
## 10%
## 12.75
(h) Use the bootstrap to estimate the standard error of \(\hat{μ}_{0.1}\). Comment on your findings.
set.seed(42)
boot.fn <- function(vector, index) {
quantile(vector[index], 0.1)
}
tenth_percentile = boot(data = Boston$medv, statistic = boot.fn, R = 1000)
tenth_percentile
##
## ORDINARY NONPARAMETRIC BOOTSTRAP
##
##
## Call:
## boot(data = Boston$medv, statistic = boot.fn, R = 1000)
##
##
## Bootstrap Statistics :
## original bias std. error
## t1* 12.75 0.0215 0.4948966
The standard error is relative larger than the previous results.