suppressMessages(library(ISLR))
suppressMessages(library(MASS))
suppressMessages(library(boot))
Resampling methods bring with them a way for statisticians,data analysts,and anyone interested in statistics,to obtain information that would not be available from fitting a model only once using the same training sample. Resampling methods are tools that involve repeatedly taking samples from the training data set and refitting a model of interest on each sample in order to squeeze out more information.
The following exercises touch on a few areas of resampling methods from the ISLR book found in chapter 5.
We now review k-fold cross-validation.
(a) Explain how k-fold cross-validation is implemented.
RESPONSE: K-fold cross validation, involves randomly dividing the set of observations into k groups, AKA folds, of about equal size. The initial fold is treated as a validation set and the method is fit on the remaining k-1 folds. The MSE of the k-fold cross validation is then determined off of the observations in the held-out fold, which is then repetead k times, each time using a different group of data observations as the validation set. This results in a k estimate of test errors which are averaged out to get the k-fold cross validation estimate. The magic k values most experts use is k = 5 or k = 10.
(b) What are the advantages and disadvantages of k-fold crossvalidation relative to:
i. The validation set approach?
RESPONSE: Some advantages of using the k-fold cross validation method is that it is not just tested on one set of observations compared to the validation set approach resulting in greatly reducing the variability in our test error estimates. For example, if the validation set approach was repeated 10 times over the same data we would see different MSE terms. The validation set approach can also lead to an over-estimate of test error rates because the training set used to learn the method usually contains a larger subset of observations from the entire data set. A disadvantage of K-fold CV is that it is not as simple as the validation set approach, however statisitcal methods tend to perform worse when trained on smaller observations, where the k-fold CV method repeats on a different group of observations and averages the estimated error, overcomes that issue.
ii. LOOCV?
RESPONSE: Besides the clear computational advantage, k-folds actually gives a more accurate test error estimate than LOOCV. This has to do with the Bias-Variance trade off for the k-fold cross validation. Keep in mind, when we use a k = 5 or k = 10 model, we essentially average out only 5 or 10 models that may be less coorelated to each other as opposed to the leave-one-out cross validation(LOOCV) method where we are training on many more obseravtions(basically as many models as there are observations) with outputs that are highly correlated. Since the overlap between tranining set is smaller in k-folds CV(k =5|k =10) we see a smaller variance using the k-folds CV method. This makes sense because a mean of many highly correlated quanitites has a higher variance than does the mean of many quantaties that are not highly correlated.. Now when it comes to bias yes the K-folds method is at a disadvantage to LOOCV but we know that bias is not our only problem in an estimating procedure, we must also look at the procedures variance. The Bias-Variance tradeoff here results in a favorable estimated MSE outcome using the k-fold cross vaildation method.
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.
attach(Default)
set.seed(1)
glm.fit.default <- glm(default~ income+balance, family = "binomial", data = Default)
summary(glm.fit.default)
##
## 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)
train <- sample(10000,5000) # there are 10,000 observations in the Default data set
head(train)
## [1] 1017 8004 4775 9725 8462 4050
ii. Fit a multiple logistic regression model using only the training observations.
fitted.glm<- glm(default ~ income + balance, family = 'binomial', data = Default, subset = train)
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.
prob1 <- predict(fitted.glm , newdata = Default[-train,], type = "response")
pred1 <- ifelse(prob1 > 0.5, 'Yes','No')
iv. Compute the validation set error, which is the fraction of the observations in the validation set that are misclassified.
table(pred1, Default[-train,]$default)
##
## pred1 No Yes
## No 4824 108
## Yes 19 49
mean(pred1 != Default[-train,'default']) # the validation set method yielded a 2.54% test error rate
## [1] 0.0254
(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.
# first repetition
set.seed(2)
train <- sample(10000,5000)
fitted.glm2 <- glm(default ~ income + balance, data = Default, family = "binomial", subset = train)
fitted.prob2 <- predict(fitted.glm2, newdata = Default[-train, ], type = "response")
fitted.pred2 <- ifelse(fitted.prob2 > .5, 'Yes','No')
mean(fitted.pred2 != Default[-train, ]$default) # Test error = 2.38%
## [1] 0.0238
# second repetition
set.seed(3)
train <- sample(10000,5000)
fitted.glm2 <- glm(default ~ income + balance, data = Default, family = "binomial", subset = train)
fitted.prob2 <- predict(fitted.glm2, newdata = Default[-train, ], type = "response")
fitted.pred2 <- ifelse(fitted.prob2 > .5, 'Yes','No')
mean(fitted.pred2 != Default[-train, ]$default) # Test error = 2.64%
## [1] 0.0264
# third repetition
set.seed(4)
train <- sample(10000,5000)
fitted.glm2 <- glm(default ~ income + balance, data = Default, family = "binomial", subset = train)
fitted.prob2 <- predict(fitted.glm2, newdata = Default[-train, ], type = "response")
fitted.pred2 <- ifelse(fitted.prob2 > .5, 'Yes','No')
mean(fitted.pred2 != Default[-train, ]$default) # Test error = 2.56%
## [1] 0.0256
RESPONSE: By performing the validation set method multiple times, we see that the test error estimates obtained varied every time we ran a new model using three different splits of the observations into a training and a validation set. The resulting test error ranged from 2.38%-2.64% so there is not a great disparity between the errors but there is still a variance.
(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)
train <- sample(10000,5000)
fitted.glm3 <- glm(default ~ income + balance + student, data=Default, family=binomial, subset=train)
fitted.prob3 <- predict(fitted.glm3, Default[-train,], type="response")
fitted.pred3 <- ifelse(fitted.prob3 > 0.5, "Yes", "No")
mean(Default[-train,]$default != fitted.pred3) # test error = 2.6%
## [1] 0.026
RESPONSE: By including the dummy variable student, I showed no real reduction in the test error rate given that it fell within the ranges that were previously observed using the validation set method without the dummy variable..
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(1)
summary(glm(default~income+balance,data=Default,family='binomial'))
##
## 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
REPONSE: the standard error of the coefficients are given from the output above, income associated with β1 = .000004985 and balance or β2 = .0002274.
(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.
set.seed(1)
boot.fn <- function(data, index) {
fit <- glm(default ~ income + balance, data = data, family = "binomial", subset = index)
return (coef(fit))
}
boot.fn(Default, 1:nrow(Default)) # checking to see if coefficient estimates match
## (Intercept) income balance
## -1.154047e+01 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.
boot(Default, boot.fn, R=1000)
##
## ORDINARY NONPARAMETRIC BOOTSTRAP
##
##
## Call:
## boot(data = Default, statistic = boot.fn, R = 1000)
##
##
## Bootstrap Statistics :
## original bias std. error
## t1* -1.154047e+01 -3.945460e-02 4.344722e-01
## t2* 2.080898e-05 1.680317e-07 4.866284e-06
## t3* 5.647103e-03 1.855765e-05 2.298949e-04
(d) Comment on the estimated standard errors obtained using the glm() function and using your bootstrap function.
RESPONSE: When comparing the estimated std. errors obtained from both the glm() function and using the bootstrap technique, which was propsed by Bradely Efron, of which he won the National Medal of science for pioneering this influential staistical method, we really don’t see much of a difference.We can infer that this means the glm function serves as a good approximation of the estimated std. errors.
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 ˆμ.
attach(Boston)
mu.hat <- mean(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.
std.err =sd(medv)/sqrt(dim(Boston)[1])
print(std.err)
## [1] 0.4088611
(c) Now estimate the standard error of ˆμ using the bootstrap. How does this compare to your answer from (b)?
set.seed(1)
boot(medv,function(x,index){mean(x[index])},R=1000)
##
## ORDINARY NONPARAMETRIC BOOTSTRAP
##
##
## Call:
## boot(data = medv, statistic = function(x, index) {
## mean(x[index])
## }, R = 1000)
##
##
## Bootstrap Statistics :
## original bias std. error
## t1* 22.53281 0.007650791 0.4106622
RESPOSNE: The estimate of the standard error of ˆμ using the bootstrap method yielded a similiar result to the estimate of the standard error of ˆμ not using the bootstrap method.
(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(ˆμ)].
t.test(medv)
##
## One Sample t-test
##
## data: 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
CI<- c(22.53281 - 2 * .4106622, 22.53281+2 * .4106622)
print(CI)
## [1] 21.71149 23.35413
RESPONSE: The two methods have approximate 95% confidence intervals.
(e) Based on this data set, provide an estimate, ˆμ med, for the median value of medv in the population.
median.hat <- median(medv)
median.hat
## [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.
set.seed(1)
med.boot.fn <- function(data, index) {
mu <- median(data[index])
return (mu)
}
boot(medv, med.boot.fn, 1000)
##
## ORDINARY NONPARAMETRIC BOOTSTRAP
##
##
## Call:
## boot(data = medv, statistic = med.boot.fn, R = 1000)
##
##
## Bootstrap Statistics :
## original bias std. error
## t1* 21.2 0.02295 0.3778075
RESPONSE: The outputs has the same median values of 21.2 with the bootstrap method yielding a .378 std. error.
(g) Based on this data set, provide an estimate for the tenth percentile of medv in Boston suburbs. Call this quantity ˆμ0.1. (You can use the quantile() function.)
tenperc<- quantile(medv, c(0.1))
tenperc
## 10%
## 12.75
(h) Use the bootstrap to estimate the standard error of ˆμ 0.1. Comment on your findings.
boot(medv,function(data,index){quantile(medv[index],.1)},R=1000)
##
## ORDINARY NONPARAMETRIC BOOTSTRAP
##
##
## Call:
## boot(data = medv, statistic = function(data, index) {
## quantile(medv[index], 0.1)
## }, R = 1000)
##
##
## Bootstrap Statistics :
## original bias std. error
## t1* 12.75 0.01455 0.4823468
REPONSE: We see that using the bootstrap method to estimate the standard error of ˆμ 0.1 which is the 10th percentile of the median value is the same as in (g). The bootstrap aslo had a .493 std. error.