Question 3

(a) Explain how k-fold cross-validation is implemented.

This method is implemented by taking the observations and randomly dividing them into a k number of groups or folds of roughly equal size. The remaining k-1 folds can then be fit using this method.

(b) What are the advantages and disadvantages of k-fold cross validation relative to: i. The validation set approach? ii. LOOCV?

  1. The validation set approach big advantage is that it is relatively easy to understand and has easy interpretation.This is because we are only training the data into two groups, so the complexity stays rather minimal. However a big disadvantage is that the error rate can fluctuate and have a high variability based on what variables are left in the model or training data sets.

  2. the LOOCV method is a unique case of the k-fold cross-validation method. Its advantage is that while it also has a high variance, it does tend to have a low bias. However this method is more complex since the model may have to fit a numerous amount of times.

Question 5

(a) Fit a logistic regression model that uses income and balance to predict default.

library(ISLR)
summary(Default)
##  default    student       balance           income     
##  No :9667   No :7056   Min.   :   0.0   Min.   :  772  
##  Yes: 333   Yes:2944   1st Qu.: 481.7   1st Qu.:21340  
##                        Median : 823.6   Median :34553  
##                        Mean   : 835.4   Mean   :33517  
##                        3rd Qu.:1166.3   3rd Qu.:43808  
##                        Max.   :2654.3   Max.   :73554
attach(Default)
set.seed(1)
Q5.glm.fit = glm(default ~ income + balance, data = Default, family = binomial)
Q5.glm.fit
## 
## Call:  glm(formula = default ~ income + balance, family = binomial, 
##     data = Default)
## 
## Coefficients:
## (Intercept)       income      balance  
##  -1.154e+01    2.081e-05    5.647e-03  
## 
## Degrees of Freedom: 9999 Total (i.e. Null);  9997 Residual
## Null Deviance:       2921 
## Residual Deviance: 1579  AIC: 1585

(b) Using the validation set approach, estimate the test error of this model. In order to do this, you must perform the following steps:

  1. Split the sample set into a training set and a validation set

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

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

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

Q5.B = function() {
train = sample(dim(Default)[1], dim(Default)[1]/2)
Q5.glm.fit = glm(default ~ income + balance, data = Default, family = binomial, subset = train)
Q5.glm.pred = rep("No", dim(Default)[1]/2)
Q5.glm.prob = predict(Q5.glm.fit, Default[-train, ], type = "response")
Q5.glm.pred[Q5.glm.prob > 0.5] = "Yes"
return(mean(Q5.glm.pred != Default[-train, ]$default)) }
Q5.B()
## [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.

Q5.B()
## [1] 0.0274
Q5.B()
## [1] 0.0244
Q5.B()
## [1] 0.0244

If we re-run our model we see that there is little change in the error rates.

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

train = sample(dim(Default)[1], dim(Default)[1]/2)
Q5.glm.fit = glm(default ~ income + balance + student, data = Default, family = binomial, subset = train)
Q5.glm.pred = rep("No", dim(Default)[1]/2)
Q5.glm.probs = predict(Q5.glm.fit, Default[-train, ], type = "response")
Q5.glm.pred[Q5.glm.probs > 0.5] = "Yes"
mean(Q5.glm.pred != Default[-train, ]$default)
## [1] 0.0278

We can see from this result that adding the additional student variable does not appear to have a significant effect on the test error rate.

Question 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(2)
Q6.glm.fit = glm(default ~ income + balance, data = Default, family = binomial)
summary(Q6.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) 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.

(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.fn = function(data, index){return(coef(glm(default ~ income + balance, data = data, family = binomial, subset = index)))}
library(boot)
boot(Default, boot.fn, 50)
## 
## ORDINARY NONPARAMETRIC BOOTSTRAP
## 
## 
## Call:
## boot(data = Default, statistic = boot.fn, R = 50)
## 
## 
## Bootstrap Statistics :
##          original        bias     std. error
## t1* -1.154047e+01 -3.302673e-02 4.929605e-01
## t2*  2.080898e-05 -2.407946e-07 5.334622e-06
## t3*  5.647103e-03  2.857492e-05 2.782918e-04

(d) Comment on the estimated standard errors obtained using the glm() function and using your bootstrap function.

After running both methods we obtain similar results for both of the estimates.

Question 9

(a) Based on this data set, provide an estimate for the population mean of medv. Call this estimate ˆμ.

library(MASS)
muhat <- mean(Boston$medv)
muhat
## [1] 22.53281

(b) Provide an estimate of the standard error of ˆμ. Interpret this result.

n <- length(Boston$medv)
s <- sd(Boston$medv)
se <- s/sqrt(n)
se
## [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)
Bootstrap <- 5000
mu.s <- numeric(Bootstrap)
for (i in 1:Bootstrap){
s <- sample(Boston$medv, size = n, replace = TRUE)
mu.s[1] <- mean(s)
}
sd(mu.s)
## [1] 0.3306884

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

ucl<-muhat+2*sd(mu.s)
lcl<-muhat-2*sd(mu.s)
print(paste("95% confidence interval for mean of medv is [",round(lcl,4),",",round(ucl,4),"]" ))
## [1] "95% confidence interval for mean of medv is [ 21.8714 , 23.1942 ]"
cl<-t.test(Boston$medv)
print(data.frame(cl$conf.int))
##   cl.conf.int
## 1    21.72953
## 2    23.33608

(e) Based on this data set, provide an estimate, ˆμmed, for the median value of medv in the population.

medhat<-median(Boston$medv)
medhat
## [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)
B<-5000
med.s<-numeric(B)
for (i in 1:B){
s<-sample(Boston$medv,size=n,replace=TRUE)
med.s[i]<-median(s)
}
sd(med.s)
## [1] 0.3771157

This distribution of medians has a SD of0.3771.

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

tenphat<-quantile(Boston$medv,p=0.1)
tenphat
##   10% 
## 12.75

(h) Use the bootstrap to estimate the standard error of ˆμ0.1. Comment on your findings.

set.seed(1)
B<-5000
tenpstar<-numeric(B)
for (i in 1:B){
s<-sample(Boston$medv,size=n,replace=TRUE)
tenpstar[i]<-quantile(s,p=0.1)
}
sd(tenpstar)
## [1] 0.4948251