3. We now review k-fold cross-validation. (a) Explain how k-fold cross-validation is implemented. (b) What are the advantages and disadvantages of k-fold crossvalidation relative to: i. The validation set approach? ii. LOOCV?
K-fold cross-validation approach divides the set of observations into k-groups of equal sizes. The first group is treated as a test dataset. The model is fitted on the remaining k-1 fold. We then compute MSE on the observation of the test dataset. This method is repeated on different observations -i.e., on different k-groups that were held out as validation sets. Each time, different group is treated as a validation set and model is fitted on remaining k-1 observations. This process will result in MSE k-times. The k-fold CV is computed by averaging these values.
\(CV_{(k)} = 1/k \Sigma^{k}_{i=1}MSEi\)
Advantage of k-fold cross-validation relative to validation approach is that it is leaves only intermediate-level of bias (for k=5 -10) compared to validation approach. This is because, training set in k-fold cross-validation may contain more observations compared to validation approach.
K-fold cross-validation approach is less computationally intensive compared to LOOCV. The reasoning behind this is that, K-fold cross-validation approach contains only (k-1)n/k observations compared to LOOCV that contains n-1 observations in training dataset. Moreover, k-fold cross-validation has less variance compared to LOOCV. The LOOCV training datasets are identical. Hence, the observations may be correlated with each other. This results in high variance in LOOCV compared to K-fold cross validation.In short, k-fold cross validation may give more accurate estimate of the test error rate than does LOOCV.
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)
View(Default)
set.seed(1)
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
#The data is split such that 50% is training dataset and 50% is the test dataset
smp_size <- floor(0.50 * nrow(Default))
## set the seed to make your partition reproducible
set.seed(1)
train_ind <- sample(seq_len(nrow(Default)), size = smp_size)
Dtrain <- Default[train_ind, ]
Dtest <- Default[-train_ind, ]
ii. Fit a multiple logistic regression model using only the training observations.
#Dtrain is our training observation
set.seed(1)
glmfit.dt=glm(default ~ income + balance, data=Dtrain, family = "binomial")
summary(glmfit.dt)
##
## Call:
## glm(formula = default ~ income + balance, family = "binomial",
## data = Dtrain)
##
## Deviance Residuals:
## Min 1Q Median 3Q Max
## -2.5830 -0.1428 -0.0573 -0.0213 3.3395
##
## Coefficients:
## Estimate Std. Error z value Pr(>|z|)
## (Intercept) -1.194e+01 6.178e-01 -19.333 < 2e-16 ***
## income 3.262e-05 7.024e-06 4.644 3.41e-06 ***
## balance 5.689e-03 3.158e-04 18.014 < 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: 1523.8 on 4999 degrees of freedom
## Residual deviance: 803.3 on 4997 degrees of freedom
## AIC: 809.3
##
## 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.
glmprob.dt=predict(glmfit.dt, Dtest, type='response')
glmpred.dt=rep('No', length(glmprob.dt))
glmpred.dt[glmprob.dt>0.5]='Yes'
iv. Compute the validation set error, which is the fraction of the observations in the validation set that are misclassified.
table(glmpred.dt,Dtest$default)
##
## glmpred.dt No Yes
## No 4824 108
## Yes 19 49
mean(glmpred.dt != Dtest$default)
## [1] 0.0254
The test error rate of the test dataset is 2.54%.The model incorrectly predicted 2.54% of the time.
(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.
#The data is split such that 75% is training dataset and 25% is the test dataset
smp_size <- floor(0.75 * nrow(Default))
## set the seed to make your partition reproducible
set.seed(1)
train_ind <- sample(seq_len(nrow(Default)), size = smp_size)
Dtrain1 <- Default[train_ind, ]
Dtest1 <- Default[-train_ind, ]
#Dtrain1 is our training observation
set.seed(1)
glmfit.dt1=glm(default ~ income + balance, data=Dtrain1, family = "binomial")
summary(glmfit.dt1)
##
## Call:
## glm(formula = default ~ income + balance, family = "binomial",
## data = Dtrain1)
##
## Deviance Residuals:
## Min 1Q Median 3Q Max
## -2.4675 -0.1399 -0.0557 -0.0207 3.3511
##
## Coefficients:
## Estimate Std. Error z value Pr(>|z|)
## (Intercept) -1.171e+01 5.071e-01 -23.098 < 2e-16 ***
## income 2.515e-05 5.803e-06 4.334 1.47e-05 ***
## balance 5.622e-03 2.612e-04 21.526 < 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: 2178.7 on 7499 degrees of freedom
## Residual deviance: 1157.7 on 7497 degrees of freedom
## AIC: 1163.7
##
## Number of Fisher Scoring iterations: 8
glmprob.dt1=predict(glmfit.dt1, Dtest1, type='response')
glmpred.dt1=rep('No', length(glmprob.dt1))
glmpred.dt1[glmprob.dt1>0.5]='Yes'
mean(glmpred.dt1 != Dtest1$default)
## [1] 0.026
The test error rate is 2.6% when the data was split by 75%. The model with 75% data as training and 25% of data as validation dataset predicted incorrectly 2.6% of the time.
#The data is split such that 80% is training dataset and 20% is the test dataset
smp_size <- floor(0.80 * nrow(Default))
## set the seed to make your partition reproducible
set.seed(1)
train_ind <- sample(seq_len(nrow(Default)), size = smp_size)
Dtrain2 <- Default[train_ind, ]
Dtest2 <- Default[-train_ind, ]
#Dtrain2 is our training observation
set.seed(1)
glmfit.dt2=glm(default ~ income + balance, data=Dtrain2, family = "binomial")
summary(glmfit.dt2)
##
## Call:
## glm(formula = default ~ income + balance, family = "binomial",
## data = Dtrain2)
##
## Deviance Residuals:
## Min 1Q Median 3Q Max
## -2.4758 -0.1413 -0.0563 -0.0210 3.4620
##
## Coefficients:
## Estimate Std. Error z value Pr(>|z|)
## (Intercept) -1.168e+01 4.893e-01 -23.879 < 2e-16 ***
## income 2.547e-05 5.631e-06 4.523 6.1e-06 ***
## balance 5.613e-03 2.531e-04 22.176 < 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: 2313.6 on 7999 degrees of freedom
## Residual deviance: 1239.2 on 7997 degrees of freedom
## AIC: 1245.2
##
## Number of Fisher Scoring iterations: 8
glmprob.dt2=predict(glmfit.dt2, Dtest2, type='response')
glmpred.dt2=rep('No', length(glmprob.dt2))
glmpred.dt2[glmprob.dt2>0.5]='Yes'
mean(glmpred.dt2 != Dtest2$default)
## [1] 0.026
The test error rate is 2.6% when the data was split by 80%. The model with 80% data as training and 20% of data as validation dataset predicted incorrectly 2.6% of the time. Interestingly it is same as the earlier one.
#The data is split such that 90% is training dataset and 10% is the test dataset
smp_size <- floor(0.90 * nrow(Default))
## set the seed to make your partition reproducible
set.seed(1)
train_ind <- sample(seq_len(nrow(Default)), size = smp_size)
Dtrain3 <- Default[train_ind, ]
Dtest3 <- Default[-train_ind, ]
#Dtrain3 is our training observation
set.seed(1)
glmfit.dt3=glm(default ~ income + balance, data=Dtrain3, family = "binomial")
summary(glmfit.dt3)
##
## Call:
## glm(formula = default ~ income + balance, family = "binomial",
## data = Dtrain3)
##
## Deviance Residuals:
## Min 1Q Median 3Q Max
## -2.4873 -0.1420 -0.0567 -0.0210 3.7315
##
## Coefficients:
## Estimate Std. Error z value Pr(>|z|)
## (Intercept) -1.167e+01 4.629e-01 -25.204 < 2e-16 ***
## income 2.384e-05 5.313e-06 4.487 7.22e-06 ***
## balance 5.652e-03 2.401e-04 23.542 < 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: 2603.6 on 8999 degrees of freedom
## Residual deviance: 1396.1 on 8997 degrees of freedom
## AIC: 1402.1
##
## Number of Fisher Scoring iterations: 8
glmprob.dt3=predict(glmfit.dt3, Dtest3, type='response')
glmpred.dt3=rep('No', length(glmprob.dt3))
glmpred.dt3[glmprob.dt3>0.5]='Yes'
mean(glmpred.dt3 != Dtest3$default)
## [1] 0.029
The test error rate is 2.9% when the data was split by 90%. The model with 90% data as training and 10% of data as validation dataset predicted incorrectly 2.9% of the time.
(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 errorrate.
#The data is split such that 90% is training dataset and 10% is the test dataset
smp_size <- floor(0.90 * nrow(Default))
## set the seed to make your partition reproducible
set.seed(1)
train_ind <- sample(seq_len(nrow(Default)), size = smp_size)
Dtrain3 <- Default[train_ind, ]
Dtest3 <- Default[-train_ind, ]
#Dtrain3 is our training observation
set.seed(1)
#adding the variable student here
glmfit.dt4=glm(default ~ income + balance + student, data=Dtrain3, family = "binomial")
summary(glmfit.dt4)
##
## Call:
## glm(formula = default ~ income + balance + student, family = "binomial",
## data = Dtrain3)
##
## Deviance Residuals:
## Min 1Q Median 3Q Max
## -2.4876 -0.1399 -0.0547 -0.0200 3.7390
##
## Coefficients:
## Estimate Std. Error z value Pr(>|z|)
## (Intercept) -1.090e+01 5.189e-01 -21.000 < 2e-16 ***
## income 3.175e-06 8.616e-06 0.368 0.71251
## balance 5.765e-03 2.460e-04 23.439 < 2e-16 ***
## studentYes -7.658e-01 2.508e-01 -3.054 0.00226 **
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## (Dispersion parameter for binomial family taken to be 1)
##
## Null deviance: 2603.6 on 8999 degrees of freedom
## Residual deviance: 1386.9 on 8996 degrees of freedom
## AIC: 1394.9
##
## Number of Fisher Scoring iterations: 8
glmprob.dt4=predict(glmfit.dt4, Dtest3, type='response')
glmpred.dt4=rep('No', length(glmprob.dt4))
glmpred.dt4[glmprob.dt4>0.5]='Yes'
mean(glmpred.dt4 != Dtest3$default)
## [1] 0.031
The test error rate is 3.1% when the ‘student’ variable was added.After adding the ‘student’ variable, the model predicted incorrectly 3.1% of the time, which is more than the earlier one (2.9% in the earlier model).
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.
#The data is split such that 50% is training dataset and 50% is the test dataset
smp_size <- floor(0.50 * nrow(Default))
## set the seed to make your partition reproducible
set.seed(1)
train_ind <- sample(seq_len(nrow(Default)), size = smp_size)
Dtrain <- Default[train_ind, ]
Dtest <- Default[-train_ind, ]
#Dtrain is our training observation
set.seed(1)
glmfit.dt=glm(default ~ income + balance, data=Dtrain, family = "binomial")
summary(glmfit.dt)$coef
## Estimate Std. Error z value Pr(>|z|)
## (Intercept) -1.194413e+01 6.177962e-01 -19.333444 2.810180e-83
## income 3.262025e-05 7.023514e-06 4.644434 3.410095e-06
## balance 5.689218e-03 3.158234e-04 18.013920 1.515093e-72
The bootstrap estimates of the standard errors are \(0.618, 7.024 X 10^{-6}\) and \(3.158 X 10^{-4}\).
(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) {
fit <- glm(default ~ income + balance, data = data, family = "binomial", subset = index)
return (coef(fit))
}
(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)
##
## 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
The bootstrap estimates of the standard errors are \(0.4345, 4.86 X 10^{-6}\) and \(2.299 X 10^{-4}\)
(d) Comment on the estimated standard errors obtained using the glm() function and using your bootstrap function.
The estimated standard errors obtained using glm() function and using bootstrap function is approximately similar.
9. We will now consider the Boston housing data set, from the MASS library.
library(MASS)
View(Boston)
(a) Based on this data set, provide an estimate for the population mean of medv. Call this estimate ˆμ.
Muhat<-mean(Boston$medv)
Muhat
## [1] 22.53281
Muhat is 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.
SDmedv<-sd(Boston$medv)
nummedv<-length(Boston$medv)
sqrtnummedv<-sqrt(nummedv)
SEmedv<-SDmedv/sqrtnummedv
SEmedv
## [1] 0.4088611
The standard error is 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.fn <- function(data, index){
muhat <- mean(data[index])
return(muhat)
}
bootmedv<-boot(Boston$medv,boot.fn,1000)
bootmedv
##
## ORDINARY NONPARAMETRIC BOOTSTRAP
##
##
## Call:
## boot(data = Boston$medv, statistic = boot.fn, R = 1000)
##
##
## Bootstrap Statistics :
## original bias std. error
## t1* 22.53281 0.007650791 0.4106622
The estimated standard error using bootstrap is 0.410
(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(ˆμ)].
boot.ci(boot.out = bootmedv, type = c("norm","basic"))
## BOOTSTRAP CONFIDENCE INTERVAL CALCULATIONS
## Based on 1000 bootstrap replicates
##
## CALL :
## boot.ci(boot.out = bootmedv, type = c("norm", "basic"))
##
## Intervals :
## Level Normal Basic
## 95% (21.72, 23.33 ) (21.68, 23.31 )
## Calculations and Intervals on Original Scale
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 after bootstrapping is 21.72-23.33. The confidence interval after using t-test is 21.72953 - 23.33608. Both are approximately same. Trying the formula, suggested in the question with Mu = 22.53281 and SE after bootstrap is 0.410
CI = c(22.53281-(2*0.410),22.53281 +(2*0.410) )
CI
## [1] 21.71281 23.35281
After trying the formula, the CI is 21.71281-23.35281, which is again more or less similar to earlier one.
(e) Based on this data set, provide an estimate, ˆμmed, for the median value of medv in the population.
med<-median(Boston$medv)
med
## [1] 21.2
Median is 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)
boot.fn <- function(data, index){
mu <- median(data[index])
return(mu)
}
bootmedian<-boot(Boston$medv,boot.fn,1000)
bootmedian
##
## ORDINARY NONPARAMETRIC BOOTSTRAP
##
##
## Call:
## boot(data = Boston$medv, statistic = boot.fn, R = 1000)
##
##
## Bootstrap Statistics :
## original bias std. error
## t1* 21.2 0.02295 0.3778075
The standard error of the median using bootstrap is 0.3778075.
(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.)
set.seed(1)
Mu.1<-quantile(Boston$medv, probs = c(0.1))
Mu.1
## 10%
## 12.75
The tenth percentile of medv in Boston suburbs is 12.75.
(h) Use the bootstrap to estimate the standard error of ˆμ0.1. Comment on your findings
set.seed(1)
boot.fn <- function(data, index){
mu.1 <- quantile(data[index],c(0.1))
return(mu.1)
}
bootq<-boot(Boston$medv,boot.fn,1000)
bootq
##
## ORDINARY NONPARAMETRIC BOOTSTRAP
##
##
## Call:
## boot(data = Boston$medv, statistic = boot.fn, R = 1000)
##
##
## Bootstrap Statistics :
## original bias std. error
## t1* 12.75 0.0339 0.4767526
The estimated tenth percentile value is 12.75, which is same as obtained in (g). The standard error is 0.4767526, which is small compared to 12.75.