Chapter 5

Problem 3

3. We now review k-fold cross-validation.
(a) Explain how k-fold cross-validation is implemented.
A)k-fold cross validation randomly divides the set of observations into k groups or folds, of approximately equal size. The first fold is treated as a validation set, and the statistical learning method is applied/fitted on the remaining k − 1 folds. The mean squared error(MSE), is then computed on the observations in the held-out fold. This procedure is repeated k times; each time, a different group of observations is treated as a validation set. This process results in k estimates of the test errors. The k-fold cross validation estimate is computed by averaging these MSE s’.

(b) What are the advantages and disadvantages of k-fold cross validation relative to:
i. The validation set approach?
Advantages of k-fold over Validation set approach:
1) Unlike validation set approach, k-fold has less variability in the test error rates(MSE).
2) k-fold cross validation doesn’t over estimate the test error as all the data is used for training and testing. Where as the validation set approach uses data split which can result in a either more or less favorable by chance.
3) Less Bias compared to validation set approach.
disadvantages of k-fold over Validation set approach: 1) Validation set approach has an computational advantage over k-fold CV when the folds are higher.

ii. LOOCV? Advantages of k-fold over LOOCV : 1) k-fold CV with k < n has a computational advantage to LOOCV as k-fold fits model K times where as LOOCV does it n times. Putting computational issues aside, a less obvious but potentially more important advantage of k-fold CV is that it often gives more accurate estimates of the test error rate than does LOOCV. This has to do with a bias-variance trade-off.
2) k-fold CV has less variance compared to the highly flexible LOOCV.
3) k-fold CV is trained on less identical set of observations, where as LOOCV will be fitted on almost identical set of observations thus producing high variance in test error compared to k-fold CV.
Disadvantages of k-fold over LOOCV :
1)k-fold has high bias
2)Like validation set approach k-fold CV has some randomness on the way we select k-folds.

Problem 5

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.

mydefault <- Default
# Fitting logictic regression model on default data
logr_default <- glm(default ~ income + balance, data = mydefault, family = "binomial")
summary(logr_default)
## 
## Call:
## glm(formula = default ~ income + balance, family = "binomial", 
##     data = mydefault)
## 
## 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) Logistic regression to classify default using income and balance shows that both of the predictors are significant with Significant level at 0.05.

(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(452)
sample_def = sample.split(mydefault$default, SplitRatio = 0.70)
default_train<-subset(mydefault,sample_def==TRUE)
default_val<-subset(mydefault,sample_def==FALSE)

A) Using 70-30 split for training and validation data sets respectively.

ii. Fit a multiple logistic regression model using only the training observations.

# Fitting logictic regression model on default training data
lrdef_train <- glm(default ~ income + balance, data = default_train, family = "binomial")

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.

def_probs=predict(lrdef_train,default_val,type="response")


def_pred=rep("No",length(default_val$default))

def_pred[def_probs > .5] = "Yes"

table(def_pred,default_val$default)
##         
## def_pred   No  Yes
##      No  2889   69
##      Yes   11   31

iv. Compute the validation set error, which is the fraction of the observations in the validation set that are misclassified.

# misclassification rate  
mean(def_pred!=default_val$default) * 100
## [1] 2.666667

\[ Validation\ Misclassification\ Rate:: \frac{11+69}{3000}= 2.66\% \]
A) Validation misclassification rate is 2.66%

(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.

Try 1

#Split Try 1
set.seed(297)
sample_def = sample.split(mydefault$default, SplitRatio = 0.60)
default_train<-subset(mydefault,sample_def==TRUE)
default_val<-subset(mydefault,sample_def==FALSE)

#Fit Try 1
# Fitting logictic regression model on default training data
lrdef_train <- glm(default ~ income + balance, data = default_train, family = "binomial")
#Prediction Try 1
def_probs=predict(lrdef_train,default_val,type="response")


def_pred=rep("No",length(default_val$default))

def_pred[def_probs > .5] = "Yes"

table(def_pred,default_val$default)
##         
## def_pred   No  Yes
##      No  3854   85
##      Yes   13   48
#Misclassification rate try 1
mean(def_pred!=default_val$default) * 100
## [1] 2.45

\[ Validation\ Misclassification\ Rate(Try\ 1):: \frac{13+85}{4000}= 2.45\% \]

Try 2

#Split Try 1
set.seed(254)
sample_def = sample.split(mydefault$default, SplitRatio = 0.50)
default_train<-subset(mydefault,sample_def==TRUE)
default_val<-subset(mydefault,sample_def==FALSE)

#Fit Try 1
# Fitting logictic regression model on default training data
lrdef_train <- glm(default ~ income + balance, data = default_train, family = "binomial")
#Prediction Try 1
def_probs=predict(lrdef_train,default_val,type="response")


def_pred=rep("No",length(default_val$default))

def_pred[def_probs > .5] = "Yes"

table(def_pred,default_val$default)
##         
## def_pred   No  Yes
##      No  4817  113
##      Yes   16   54
#Misclassification rate try 1
mean(def_pred!=default_val$default) * 100
## [1] 2.58

\[ Validation\ Misclassification\ Rate(Try\ 2):: \frac{16+113}{5000}= 2.58\% \]

Try 3

#Split Try 1
set.seed(999)
sample_def = sample.split(mydefault$default, SplitRatio = 0.75)
default_train<-subset(mydefault,sample_def==TRUE)
default_val<-subset(mydefault,sample_def==FALSE)

#Fit Try 1
# Fitting logictic regression model on default training data
lrdef_train <- glm(default ~ income + balance, data = default_train, family = "binomial")
#Prediction Try 1
def_probs=predict(lrdef_train,default_val,type="response")


def_pred=rep("No",length(default_val$default))

def_pred[def_probs > .5] = "Yes"

table(def_pred,default_val$default)
##         
## def_pred   No  Yes
##      No  2406   60
##      Yes   11   23
#Misclassification rate try 1
mean(def_pred!=default_val$default) * 100
## [1] 2.84

\[ Validation\ Misclassification\ Rate(Try\ 3):: \frac{11+60}{2500}= 2.84\% \]
A) After multiple train, test splits along with different random seeds, I see that my Try 1 gave a lowest test error rate of \(2.45\%\). This try has a 60-40% split for training and validation sets.

(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.

#including Student as a predictor

set.seed(297)
sample_def = sample.split(mydefault$default, SplitRatio = 0.60)
default_train<-subset(mydefault,sample_def==TRUE)
default_val<-subset(mydefault,sample_def==FALSE)

#Fit Try 1
# Fitting logictic regression model on default training data
lrdef_train <- glm(default ~ income + balance + student, data = default_train, family = "binomial")
#Prediction Try 1
def_probs=predict(lrdef_train,default_val,type="response")


def_pred=rep("No",length(default_val$default))

def_pred[def_probs > .5] = "Yes"

table(def_pred,default_val$default)
##         
## def_pred   No  Yes
##      No  3855   87
##      Yes   12   46
#Misclassification rate try 1
mean(def_pred!=default_val$default) * 100
## [1] 2.475

A) Error/ Misclassification rate with student as additional predictor doesn’t improve the misclassification rate.Best score without student is 2.45% and with Student as predictor is 2.475%

Problem 6

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.

set.seed(986)
# Fitting logictic regression model on default training data
lrdef_std <- glm(default ~ income + balance, data = mydefault, family = "binomial")

summary(lrdef_std)$coefficients[2:3,]
##             Estimate   Std. Error   z value      Pr(>|z|)
## income  2.080898e-05 4.985167e-06  4.174178  2.990638e-05
## balance 5.647103e-03 2.273731e-04 24.836280 3.638120e-136

(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){
  lr_fn = glm(default ~ income + balance, data = data, subset = index,family = "binomial")
  return(summary(lr_fn)$coefficients[2:3,2])
}

(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(986)

boot(mydefault,boot.fn,R=100)
## 
## ORDINARY NONPARAMETRIC BOOTSTRAP
## 
## 
## Call:
## boot(data = mydefault, statistic = boot.fn, R = 100)
## 
## 
## Bootstrap Statistics :
##         original       bias     std. error
## t1* 4.985167e-06 1.076749e-08 1.282837e-07
## t2* 2.273731e-04 8.210079e-07 1.016713e-05

(d) Comment on the estimated standard errors obtained using the glm() function and using your bootstrap function. A)Above result indicates that the bootstrap estimate for \(SE(\hat{\beta}_{income})\) is 1.282837e-07, and that the bootstrap estimate for \(SE(\hat{\beta}_{balance})\) is 1.016713e-05. Using the summary() function, we computed the standard errors for the regression coefficients for \(SE(\hat{\beta}_{income})\) is 4.985167e-06 and for \(SE(\hat{\beta}_{balance})\) is 2.273731e-04.

The standard Errors from the bootstrap are lower compared to the standard error estimates obtained from the formulas.As the bootstrap approach does not rely on any of the assumptions that standard formulas take into account. Bootstap estimates for \(SE(\hat{\beta}_{income})\) and \(SE(\hat{\beta}_{balance})\) are likely giving a more accurate estimate of the standard errors that of the summary() function.

Problem 9

9. 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 \(\hat{\mu}\).

myboston <- Boston
mu_est <- mean(myboston$medv)
mu_est
## [1] 22.53281

A)\(\hat{\mu}=22.5328\)

(b) Provide an estimate of the standard error of \(\hat{\mu}\).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 = sd(myboston$medv)/sqrt(length(myboston$medv))
se_mu
## [1] 0.4088611

A) Standard error of \(\hat{\mu} = 0.40886\)

(c) Now estimate the standard error of \(\hat{\mu}\) using the bootstrap. How does this compare to your answer from (b)?

#boot strap function
set.seed(123)
boot_mu_fn <- function(data,index)
              return(mean(data[index]))

boot_result<- boot(myboston$medv,boot_mu_fn, R = 1000)

boot_result
## 
## ORDINARY NONPARAMETRIC BOOTSTRAP
## 
## 
## Call:
## boot(data = myboston$medv, statistic = boot_mu_fn, R = 1000)
## 
## 
## Bootstrap Statistics :
##     original      bias    std. error
## t1* 22.53281 -0.01607372   0.4045557

A) Standard error from Bootstrap for \(\hat{\mu} \ is\ 0.4045557\), this is slightly lower than that from (b),which is \(0.40886\)

(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{\mu}\)\(2*SE(\hat{\mu})\), \(\hat{\mu}\) + \(2*SE(\hat{\mu})\) ].

#confidence intervals using the SE from bootstrap is:

lower_bd <- mu_est - (2*0.4045557) #mu hat - 2 * SE(from bootstrap)
upper_db <- mu_est + (2*0.4045557) #mu hat + 2 * SE(from bootstrap)
lower_bd
## [1] 21.72369
upper_db
## [1] 23.34192

\(Lower\ bound\ is\ 21.72369\) \(Upper\ bound\ is\ 23.34192\)

using One Sampe t-Test

t.test(myboston$medv)
## 
##  One Sample t-test
## 
## data:  myboston$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

A) Confidence intervals calculated using the bootstrap estimate of \(SE\) and one sample t-Test are approximately same.

(e) Based on this data set, provide an estimate, \(\hat{\mu}_{median}\) for the median value of medv in the population.

median(myboston$medv)
## [1] 21.2

(f) We now would like to estimate the standard error of \(\hat{\mu}_{median}\).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 strap function
set.seed(123)
boot_med_fn <- function(data,index)
              return(median(data[index]))

boot(myboston$medv,boot_med_fn, R = 1000)
## 
## ORDINARY NONPARAMETRIC BOOTSTRAP
## 
## 
## Call:
## boot(data = myboston$medv, statistic = boot_med_fn, R = 1000)
## 
## 
## Bootstrap Statistics :
##     original  bias    std. error
## t1*     21.2 -0.0203   0.3676453

\(SE(\hat{\mu}_{median})\) using the bootstrap is 0.37(rounded to 2 decimals). This is small compared to the \(SE(\hat{\mu}_{mean})\). this indicates that the mediam estimate for the population is mostly accurate.

(g) Based on this data set, provide an estimate for the tenth percentile of medv in Boston suburbs. Call this quantity \(\hat{\mu}_{0.1})\).(You can use the quantile() function.)

#boot strap function

quantile(myboston$medv,0.1)
##   10% 
## 12.75

\(\hat{\mu}_{0.1}=12.75\)

(h) Use the bootstrap to estimate the standard error of \(\hat{\mu}_{0.1}\). Comment on your findings.

set.seed(1)
boot_10q_fn <- function(data,index)
              return(quantile(data[index],0.1))

boot(myboston$medv,boot_10q_fn, R = 1000)
## 
## ORDINARY NONPARAMETRIC BOOTSTRAP
## 
## 
## Call:
## boot(data = myboston$medv, statistic = boot_10q_fn, R = 1000)
## 
## 
## Bootstrap Statistics :
##     original  bias    std. error
## t1*    12.75  0.0339   0.4767526

\(Bootstrap\ \hat{\mu}_{0.1}=0.48\) this is relatively small considering the 10th percentile of 12.75.