Q)3. We now review k-fold cross-validation.

(a) Explain how k-fold cross-validation is implemented. It involves randomly dividing the set of observations into k groups, or folds, of approximately equal size. The first fold is treated as a validation set, and the method is fit on the remaining k − 1 folds. The mean squared error, MSE1, 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 error,. The k-fold CV estimate is computed by averaging these values

(b) What are the advantages and disadvantages of k-fold crossvalidation relative to: i. The validation set approach? The variability is typically much lower than the variability in the test error estimates that results from the validation set approach

ii. LOOCV? The most obvious advantage is computational. performing LOOCV may pose computational problems, especially if n is extremely large. In contrast, performing 10-fold CV requires fitting the learning procedure only ten times, which may be much more feasible.

==============================================================

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.

library(ISLR2) #loading necessary library
set.seed(10)   #ensuring duplicacy
#create vector of random 196 random row numbers to help split training and test datasets
data(Default)

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

# Make sure the response variable is a factor
Default$default <- as.factor(Default$default)

# Fit logistic regression using income and balance
glm.fit <- glm(default ~ income + balance, data = Default, family = binomial)
summary(glm.fit)
## 
## 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

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

  split_data=sample(10000,5000) #splitting data into training and validation data
train_data <- Default[split_data, ]
valid_data <- Default[-split_data, ]

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

glm.fit <- glm(default ~ income + balance, data = train_data, 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.

glm.probs <- predict(glm.fit, newdata = valid_data, type = "response")
glm.pred <- ifelse(glm.probs > 0.5, "Yes", "No")

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

actual <- valid_data$default
mean(glm.pred != actual)
## [1] 0.0288

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

set.seed(3)
error1 <- {
  fit <- glm(default ~ income + balance, data = Default, subset = split_data, family = binomial)
  probs <- predict(fit, newdata = Default[-split_data, ], type = "response")
  pred <- ifelse(probs > 0.5, "Yes", "No")
  mean(pred != Default[-split_data, "default"])
}

set.seed(7)
error2 <- {
  fit <- glm(default ~ income + balance, data = Default, subset = split_data, family = binomial)
  probs <- predict(fit, newdata = Default[-split_data, ], type = "response")
  pred <- ifelse(probs > 0.5, "Yes", "No")
  mean(pred != Default[-split_data, "default"])
}

set.seed(12)
error3 <- {
  fit <- glm(default ~ income + balance, data = Default, subset = split_data, family = binomial)
  probs <- predict(fit, newdata = Default[-split_data, ], type = "response")
  pred <- ifelse(probs > 0.5, "Yes", "No")
  mean(pred != Default[-split_data, "default"])
}

error1; error2; error3
## [1] 0.0288
## [1] 0.0288
## [1] 0.0288

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

# Fit model with student included
glm.fit2 <- glm(default ~ income + balance + student, data = Default, subset = split_data, family = binomial)

# Predict on validation set
probs2 <- predict(glm.fit2, newdata = Default[-split_data, ], type = "response")
pred2 <- ifelse(probs2 > 0.5, "Yes", "No")

# Compute test error
error_with_student <- mean(pred2 != Default[-split_data, "default"])
error_with_student
## [1] 0.0286
#student improves the 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.

library(ISLR2)
set.seed(15)
data(Default)

# Ensure response is a factor
Default$default <- as.factor(Default$default)

# Fitting logistic regression
glm.fit <- glm(default ~ income + balance, data = Default, family = binomial)

# Show estimated standard errors
summary(glm.fit)$coefficients
##                  Estimate   Std. Error    z value      Pr(>|z|)
## (Intercept) -1.154047e+01 4.347564e-01 -26.544680 2.958355e-155
## 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.

# Loading required library
library(boot)

# creating the Bootstrap function
boot.fn <- function(data, index) {
  fit <- glm(default ~ income + balance, data = data, family = binomial, subset = index)
  return(coef(fit)[2:3])  # Only income and balance
}

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

# Apply bootstrap with 1000 resamples
set.seed(2)
boot.results <- boot(Default, boot.fn, R = 1000)

# View bootstrap standard errors
boot.results
## 
## ORDINARY NONPARAMETRIC BOOTSTRAP
## 
## 
## Call:
## boot(data = Default, statistic = boot.fn, R = 1000)
## 
## 
## Bootstrap Statistics :
##         original        bias     std. error
## t1* 2.080898e-05 -4.605498e-07 4.924565e-06
## t2* 5.647103e-03  3.048004e-05 2.228767e-04

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

# From glm
glm.se <- summary(glm.fit)$coefficients[2:3, 2]  # Std. Error for income & balance

# From bootstrap
boot.se <- boot.results$t0  # Original estimates
boot.std.errs <- apply(boot.results$t, 2, sd)  # Bootstrap SEs

# Combine results
se.compare <- data.frame(
  Coefficient = c("income", "balance"),
  SE_glm = glm.se,
  SE_bootstrap = boot.std.errs
)

se.compare
##         Coefficient       SE_glm SE_bootstrap
## income       income 4.985167e-06 4.924565e-06
## balance     balance 2.273731e-04 2.228767e-04
#The standard errors estimated using the bootstrap are nearly identical to those computed by the glm() function. 
#This close agreement confirms that the built-in standard error formula used by logistic regression is reliable in this case. Both income and balance have stable coefficient estimates with low variability, suggesting a strong and consistent relationship between these predictors and the probability of default.###

==============================================================

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

#Loading required data
library(ISLR2)
library(boot)

data(Boston)

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

mu_hat <- mean(Boston$medv)
mu_hat
## [1] 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.

n <- nrow(Boston)
se_formula <- sd(Boston$medv) / sqrt(n)
se_formula
## [1] 0.4088611
#This value estimates the expected variability of the sample mean across repeated samples from the population.

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

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

set.seed(1)
boot.mean <- boot(Boston$medv, boot.fn.mean, R = 1000)
boot.mean
## 
## ORDINARY NONPARAMETRIC BOOTSTRAP
## 
## 
## Call:
## boot(data = Boston$medv, statistic = boot.fn.mean, R = 1000)
## 
## 
## Bootstrap Statistics :
##     original      bias    std. error
## t1* 22.53281 0.007650791   0.4106622
se_bootstrap <- sd(boot.mean$t)
se_bootstrap
## [1] 0.4106622
#The results are very close, confirming the validity of the formula 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(ˆμ)].

# Bootstrap 95% CI using [μ̂ − 2SE, μ̂ + 2SE]
ci_bootstrap <- c(mu_hat - 2 * se_bootstrap, mu_hat + 2 * se_bootstrap)
ci_bootstrap
## [1] 21.71148 23.35413
#Comparing with t test
t.test(Boston$medv)$conf.int
## [1] 21.72953 23.33608
## attr(,"conf.level")
## [1] 0.95
#Both confidence intervals are nearly identical, which suggests that the normal approximation used in the t-test is reasonable for the sample size.#

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

mu_med <- median(Boston$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.median <- function(data, index) {
  return(median(data[index]))
}

set.seed(2)
boot.median <- boot(Boston$medv, boot.fn.median, R = 1000)

# Bootstrap SE
se_median <- sd(boot.median$t)
se_median
## [1] 0.3879954
#The bootstrap gives us a reliable estimate of the median's variability. The standard error is slightly smaller than that of the mean, consistent with the robustness of the median to outliers.

(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_0.1 <- quantile(Boston$medv, 0.1)
mu_0.1
##   10% 
## 12.75

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

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

set.seed(3)
boot.quantile <- boot(Boston$medv, boot.fn.quantile, R = 1000)

# Bootstrap SE
se_quantile <- sd(boot.quantile$t)
se_quantile
## [1] 0.4873263
#The standard error for the 10th percentile is higher than that of the mean or median, which reflects the increased uncertainty in estimating tail values in the distribution.