# Elastic net and cross-validation
# https://tidyecology.com/posts/elastic-net-and-cross-validation/
#
# The R code of this Tidy Ecology tutorial, chunk by chunk, in the order of the post.
# Run it top to bottom in a fresh R session. Code the post shows but does not run
# is commented out. The prose, and the numbers it quotes, are in the post itself.
# Post last modified: 2026-10-14

## ---- setup ----
library(ggplot2)

te_ink <- "#275139"; te_naive <- "#b5482a"; te_truth <- "#565656"
theme_te <- function(base_size = 12) {
  theme_minimal(base_size = base_size, base_family = "sans") +
    theme(
          plot.background  = element_rect(fill = "#f5f4ee", colour = NA),
          panel.background = element_rect(fill = "#f5f4ee", colour = NA),
          plot.title = element_text(colour = te_ink, face = "bold"),
          plot.subtitle = element_text(colour = "#3f3f3f"),
          axis.title = element_text(colour = te_ink),
          panel.grid.minor = element_blank(),
          panel.grid.major = element_line(colour = "#e4dfd4", linewidth = 0.35),
          legend.position = "top")
}
theme_set(theme_te())

set.seed(4212)
n <- 60; p <- 30; ntest <- 8000; sigma <- 1.4
gen_X <- function(n) {
  f <- matrix(rnorm(n * 4), n, 4); M <- matrix(rnorm(n * p), n, p)
  M[, 1:6]   <- M[, 1:6]   * sqrt(1 - 0.9^2) + f[, 1] * 0.9   # the correlated group
  M[, 7:16]  <- M[, 7:16]  * sqrt(1 - 0.5^2) + f[, 2] * 0.5
  M[, 17:26] <- M[, 17:26] * sqrt(1 - 0.5^2) + f[, 3] * 0.5
  M[, 27:30] <- M[, 27:30] * sqrt(1 - 0.4^2) + f[, 4] * 0.4
  colnames(M) <- paste0("x", 1:p); M
}
X <- gen_X(n)
grp <- 1:6
beta_true <- numeric(p)
beta_true[grp] <- 0.45                          # six correlated members share the signal
beta_true[c(10, 20, 28)] <- c(0.8, 0.7, 0.6)    # isolated singletons
k_true <- sum(beta_true != 0)
y  <- as.numeric(X %*% beta_true) + rnorm(n, 0, sigma)
Xt <- gen_X(ntest); yt <- as.numeric(Xt %*% beta_true) + rnorm(ntest, 0, sigma)

## ---- fit ----
soft <- function(z, g) sign(z) * pmax(abs(z) - g, 0)
en_fit_cov <- function(G, xy, lambda, alpha, b0 = NULL, maxit = 5000, tol = 1e-7) {
  p <- length(xy); b <- if (is.null(b0)) numeric(p) else b0
  denom <- 1 + lambda * (1 - alpha); g <- lambda * alpha
  cvec <- xy - as.numeric(G %*% b)           # c_j = X'y/n - (Gb)_j, kept in step with b
  for (it in 1:maxit) {
    dmax <- 0
    for (j in 1:p) {
      zj <- cvec[j] + b[j]
      bn <- soft(zj, g) / denom; d <- bn - b[j]
      if (d != 0) { cvec <- cvec - G[, j] * d; b[j] <- bn }
      dmax <- max(dmax, abs(d))
    }
    if (dmax < tol) break
  }
  b
}
gram_of <- function(Xs) crossprod(Xs) / nrow(Xs)
xy_of   <- function(Xs, yc) as.numeric(crossprod(Xs, yc)) / nrow(Xs)
en_path_cov <- function(G, xy, lams, alpha) {
  P <- matrix(0, length(lams), ncol(G)); b <- NULL
  for (i in seq_along(lams)) { b <- en_fit_cov(G, xy, lams[i], alpha, b0 = b); P[i, ] <- b }
  P
}
standardise <- function(X) {
  xm <- colMeans(X); Xc <- sweep(X, 2, xm); xn <- sqrt(colMeans(Xc^2))
  list(Xs = sweep(Xc, 2, xn, "/"), xm = xm, xn = xn)
}
back <- function(bs, xn, xm, ym) { bo <- bs / xn; list(bo = bo, it = ym - sum(bo * xm)) }
lam_max_a <- function(Xs, yc, alpha) max(abs(colMeans(Xs * yc))) / max(alpha, 0.05)

cc <- cor(X); gcor <- cc[grp, grp]; group_cor <- mean(gcor[upper.tri(gcor)])
st <- standardise(X); ym <- mean(y); yc <- y - ym
G0 <- gram_of(st$Xs); xy0 <- xy_of(st$Xs, yc)

## ---- cv ----
alphas <- c(0.1, 0.25, 0.5, 0.75, 1.0)
nl <- 45
set.seed(4312); K <- 10; fold <- sample(rep(1:K, length.out = n))
folds <- lapply(1:K, function(kk) {
  tr <- fold != kk; s <- standardise(X[tr, ]); yct <- y[tr] - mean(y[tr])
  list(tr = tr, s = s, G = gram_of(s$Xs), xy = xy_of(s$Xs, yct), ytr = mean(y[tr]))
})
cv_alpha <- function(alpha) {
  lmax <- lam_max_a(st$Xs, yc, alpha)
  lams <- exp(seq(log(lmax), log(lmax * 1e-3), length.out = nl))
  E <- matrix(NA, K, nl)
  for (kk in 1:K) {
    fk <- folds[[kk]]; te <- !fk$tr
    Ptr <- en_path_cov(fk$G, fk$xy, lams, alpha)
    for (i in 1:nl) {
      q <- back(Ptr[i, ], fk$s$xn, fk$s$xm, fk$ytr)
      E[kk, i] <- mean((y[te] - (as.numeric(X[te, , drop = FALSE] %*% q$bo) + q$it))^2)
    }
  }
  cvm <- colMeans(E)
  data.frame(alpha = alpha, lam = lams, rmse = sqrt(cvm), cvm = cvm)
}
cvgrid <- do.call(rbind, lapply(alphas, cv_alpha))
best <- cvgrid[which.min(cvgrid$cvm), ]
amins <- do.call(rbind, lapply(split(cvgrid, cvgrid$alpha), function(d) d[which.min(d$cvm), ]))
amins <- amins[order(amins$alpha), ]
alpha_hat <- best$alpha; lam_hat <- best$lam
lam_las   <- amins$lam[amins$alpha == 1.0]
cv_spread <- max(amins$rmse) - min(amins$rmse)

## ---- fig-cv ----
cvgrid$alpha_f <- factor(sprintf("%.2f", cvgrid$alpha))
pal <- c("0.10" = "#c7bda8", "0.25" = "#9bbf8a", "0.50" = te_ink, "0.75" = "#c98b3a", "1.00" = te_naive)
ggplot(cvgrid, aes(log10(lam), rmse, colour = alpha_f)) +
  geom_line(linewidth = 0.8) +
  geom_point(data = amins, aes(log10(lam), rmse, colour = factor(sprintf("%.2f", alpha))),
             size = 2.6, show.legend = FALSE) +
  geom_point(data = best, aes(log10(lam), rmse), colour = "black", shape = 21, fill = NA,
             size = 4.2, stroke = 0.9, inherit.aes = FALSE) +
  scale_colour_manual(values = pal, name = expression(alpha),
    labels = c("0.10 (near ridge)", "0.25", "0.50 (chosen)", "0.75", "1.00 (lasso)")) +
  labs(title = "Cross-validation over both the mix and the penalty",
       subtitle = "10-fold CV error along each alpha path; the ringed point is the joint minimum",
       x = expression(log[10] ~ lambda), y = "cross-validated RMSE")

## ---- fits ----
b_en  <- en_fit_cov(G0, xy0, lam_hat, alpha_hat)
b_las <- en_fit_cov(G0, xy0, lam_las, 1.0)
sel_en <- which(b_en != 0); sel_las <- which(b_las != 0)
grp_en <- sum(b_en[grp] != 0); grp_las <- sum(b_las[grp] != 0)
tp <- function(s) sum(beta_true[s] != 0); fp <- function(s) sum(beta_true[s] == 0)

trmse <- function(bs) { q <- back(bs, st$xn, st$xm, ym); sqrt(mean((yt - (as.numeric(Xt %*% q$bo) + q$it))^2)) }
ols <- lm(y ~ ., data = data.frame(y = y, X)); rmse_ols <- sqrt(mean((yt - cbind(1, Xt) %*% coef(ols))^2))
rmse_en <- trmse(b_en); rmse_las <- trmse(b_las)

## ---- stability ----
set.seed(4322); B <- 800
sf_en <- numeric(p); sf_las <- numeric(p); n_grp_en <- integer(B)
for (b in 1:B) {
  id <- sample.int(n, n, replace = TRUE)
  s <- standardise(X[id, ]); ycb <- y[id] - mean(y[id])
  G <- gram_of(s$Xs); xy <- xy_of(s$Xs, ycb)
  sel_b  <- en_fit_cov(G, xy, lam_hat, alpha_hat) != 0
  sf_en  <- sf_en  + sel_b; n_grp_en[b] <- sum(sel_b[grp])
  sf_las <- sf_las + (en_fit_cov(G, xy, lam_las, 1.0) != 0)
}
sf_en <- sf_en / B; sf_las <- sf_las / B
all_grp_en <- mean(n_grp_en == length(grp)); min_grp_en <- min(n_grp_en)
grp_freq_en  <- mean(sf_en[grp]);  grp_min_en  <- min(sf_en[grp])
grp_freq_las <- mean(sf_las[grp]); grp_min_las <- min(sf_las[grp])
worst_las <- paste0("x", grp[which.min(sf_las[grp])])

## ---- fig-group ----
gd <- rbind(
  data.frame(var = paste0("x", grp), freq = sf_las[grp], method = "lasso (alpha = 1)"),
  data.frame(var = paste0("x", grp), freq = sf_en[grp],  method = "elastic net (alpha = 0.5)"))
gd$var <- factor(gd$var, levels = paste0("x", grp))
gd$method <- factor(gd$method, levels = c("lasso (alpha = 1)", "elastic net (alpha = 0.5)"))
ggplot(gd, aes(var, freq, fill = method)) +
  geom_col(position = position_dodge(width = 0.72), width = 0.66) +
  geom_hline(yintercept = 0.5, linetype = "dashed", colour = "#888888", linewidth = 0.4) +
  scale_fill_manual(values = c("lasso (alpha = 1)" = "#c7bda8",
                               "elastic net (alpha = 0.5)" = te_ink), name = NULL) +
  ylim(0, 1) +
  labs(title = "Elastic net keeps a correlated group together",
       subtitle = "selection frequency of six correlated true effects across 800 bootstrap resamples",
       x = NULL, y = "selection frequency")
