Problem # 3

Part a:

Explain how k-fold cross-validation is implemented.

In k-fold cross-validation, the dataset is randomly divided into k approximately equal-sized subsets or “folds”. The model is trained and validated k times. In each iteration, one fold is held out as the validation set, and the remaining k−1 folds are used as the training set. The validation error is calculated for each fold, and the final estimate of test error is the average of these k validation errors. This approach ensures that every observation is used for both training and validation exactly once.

Part b:

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

  1. The validation set approach:
  1. Provides a more reliable and stable estimate of test error because it averages across multiple splits.

  2. Makes better use of data, as every point gets to be in a validation set and training set.

  1. More computationally expensive than a single validation set split, especially for large values of k.
  1. LOOCV (Leave-One-Out Cross-Validation):
  1. Less computationally intensive than LOOCV (which requires n iterations, one for each observation).

  2. Usually provides a better bias-variance tradeoff: LOOCV can have high variance, while k-fold CV (with k = 5 or 10) tends to have lower variance.

  1. LOOCV often gives an almost unbiased estimate of the test error, while k-fold CV can be slightly biased depending on k.

Problem # 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.

part a

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

# Set seed for reproducibility
library(ISLR) 
## Warning: package 'ISLR' was built under R version 4.4.2
data(Default)
set.seed(23)
d1 = Default
glm1 = glm(default ~ income + balance, data = d1, family = "binomial")
summary(glm1)
## 
## Call:
## glm(formula = default ~ income + balance, family = "binomial", 
##     data = d1)
## 
## 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

part 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(23)
index <- sample(nrow(d1),0.7*nrow(d1),replace = FALSE) 
train_d1 <- d1[index, ]
val_d1 <- d1[-index, ]

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

# Fit logistic regression using income and balance to predict default
set.seed(23)
glm2 = glm(default ~ income + balance, data = train_d1, family = "binomial")
summary(glm2)
## 
## Call:
## glm(formula = default ~ income + balance, family = "binomial", 
##     data = train_d1)
## 
## Coefficients:
##               Estimate Std. Error z value Pr(>|z|)    
## (Intercept) -1.189e+01  5.410e-01 -21.975  < 2e-16 ***
## income       2.798e-05  6.086e-06   4.597 4.28e-06 ***
## balance      5.686e-03  2.794e-04  20.351  < 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: 1976.0  on 6999  degrees of freedom
## Residual deviance: 1067.3  on 6997  degrees of freedom
## AIC: 1073.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.

d1_prob = predict(glm2, val_d1, type = "response")
d1_pred = rep("No", nrow(val_d1))
d1_pred[d1_prob > .5] = "Yes"

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

mean(d1_pred!=val_d1$default)
## [1] 0.02733333

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

library(ISLR)

# Function to perform one validation run
run_validation <- function(seed) {
  set.seed(seed)
  sample_size <- nrow(Default)
  train_indices <- sample(1:sample_size, size = sample_size / 2)
  
  train_data <- Default[train_indices, ]
  validation_data <- Default[-train_indices, ]
  
  model <- glm(default ~ income + balance, data = train_data, family = "binomial")
  probs <- predict(model, newdata = validation_data, type = "response")
  predicted <- ifelse(probs > 0.5, "Yes", "No")
  actual <- validation_data$default
  
  mean(predicted != actual)
}

# Run the validation three times with different seeds
error1 <- run_validation(1)
error2 <- run_validation(2)
error3 <- run_validation(3)

# Print results
print(paste("Validation Error 1:", round(error1, 4)))
## [1] "Validation Error 1: 0.0254"
print(paste("Validation Error 2:", round(error2, 4)))
## [1] "Validation Error 2: 0.0238"
print(paste("Validation Error 3:", round(error3, 4)))
## [1] "Validation Error 3: 0.0264"

Comment on the result:

The validation errors across the three different splits are quite similar, ranging from 0.0238 to 0.0264. This consistency suggests that the logistic regression model performs reliably, and the validation set approach provides a reasonably stable estimate of test error despite some minor variation due to random splitting.

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

library(ISLR)

# Function to perform validation with 'student' included
run_validation_with_student <- function(seed) {
  set.seed(seed)
  sample_size <- nrow(Default)
  train_indices <- sample(1:sample_size, size = sample_size / 2)
  
  train_data <- Default[train_indices, ]
  validation_data <- Default[-train_indices, ]
  
  model <- glm(default ~ income + balance + student, data = train_data, family = "binomial")
  probs <- predict(model, newdata = validation_data, type = "response")
  predicted <- ifelse(probs > 0.5, "Yes", "No")
  actual <- validation_data$default
  
  mean(predicted != actual)
}

# Run the validation three times
error1 <- run_validation_with_student(1)
error2 <- run_validation_with_student(2)
error3 <- run_validation_with_student(3)

# Print results
print(paste("Validation Error with student 1:", round(error1, 4)))
## [1] "Validation Error with student 1: 0.026"
print(paste("Validation Error with student 2:", round(error2, 4)))
## [1] "Validation Error with student 2: 0.0246"
print(paste("Validation Error with student 3:", round(error3, 4)))
## [1] "Validation Error with student 3: 0.0272"

Comment on the result: The validation errors with the student variable are very similar to those without it, ranging from 0.0246 to 0.0272. This suggests that including the student variable does not significantly reduce the test error rate, indicating it adds little predictive value beyond income and balance.

Problem #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.

  1. 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.
# Load the ISLR package
library(ISLR)

# Fit logistic regression model
model <- glm(default ~ income + balance, data = Default, family = "binomial")

# View summary to get standard errors
summary(model)
## 
## Call:
## glm(formula = default ~ income + balance, family = "binomial", 
##     data = Default)
## 
## 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

Interpretation:

The standard error for income is 4.985e-06, and for balance is 2.274e-04, indicating that the estimate for balance is more precise and has a stronger influence on predicting default.

part 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 = 1:nrow(data)) {
  coef(glm(default ~ income + balance, data = data, subset = index, family = "binomial"))[-1]
}

boot.fn(Default)
##       income      balance 
## 2.080898e-05 5.647103e-03

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

# Load the boot package
library(boot)

# Run the bootstrap with 1000 replications
set.seed(123)
bootstrap_results <- boot(data = Default, statistic = boot.fn, R = 1000)

# View standard errors
print(bootstrap_results)
## 
## ORDINARY NONPARAMETRIC BOOTSTRAP
## 
## 
## Call:
## boot(data = Default, statistic = boot.fn, R = 1000)
## 
## 
## Bootstrap Statistics :
##         original       bias     std. error
## t1* 2.080898e-05 1.582518e-07 4.729534e-06
## t2* 5.647103e-03 1.296980e-05 2.217214e-04

The Estimated std error is for income is 4.729e-06 and for balance is 2.217e-04.

Part d

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

Using the glm() function, the ESE for income is 4.985e-06 and for balance is 2.274e-04. Using the bootstrap function function, the ESE for income is income is 4.729e-06 and for balance is 2.217e-04. Standard error was lower when using bootstrap.

Problem # 9

We will now consider the Boston housing data set, from the ISLR2 library.

Part a

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

# Load the ISLR2 package
library(ISLR2)
## Warning: package 'ISLR2' was built under R version 4.4.2
## 
## Attaching package: 'ISLR2'
## The following objects are masked from 'package:ISLR':
## 
##     Auto, Credit
# Estimate the population mean of medv
mu_hat <- mean(Boston$medv)

# Print the result
print(paste("Estimated population mean of medv (mû):", round(mu_hat, 4)))
## [1] "Estimated population mean of medv (mû): 22.5328"

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

# Standard deviation of medv
std_dev <- sd(Boston$medv)

# Sample size
n <- nrow(Boston)

# Standard error of the mean
se_mu_hat <- std_dev / sqrt(n)

# Print result
print(paste("Standard Error of mû:", round(se_mu_hat, 4)))
## [1] "Standard Error of mû: 0.4089"

Part c

Now estimate the standard error of ˆμ using the bootstrap. How does this compare to your answer from (b)?

boot.fn <- function(vector, index) {
  mean(vector[index])
}

set.seed(66, sample.kind = "Rounding")
## Warning in set.seed(66, sample.kind = "Rounding"): non-uniform 'Rounding'
## sampler used
(boot_results <- boot(data = Boston$medv, statistic = boot.fn, R = 1000))
## 
## ORDINARY NONPARAMETRIC BOOTSTRAP
## 
## 
## Call:
## boot(data = Boston$medv, statistic = boot.fn, R = 1000)
## 
## 
## Bootstrap Statistics :
##     original    bias    std. error
## t1* 22.53281 0.0116587   0.4081538

The standard error from part (b) (using the formula) was 0.4089, while the bootstrap estimate from part (c) is 0.4081. These values are very close, indicating that both methods provide consistent estimates of the standard error. This confirms the reliability of both the theoretical and resampling approaches for estimating uncertainty in the sample mean.

Part 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(ˆμ)].

# Use previous results
mu_hat <- mean(Boston$medv)
se_boot <- 0.4046  # From part (c)

# Bootstrap-based 95% CI
ci_lower <- mu_hat - 2 * se_boot
ci_upper <- mu_hat + 2 * se_boot
cat("Bootstrap 95% CI for mean of medv:", round(ci_lower, 4), "to", round(ci_upper, 4), "\n")
## Bootstrap 95% CI for mean of medv: 21.7236 to 23.342
# Compare with t.test
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 bootstrap 95% CI is (21.7236, 23.342) and the t-test CI is (21.7295, 23.3361). These intervals are nearly identical, showing strong agreement between the bootstrap method and the theoretical t-distribution, reinforcing the reliability of both approaches for estimating confidence intervals of the mean.

Part e

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

# Estimate of the population median of medv
mu_med <- median(Boston$medv)

# Print result
print(paste("Estimated population median of medv (mû_med):", mu_med))
## [1] "Estimated population median of medv (mû_med): 21.2"

Part 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 <- function(vector, index) {
  median(vector[index])
}

set.seed(77, sample.kind = "Rounding")
## Warning in set.seed(77, sample.kind = "Rounding"): non-uniform 'Rounding'
## sampler used
(boot_results <- boot(data = Boston$medv, statistic = boot.fn, R = 1000))
## 
## ORDINARY NONPARAMETRIC BOOTSTRAP
## 
## 
## Call:
## boot(data = Boston$medv, statistic = boot.fn, R = 1000)
## 
## 
## Bootstrap Statistics :
##     original  bias    std. error
## t1*     21.2  0.0094   0.3700318

The bootstrap standard error of the median is 0.3700, which is relatively small. This indicates that the sample median of medv is a stable and reliable estimate of the population median, even though no closed-form formula exists for its standard error. Bootstrap proves useful in quantifying its variability.

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

# Estimate the 10th percentile (μ̂_0.1) of medv
quantile(Boston$medv, 0.1)
##   10% 
## 12.75

Part h

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

boot.fn <- function(vector, index) {
  quantile(vector[index], 0.1)
}

set.seed(77, sample.kind = "Rounding")
## Warning in set.seed(77, sample.kind = "Rounding"): non-uniform 'Rounding'
## sampler used
(boot_results <- boot(data = Boston$medv, statistic = boot.fn, R = 1000))
## 
## ORDINARY NONPARAMETRIC BOOTSTRAP
## 
## 
## Call:
## boot(data = Boston$medv, statistic = boot.fn, R = 1000)
## 
## 
## Bootstrap Statistics :
##     original  bias    std. error
## t1*    12.75 0.02085    0.488873

The standard error is slightly larger relative to μ^0.1, but it is still small.