set.seed(1)
model_a <- glm(default~income+balance, data = Default, family=binomial)
summary(model_a)
##
## 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
train_indices <- sample(1:nrow(Default), nrow(Default) / 2)
train <- Default[train_indices, ]
validation <- Default[-train_indices, ]
model_b <- glm(default ~ income + balance, data = train, family = "binomial")
probs <- predict(model_b, newdata = validation, type = "response")
preds <- ifelse(probs > 0.5, "Yes", "No")
mean(preds != validation$default)
## [1] 0.0254
set.seed(2)
train1 <- sample(1:nrow(Default), nrow(Default) / 2)
model1 <- glm(default ~ income + balance, data = Default[train1, ], family = "binomial")
preds1 <- ifelse(predict(model1, newdata = Default[-train1, ], type = "response") > 0.5, "Yes", "No")
error1 <- mean(preds1 != Default[-train1, ]$default)
set.seed(3)
train2 <- sample(1:nrow(Default), nrow(Default) / 2)
model2 <- glm(default ~ income + balance, data = Default[train2, ], family = "binomial")
preds2 <- ifelse(predict(model2, newdata = Default[-train2, ], type = "response") > 0.5, "Yes", "No")
error2 <- mean(preds2 != Default[-train2, ]$default)
set.seed(4)
train3 <- sample(1:nrow(Default), nrow(Default) / 2)
model3 <- glm(default ~ income + balance, data = Default[train3, ], family = "binomial")
preds3 <- ifelse(predict(model3, newdata = Default[-train3, ], type = "response") > 0.5, "Yes", "No")
error3 <- mean(preds3 != Default[-train3, ]$default)
error1
## [1] 0.0238
error2
## [1] 0.0264
error3
## [1] 0.0256
These validation errors represent the test error rates, i.e., the fraction of misclassified observations on the validation sets across three random splits.
The error rates are consistently low, ranging between 2.38% and 2.64%, which indicates that the logistic regression model using income and balance is performing quite well in predicting default.
The small variation across the three trials (about ±0.0013) suggests that the model’s performance is stable and not overly sensitive to how the data is split into training and validation sets.
This stability increases our confidence in the generalization ability of the model — i.e., its ability to perform well on unseen data.
In short, the model demonstrates reliable and robust classification performance with minimal variance across different validation splits.
set.seed(1)
train4 <- sample(1:nrow(Default), nrow(Default) / 2)
model_d <- glm(default ~ income + balance + student, data = Default[train4, ], family = "binomial")
preds_d <- ifelse(predict(model_d, newdata = Default[-train4, ], type = "response") > 0.5, "Yes", "No")
error_d <- mean(preds_d != Default[-train4, ]$default)
error_d
## [1] 0.026
Including the dummy variable for student did not lead to a meaningful reduction in the test error rate. In fact:
The test error with student (0.0260) is very similar to — and in one case slightly higher than — the errors from the model without it.
This suggests that student status does not provide much additional predictive power for default beyond what is already captured by income and balance.
It’s likely that the variable student is not strongly associated with default after controlling for income and balance. Any effect it has may already be accounted for by the other two predictors.
set.seed(1)
model_6a <- glm(default ~ income + balance, data = Default, family = "binomial")
summary(model_6a)$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
boot.fn <- function(data, index) {
fit <- glm(default ~ income + balance, data = data, family = "binomial", subset = index)
return(coef(fit)[c("income", "balance")])
}
library(boot)
set.seed(1)
boot_results <- boot(data = Default, statistic = boot.fn, R = 100)
boot_results
##
## ORDINARY NONPARAMETRIC BOOTSTRAP
##
##
## Call:
## boot(data = Default, statistic = boot.fn, R = 100)
##
##
## Bootstrap Statistics :
## original bias std. error
## t1* 2.080898e-05 -3.993598e-07 4.186088e-06
## t2* 5.647103e-03 -4.116657e-06 2.226242e-04
The standard errors obtained using the bootstrap method are very similar to those computed using the glm() function’s internal formula:
For income, the glm() SE is 4.99e-06, while the bootstrap SE is slightly smaller at 4.19e-06.
For balance, the glm() SE is 2.27e-04, and the bootstrap SE is 2.23e-04.
These results are consistent with what we would expect when the model assumptions (e.g., binomial distribution of the response, large enough sample size) hold reasonably well:
The small differences arise because the glm() standard errors are model-based and rely on theoretical asymptotic approximations.
The bootstrap standard errors are empirical, relying on resampling the observed data to directly estimate variability in the coefficients.
In this case, the close agreement between the two methods suggests that the assumptions used by glm() are appropriate, and the model is well-behaved.
data("Weekly")
str(Weekly)
## 'data.frame': 1089 obs. of 9 variables:
## $ Year : num 1990 1990 1990 1990 1990 1990 1990 1990 1990 1990 ...
## $ Lag1 : num 0.816 -0.27 -2.576 3.514 0.712 ...
## $ Lag2 : num 1.572 0.816 -0.27 -2.576 3.514 ...
## $ Lag3 : num -3.936 1.572 0.816 -0.27 -2.576 ...
## $ Lag4 : num -0.229 -3.936 1.572 0.816 -0.27 ...
## $ Lag5 : num -3.484 -0.229 -3.936 1.572 0.816 ...
## $ Volume : num 0.155 0.149 0.16 0.162 0.154 ...
## $ Today : num -0.27 -2.576 3.514 0.712 1.178 ...
## $ Direction: Factor w/ 2 levels "Down","Up": 1 1 2 2 2 1 2 2 2 1 ...
model_7a <- glm(Direction ~ Lag1 + Lag2, data = Weekly, family = "binomial")
summary(model_7a)
##
## Call:
## glm(formula = Direction ~ Lag1 + Lag2, family = "binomial", data = Weekly)
##
## Coefficients:
## Estimate Std. Error z value Pr(>|z|)
## (Intercept) 0.22122 0.06147 3.599 0.000319 ***
## Lag1 -0.03872 0.02622 -1.477 0.139672
## Lag2 0.06025 0.02655 2.270 0.023232 *
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## (Dispersion parameter for binomial family taken to be 1)
##
## Null deviance: 1496.2 on 1088 degrees of freedom
## Residual deviance: 1488.2 on 1086 degrees of freedom
## AIC: 1494.2
##
## Number of Fisher Scoring iterations: 4
model_7b <- glm(Direction ~ Lag1 + Lag2, data = Weekly[-1, ], family = "binomial")
summary(model_7b)
##
## Call:
## glm(formula = Direction ~ Lag1 + Lag2, family = "binomial", data = Weekly[-1,
## ])
##
## Coefficients:
## Estimate Std. Error z value Pr(>|z|)
## (Intercept) 0.22324 0.06150 3.630 0.000283 ***
## Lag1 -0.03843 0.02622 -1.466 0.142683
## Lag2 0.06085 0.02656 2.291 0.021971 *
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## (Dispersion parameter for binomial family taken to be 1)
##
## Null deviance: 1494.6 on 1087 degrees of freedom
## Residual deviance: 1486.5 on 1085 degrees of freedom
## AIC: 1492.5
##
## Number of Fisher Scoring iterations: 4
prob1 <- predict(model_7b, newdata = Weekly[1, ], type = "response")
pred1 <- ifelse(prob1 > 0.5, "Up", "Down")
actual1 <- Weekly$Direction[1]
pred1
## 1
## "Up"
actual1
## [1] Down
## Levels: Down Up
correct <- pred1 == actual1
correct
## [1] FALSE
The model incorrectly classified the first observation. It predicted the market would go up, but in reality, it went down.
n <- nrow(Weekly)
errors <- rep(NA, n)
for (i in 1:n) {
# i. Fit model
fit <- glm(Direction ~ Lag1 + Lag2, data = Weekly[-i, ], family = "binomial")
# ii. Posterior probability
prob <- predict(fit, newdata = Weekly[i, ], type = "response")
# iii. Classification
pred <- ifelse(prob > 0.5, "Up", "Down")
# iv. Record error
actual <- Weekly$Direction[i]
errors[i] <- ifelse(pred != actual, 1, 0)
}
loocv_error <- mean(errors)
loocv_error
## [1] 0.4499541
This means that the logistic regression model misclassified about 44.99% of the observations when evaluated using LOOCV, which tests each point using a model trained on all other points.
In practical terms: out of 1089 weekly market observations, the model predicted the direction of the market incorrectly about 490 times.
Is this good performance? Not really — for a binary classification task where the response is either Up or Down, a random guess would have an expected error rate of around 50%. Your model:
Achieved ~45% error, which is only slightly better than random guessing.
Shows that Lag1 and Lag2 alone do not provide strong predictive power for the market’s direction.
library(ISLR2)
library(boot)
data("Boston")
set.seed(1)
str(Boston)
## 'data.frame': 506 obs. of 13 variables:
## $ crim : num 0.00632 0.02731 0.02729 0.03237 0.06905 ...
## $ zn : num 18 0 0 0 0 0 12.5 12.5 12.5 12.5 ...
## $ indus : num 2.31 7.07 7.07 2.18 2.18 2.18 7.87 7.87 7.87 7.87 ...
## $ chas : int 0 0 0 0 0 0 0 0 0 0 ...
## $ nox : num 0.538 0.469 0.469 0.458 0.458 0.458 0.524 0.524 0.524 0.524 ...
## $ rm : num 6.58 6.42 7.18 7 7.15 ...
## $ age : num 65.2 78.9 61.1 45.8 54.2 58.7 66.6 96.1 100 85.9 ...
## $ dis : num 4.09 4.97 4.97 6.06 6.06 ...
## $ rad : int 1 2 2 3 3 3 5 5 5 5 ...
## $ tax : num 296 242 242 222 222 222 311 311 311 311 ...
## $ ptratio: num 15.3 17.8 17.8 18.7 18.7 18.7 15.2 15.2 15.2 15.2 ...
## $ lstat : num 4.98 9.14 4.03 2.94 5.33 ...
## $ medv : num 24 21.6 34.7 33.4 36.2 28.7 22.9 27.1 16.5 18.9 ...
mu_hat <- mean(Boston$medv)
mu_hat
## [1] 22.53281
se_mu_formula <- sd(Boston$medv) / sqrt(nrow(Boston))
se_mu_formula
## [1] 0.4088611
This tells us the typical variation we might expect in the sample mean if we repeatedly drew random samples of the same size from the population. If we were to repeatedly draw random samples of the same size from the Boston population and compute the mean medv (median house value) for each sample, the standard deviation of those means would be approximately 0.41.
It tells us how precise our estimate of the population mean is.
A smaller SE means more confidence in the sample mean being close to the true population mean. Since the standard deviation of medv is much larger (around 9.2), the SE is small in comparison, meaning the sample mean is a very stable estimator with relatively low variability.
boot.fn.mean <- function(data, index) {
return(mean(data[index]))
}
boot_mean <- boot(data = Boston$medv, statistic = 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_mu_bootstrap <- sd(boot_mean$t)
se_mu_bootstrap
## [1] 0.4106622
Comparison and Interpretation The two standard error estimates are extremely close — the difference is only about 0.0018.
This small difference indicates that the model-based formula in 9b is working very well, likely because:
The sample size (n = 506) is large enough for the Central Limit Theorem to hold.
The sample isn’t excessively skewed or heavy-tailed in a way that would mislead the parametric formula.
ci_boot <- c(mu_hat - 2 * se_mu_bootstrap, mu_hat + 2 * se_mu_bootstrap)
ci_boot
## [1] 21.71148 23.35413
t.test(Boston$medv)$conf.int
## [1] 21.72953 23.33608
## attr(,"conf.level")
## [1] 0.95
Comparison and Interpretation: The two intervals are very close — differing only slightly at both the lower and upper bounds (within ~0.02 units).
The bootstrap CI is very slightly wider than the one from t.test():
Bootstrap width: 23.35413 − 21.71148 = 1.64265
t.test() width: 23.33608 − 21.72953 = 1.60655
Both intervals capture the same central location, centered around the sample mean (~22.5).
The t-test CI is based on the assumption that the sample mean follows a t-distribution — which is appropriate when:
The sample size is moderate to large, and
The population distribution is reasonably normal (which seems to hold for medv).
The bootstrap CI is more flexible and data-driven, relying on resampling rather than theoretical distributions.
In this case, the similarity between the two CIs suggests that the theoretical assumptions underlying the t-test are valid, and the sampling distribution of the mean is approximately normal.
The slightly wider bootstrap CI reflects its non-parametric nature, which doesn’t assume a specific distribution and may be slightly more conservative in borderline cases.
mu_med_hat <- median(Boston$medv)
mu_med_hat
## [1] 21.2
boot.fn.median <- function(data, index) {
return(median(data[index]))
}
boot_median <- boot(data = Boston$medv, statistic = boot.fn.median, R = 1000)
se_median_bootstrap <- sd(boot_median$t)
se_median_bootstrap
## [1] 0.3770241
This result tells us that if we repeatedly drew random samples (with replacement) from the Boston housing data and computed the median of medv each time, the standard deviation of those medians would be approximately 0.377.
The sample median is a stable and reliable estimator of the population median, with moderate variability — slightly less than half a thousand dollars.
mu_p10_hat <- quantile(Boston$medv, 0.1)
mu_p10_hat
## 10%
## 12.75
boot.fn.p10 <- function(data, index) {
return(quantile(data[index], 0.1))
}
boot_p10 <- boot(data = Boston$medv, statistic = boot.fn.p10, R = 1000)
se_p10_bootstrap <- sd(boot_p10$t)
se_p10_bootstrap
## [1] 0.4925766
Interpretation: This value means that if we were to repeatedly sample (with replacement) from the Boston housing dataset and calculate the 10th percentile each time, the standard deviation of those estimates would be about 0.493 (in thousands of dollars).
The 10th percentile estimate is subject to more variability than the mean or median, with a standard error nearly 0.5.
The SE of ≈ 0.493 suggests that the estimate of the 10th percentile is less stable than the mean or median.
However, using the bootstrap provides a reliable, distribution-free way to assess its uncertainty.
This kind of analysis is especially important when dealing with inequality, low-income housing, or affordable housing analysis, where lower-percentile values (like the 10th percentile of medv) may drive decision-making.