set.seed(577)
n <- 100; p <- 10
X <- matrix(rnorm(n * p), n, p)
beta_true <- c(3, 1.5, 0, 0, 2, rep(0, 5))
y <- X %*% beta_true + rnorm(n)
# Point estimate: Ridge coefficient for X1
fit_full <- glmnet(X, y, alpha = 0, lambda = 0.5)
theta_hat <- as.vector(coef(fit_full))[-1][1] # X1 coefficient
# Bootstrap
B <- 2000
boot_theta <- numeric(B)
for (b in 1:B) {
idx <- sample(1:n, n, replace = TRUE)
fit_b <- glmnet(X[idx, ], y[idx], alpha = 0, lambda = 0.5)
boot_theta[b] <- as.vector(coef(fit_b))[-1][1]
}
# Three types of 95% CIs
alpha <- 0.05
q_lo <- quantile(boot_theta, alpha / 2)
q_hi <- quantile(boot_theta, 1 - alpha / 2)
ci_percentile <- c(q_lo, q_hi)
ci_basic <- c(2 * theta_hat - q_hi, 2 * theta_hat - q_lo)
ci_df <- tibble(
Method = c("Percentile", "Basic (Pivotal)"),
lo = c(ci_percentile[1], ci_basic[1]),
hi = c(ci_percentile[2], ci_basic[2]),
ypos = c(-0.15, 0)
)
p_ci <- ggplot() +
geom_histogram(aes(x = boot_theta, y = after_stat(density)),
bins = 50, fill = colors["blue"], alpha = 0.5, color = "white") +
geom_vline(xintercept = theta_hat, linewidth = 1, color = "black") +
geom_vline(xintercept = 3, linewidth = 1, linetype = "dashed", color = colors["red"]) +
geom_segment(data = ci_df, aes(x = lo, xend = hi, y = ypos, yend = ypos, color = Method),
linewidth = 2) +
geom_point(data = ci_df, aes(x = lo, y = ypos, color = Method), size = 3) +
geom_point(data = ci_df, aes(x = hi, y = ypos, color = Method), size = 3) +
scale_color_manual(values = c("Percentile" = colors["green"], "Basic (Pivotal)" = colors["orange"])) +
annotate("text", x = 3.05, y = 2.5, label = "'True' ~ beta[1] == 3",
parse = TRUE, color = colors["red"], hjust = 0, size = 4.5) +
annotate("text", x = theta_hat + 0.05, y = 2.8,
label = paste0("hat(theta) == ", round(theta_hat, 2)),
parse = TRUE, hjust = 0, size = 4.5) +
labs(title = "Bootstrap Confidence Intervals for Ridge Coefficient (X1)",
subtitle = "2000 bootstrap replicates | lambda = 0.5 | 95% confidence level",
x = "Coefficient Value", y = "Density") +
theme_bw(base_size = 16) +
theme(legend.position = "bottom")
ggsave(file.path(fig_dir, "06_bootstrap_ci.png"), p_ci, width = 10, height = 5, dpi = 150)
p_ci