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(ISLR2)
dat = Default
mod1 <- glm(default ~ balance + income, data = dat, family = binomial)
summary(mod1)
##
## Call:
## glm(formula = default ~ balance + income, family = binomial,
## data = dat)
##
## 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 ***
## balance 5.647e-03 2.274e-04 24.836 < 2e-16 ***
## income 2.081e-05 4.985e-06 4.174 2.99e-05 ***
## ---
## 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(007)
q = sample(nrow(dat), nrow(dat)*0.8)
train = dat[q, ] #training data
val = dat[-q, ] #validation data
ii. Fit a multiple logistic regression model using only the training observations.
train_mod <- glm(default ~ balance + income, data = train, family = binomial)
summary(train_mod)
##
## Call:
## glm(formula = default ~ balance + income, family = binomial,
## data = train)
##
## Deviance Residuals:
## Min 1Q Median 3Q Max
## -2.4696 -0.1450 -0.0575 -0.0215 3.7100
##
## Coefficients:
## Estimate Std. Error z value Pr(>|z|)
## (Intercept) -1.148e+01 4.837e-01 -23.738 < 2e-16 ***
## balance 5.636e-03 2.537e-04 22.218 < 2e-16 ***
## income 2.004e-05 5.505e-06 3.641 0.000272 ***
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## (Dispersion parameter for binomial family taken to be 1)
##
## Null deviance: 2354.0 on 7999 degrees of freedom
## Residual deviance: 1282.6 on 7997 degrees of freedom
## AIC: 1288.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.
test_prob <- predict(train_mod, val, type = "response")
test_pred <- as.factor(ifelse(test_prob > 0.5, "Yes", "No"))
iv. Compute the validation set error, which is the fraction of the observations in the validation set that are misclassified.
conf_mat = table(val$default, test_pred)
error = (conf_mat[[2]] + conf_mat[[2]])/length(val$default)
print(paste("Fraction of the observations in the validation set that are misclassified is", error))
## [1] "Fraction of the observations in the validation set that are misclassified is 0.038"
(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.
## Round 1
set.seed(008)
q1 = sample(nrow(dat), nrow(dat)*0.6)
train1 = dat[q1, ] #training data
val1 = dat[-q1, ] #validation data
train_mod1 <- glm(default ~ balance + income, data = train1, family = binomial)
test_prob1 <- predict(train_mod1, val1, type = "response")
test_pred1 <- as.factor(ifelse(test_prob1 > 0.5, "Yes", "No"))
conf_mat1 = table(val1$default, test_pred1)
error1 = (conf_mat1[[2]] + conf_mat1[[2]])/length(val1$default)
print(paste("Fraction of the observations in the validation set that are misclassified is", error1))
## [1] "Fraction of the observations in the validation set that are misclassified is 0.0455"
## Round 2
set.seed(009)
q2 = sample(nrow(dat), nrow(dat)*0.7)
train2 = dat[q2, ] #training data
val2 = dat[-q2, ] #validation data
train_mod2 <- glm(default ~ balance + income, data = train2, family = binomial)
test_prob2 <- predict(train_mod2, val2, type = "response")
test_pred2 <- as.factor(ifelse(test_prob2 > 0.5, "Yes", "No"))
conf_mat2 = table(val2$default, test_pred2)
error2 = (conf_mat2[[2]] + conf_mat2[[2]])/length(val2$default)
print(paste("Fraction of the observations in the validation set that are misclassified is", error2))
## [1] "Fraction of the observations in the validation set that are misclassified is 0.0393333333333333"
## Round 3
set.seed(010)
q3 = sample(nrow(dat), nrow(dat)*0.9)
train3 = dat[q3, ] #training data
val3 = dat[-q3, ] #validation data
train_mod3 <- glm(default ~ balance + income, data = train3, family = binomial)
test_prob3 <- predict(train_mod3, val3, type = "response")
test_pred3 <- as.factor(ifelse(test_prob3 > 0.5, "Yes", "No"))
conf_mat3 = table(val3$default, test_pred3)
error3 = (conf_mat3[[2]] + conf_mat3[[2]])/length(val3$default)
print(paste("Fraction of the observations in the validation set that are misclassified is", error3))
## [1] "Fraction of the observations in the validation set that are misclassified is 0.038"
err = data.frame("Round" = c(1,2,3),
"Split" = c("60:40", "70:30","90:10"),
"Error" = c(error1, error2, error3))
print(err)
## Round Split Error
## 1 1 60:40 0.04550000
## 2 2 70:30 0.03933333
## 3 3 90:10 0.03800000
Here, we can observe that irrespective of the split ratio there is not much difference in the misclassification error. The errors are very close to each other. However, we can surely claim that increasing the size of the training data improves the model accuracy as model learns the pattern well from the data.
(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(011)
library(fastDummies) #for creating dummy columns
dat1 <- dummy_cols(dat, select_columns = "student")
q4 = sample(nrow(dat1), nrow(dat1)*0.8)
train4 = dat1[q4, ] #training data
val4 = dat1[-q4, ] #validation data
train_mod4 <- glm(default ~., data = train4, family = binomial)
test_prob4 <- predict(train_mod4, val4, type = "response")
## Warning in predict.lm(object, newdata, se.fit, scale = 1, type = if (type == :
## prediction from a rank-deficient fit may be misleading
test_pred4 <- as.factor(ifelse(test_prob4 > 0.5, "Yes", "No"))
conf_mat4 = table(val4$default, test_pred4)
error4 = (conf_mat4[[2]] + conf_mat4[[2]])/length(val4$default)
print(paste("Fraction of the observations in the validation set that are misclassified is", error4))
## [1] "Fraction of the observations in the validation set that are misclassified is 0.033"
Ans: Including the dummy columns for “student” makes a minor reduction to misclassification
We will now consider the Boston housing data set, from the ISLR2 library.
(a) Based on this data set, provide an estimate for the population mean of medv. Call this estimate ˆμ.
library(ISLR2)
bos = Boston
mu_hat = mean(bos$medv)
print(paste("Estimate for the population mean of medv is ", mu_hat))
## [1] "Estimate for the population mean of medv is 22.5328063241107"
(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.
se_mu_hat = sd(bos$medv)/sqrt(length(bos$medv))
print(paste("Estimate of the standard error of ˆμ is", se_mu_hat))
## [1] "Estimate of the standard error of \210µ is 0.408861147497535"
Ans: Standard Error of 0.408 indicate that mu_hat of “medv” is close to the true mean of the population as the standard error value is small.
(c) Now estimate the standard error of ˆμ using the bootstrap. How does this compare to your answer from (b)?
boot.fn <- function(data, index){
return(mean(data[index]))}
library(boot)
se <- boot(bos$medv, boot.fn, 500)
se
##
## ORDINARY NONPARAMETRIC BOOTSTRAP
##
##
## Call:
## boot(data = bos$medv, statistic = boot.fn, R = 500)
##
##
## Bootstrap Statistics :
## original bias std. error
## t1* 22.53281 0.007449012 0.4012182
Ans: The standard error of 0.417 is very close to the standard error in (b)
(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(ˆμ)].
c(se$t0 - 2 * 0.417, se$t0 + 2 * 0.417)
## [1] 21.69881 23.36681
t.test(bos$medv)
##
## One Sample t-test
##
## data: bos$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
Ans: Confidence Interval of 95% from t-test is [21.72953, 23.33608] whereas confidence interval from boostrap is [21.69881, 23.36681]. They are very close to each other.
(e) Based on this data set, provide an estimate, ˆμmed, for the median value of medv in the population.
mu_med = median(bos$medv)
mu_med
## [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.
boot.fn.med <- function(data, index){
return(median(data[index]))}
library(boot)
se <- boot(bos$medv, boot.fn.med, 500)
se
##
## ORDINARY NONPARAMETRIC BOOTSTRAP
##
##
## Call:
## boot(data = bos$medv, statistic = boot.fn.med, R = 500)
##
##
## Bootstrap Statistics :
## original bias std. error
## t1* 21.2 -0.0356 0.3913297
Ans: Even the standartd error of the median using bootstrap is small. However, it seems to slightly more closer to the true population median.
(g) Based on this data set, provide an estimate for the tenth percentile of medv in Boston census tracts. Call this quantity ˆμ0.1. (You can use the quantile() function.)
mu_hat_0.1 = quantile(bos$medv,0.1)
mu_hat_0.1
## 10%
## 12.75
(h) Use the bootstrap to estimate the standard error of ˆμ0.1. Comment on your findings.
set.seed(1)
boot.fn.quan <- function(data, index){
return(quantile(data[index], c(0.1)))}
library(boot)
se <- boot(bos$medv, boot.fn.quan, 500)
se
##
## ORDINARY NONPARAMETRIC BOOTSTRAP
##
##
## Call:
## boot(data = bos$medv, statistic = boot.fn.quan, R = 500)
##
##
## Bootstrap Statistics :
## original bias std. error
## t1* 12.75 0.0184 0.5147634
Ans: The standard error of the quantile 10% performs worse than standard error of mean and median but is still relatively small.