########################################################################
# PLS 206 — Week 6: Shrinkage and cross-validation
# Grey Monroe, Fall 2026
#
# Every block is tagged:
#   [CORE]   the analysis: code you would run on your own data
#   [HANDY]  useful, not essential: wrangling, plotting, small helpers
#   [DEMO]   for the lecture only: simulated data, sums by hand, and the
#            code behind slide figures
########################################################################

# [CORE]
# install.packages(c("ggplot2", "lme4", "lmerTest", "glmnet", "MASS", "pROC"))
library(ggplot2)
library(lmerTest)   # loads lme4 too; adds df and p-values to lmer()
library(glmnet)     # ridge, lasso, elastic net; cv.glmnet()
library(MASS)       # stepAIC(), for the comparison with Week 5

# ---- Which tool for which question -----------------------------------

# | You want… | Use | |---|---| | Plots/observations grouped in farms,
# blocks, years | lmer(y ~ x + (1 | group)) | | p-values for a mixed
# model | load lmerTest instead of lme4, same lmer() call | | Groups
# that differ in their slope | lmer(y ~ x + (x | group)); test with
# anova(m1, m2, refit = FALSE) | | A yes/no or count response, grouped
# | glmer(y ~ x + (1 | group), family = binomial) (or poisson) | | Many
# predictors, shrink all slopes | glmnet(X, y, alpha = 0) (ridge) | |
# Many predictors, shrink and select | glmnet(X, y, alpha = 1) (lasso);
# 0 < alpha < 1 elastic net | | Choose λ | cv.glmnet(X, y), then
# lambda.min or lambda.1se |

########################################################################
# PART A. Shrinkage
########################################################################

# ---- 1) Which farm is best? ------------------------------------------

# 112 plots on 12 farms, 2 to 25 plots each (simulated, so the truth is
# known: Week 6/deck_build/make_data.R). For each farm, its yield at
# 100 kg N/ha estimated from its own plots.

# [CORE]
farms <- read.csv("https://greymonroe.github.io/PLS_206/data/farm_plots.csv")
head(farms)
table(farms$farm)

# [CORE]
m_fixed <- lm(yield ~ nitrogen + farm, data = farms)           # each farm on its own
own <- data.frame(nitrogen = 100, farm = sort(unique(farms$farm)))
own <- cbind(own, predict(m_fixed, own, interval = "confidence"))
own$plots <- as.numeric(table(farms$farm))
own[order(-own$fit), ]

# [DEMO: the ranking plot]
own$lab <- factor(paste0(own$farm, " (", own$plots, " plots)"), levels = paste0(own$farm, " (", own$plots, " plots)")[order(own$fit)])
ggplot(own, aes(fit, lab)) +
  geom_errorbar(aes(xmin = lwr, xmax = upr), width = 0, orientation = "y", colour = "grey60") +
  geom_point(size = 3) +
  labs(x = "Yield at 100 kg N/ha, each farm on its own plots (t/ha)", y = NULL) + theme_classic()

# ---- 2) The truth: the top farm was lucky ----------------------------

# The simulation's true farm baselines (from make_data.R, seed 6):
# farm01, with 2 plots, is really close to average.

# [DEMO: the true yields at 100 kg N]
set.seed(6); u_true <- rnorm(12, 0, 0.8)
own$truth <- 3.5 + 0.012 * 100 + u_true
own[order(-own$fit), c("farm", "plots", "fit", "truth")]

# ---- 3) Shrink toward the average ------------------------------------

# shrunk = average + w × (own − average), with w between 0 and 1. The
# mixed model in Part B does this, with w set by the data.

# [CORE]
m_mixed <- lmer(yield ~ nitrogen + (1 | farm), data = farms)
own$shrunk <- predict(m_mixed, own)
own[order(-own$fit), c("farm", "plots", "fit", "shrunk", "truth")]

# ---- 4) Replay the season 500 times ----------------------------------

# Same farms, same truth, new plots each time: how far does each farm's
# estimate land from its truth?

# [DEMO: 500 replays, own vs shrunk (about 20 s)]
set.seed(6); u <- setNames(rnorm(12, 0, 0.8), own$farm); b <- setNames(rnorm(12, 0, 0.007), own$farm)
truth <- 4.7 + u
set.seed(206)
err <- replicate(500, {
  N <- round(runif(112, 0, 200)); f <- farms$farm
  y <- 3.5 + 0.012 * N + u[f] + b[f] * (N - 100) + rnorm(112, 0, 1)
  d <- data.frame(farm = f, nitrogen = N, yield = y)
  a <- predict(lm(yield ~ nitrogen + farm, d), own)
  m <- lmer(yield ~ nitrogen + (1 | farm), d)
  c(a - truth, predict(m, own) - truth)
})
data.frame(farm = own$farm, plots = own$plots,
           error_own = round(sqrt(rowMeans(err[1:12, ]^2)), 2), error_shrunk = round(sqrt(rowMeans(err[13:24, ]^2)), 2))

########################################################################
# PART B. Mixed models
########################################################################

# ---- 5) Three ways to treat farm -------------------------------------

# [CORE]
m_ignore <- lm(yield ~ nitrogen, data = farms)                  # one line
m_fixed  <- lm(yield ~ nitrogen + farm, data = farms)           # 12 free intercepts
m_mixed  <- lmer(yield ~ nitrogen + (1 | farm), data = farms)   # farms drawn from N(0, sigma_farm^2)

# [DEMO: each farm's line, fixed vs random]
g <- expand.grid(nitrogen = c(0, 200), farm = own$farm)
g$fixed <- predict(m_fixed, g); g$random <- predict(m_mixed, g)
gl <- rbind(data.frame(g[, 1:2], yield = g$fixed, how = "farm fixed"), data.frame(g[, 1:2], yield = g$random, how = "farm random"))
ggplot(farms, aes(nitrogen, yield, colour = farm)) + geom_point(alpha = 0.6) +
  geom_line(data = gl, aes(group = farm)) + facet_wrap(~how) + theme_classic() + theme(legend.position = "none")

# ---- 6) What 'random' means ------------------------------------------

# Two variance components: farm to farm (σ_farm) and plot to plot (σ).

# [CORE]
VarCorr(m_mixed)
ranef(m_mixed)$farm          # each farm's estimated offset from the average farm

# ---- 7) Shrinkage: small farms borrow strength -----------------------

# Each farm keeps a weight w = σ²_farm / (σ²_farm + σ² / n) of its own
# estimate.

# [CORE]
s_farm <- attr(VarCorr(m_mixed)$farm, "stddev")
s <- sigma(m_mixed)
n <- as.numeric(table(farms$farm))
round(s_farm^2 / (s_farm^2 + s^2 / n), 2)

# [DEMO: the shrinkage picture]
avg <- fixef(m_mixed)[1] + fixef(m_mixed)[2] * 100
plot(1:12, own$fit - avg, ylim = range(c(own$fit, own$shrunk) - avg), xaxt = "n", xlab = "", ylab = "Farm effect (t/ha)")
axis(1, at = 1:12, labels = paste0("n=", own$plots), cex.axis = 0.7)
points(1:12, own$shrunk - avg, pch = 16, col = "purple")
arrows(1:12, own$fit - avg, 1:12, own$shrunk - avg, length = 0.05, col = "purple")
abline(h = 0, lty = 2)

# ---- 8) In R: lmer() -------------------------------------------------

# [CORE]
summary(m_mixed)
coef(summary(m_fixed))["nitrogen", ]       # the slope barely changes: nitrogen varies within farms

# ---- 9) p-values: lmerTest -------------------------------------------

# With library(lmerTest) loaded, lmer() gives Satterthwaite df and
# p-values. Nitrogen varies plot by plot, so its df is close to the
# number of plots.

# [CORE]
coef(summary(m_mixed))
anova(m_mixed)               # F test for each fixed term

# ---- 10) Why it matters: a treatment chosen per farm -----------------

# Six of the 12 farmers grew a cover crop. In the simulation it does
# nothing.

# [CORE]
m_plots <- lm(yield ~ nitrogen + cover, data = farms)                # plots as independent: wrong
coef(summary(m_plots))["coveryes", ]
m_cover <- lmer(yield ~ nitrogen + cover + (1 | farm), data = farms)  # farm in the model: honest
coef(summary(m_cover))["coveryes", ]                                 # df about 8: it is the farms that count

# ---- 11) Random slopes -----------------------------------------------

# Rescale nitrogen to 100s of kg so lmer() converges, then test the
# extra variance.

# [CORE]
farms$n100 <- farms$nitrogen / 100
m_int   <- lmer(yield ~ n100 + (1 | farm), data = farms)
m_slope <- lmer(yield ~ n100 + (n100 | farm), data = farms)
anova(m_int, m_slope, refit = FALSE)
VarCorr(m_slope)
coef(m_slope)$farm           # each farm's own intercept and slope (shrunk)

# ---- 12) glmer(): yes/no and counts ----------------------------------

# [CORE]
m_rust <- glmer(rust ~ nitrogen + (1 | farm), data = farms, family = binomial)
summary(m_rust)
exp(10 * fixef(m_rust)["nitrogen"])   # odds ratio per 10 kg N
# counts: glmer(aphids ~ nitrogen + (1 | farm), family = poisson, data = ...)

# [HANDY]
# P(rust) along nitrogen for the average farm (re.form = NA: no farm effect)
g <- data.frame(nitrogen = 0:200)
g$p <- predict(m_rust, g, type = "response", re.form = NA)
ggplot(farms, aes(nitrogen, rust)) + geom_jitter(height = 0.03, width = 0, alpha = 0.5) +
  geom_line(data = g, aes(nitrogen, p), colour = "purple", linewidth = 1.2) +
  labs(x = "Nitrogen (kg N/ha)", y = "P(rust)") + theme_classic()

# ---- 13) Checks ------------------------------------------------------

# [CORE]
plot(m_mixed)                                          # residuals vs fitted, as for lm()
qqnorm(ranef(m_mixed)$farm[, 1]); qqline(ranef(m_mixed)$farm[, 1])   # farm effects roughly Normal

# ---- 14) Plot the model ----------------------------------------------

# [HANDY]
# yield along nitrogen for the average farm, with a 95% CI from the fixed effects
g <- data.frame(nitrogen = 0:200)
X0 <- cbind(1, g$nitrogen)
g$fit <- as.vector(X0 %*% fixef(m_mixed))
se <- sqrt(diag(X0 %*% vcov(m_mixed) %*% t(X0)))
g$lo <- g$fit - 1.96 * se; g$hi <- g$fit + 1.96 * se
ggplot(farms, aes(nitrogen, yield)) + geom_point(aes(colour = farm), alpha = 0.6) +
  geom_ribbon(data = g, aes(nitrogen, ymin = lo, ymax = hi), inherit.aes = FALSE, alpha = 0.2) +
  geom_line(data = g, aes(nitrogen, fit), linewidth = 1.2) +
  labs(x = "Nitrogen (kg N/ha)", y = "Yield (t/ha)") + theme_classic() + theme(legend.position = "none")

########################################################################
# PART C. Ridge and lasso
########################################################################

# ---- 15) Back to 15 predictors, one real driver ----------------------

# The cover-crop farms from Week 5. Simulated: only gdd drives biomass.

# [CORE]
cc <- read.csv("https://greymonroe.github.io/PLS_206/data/cover_crop.csv")
cc <- subset(cc, select = -c(farm, clay))
X <- scale(as.matrix(cc[, -1]))       # 15 predictors in SD units
y <- cc$biomass
round(coef(lm(y ~ X)), 1)             # every slope free

# ---- 16) Scale the predictors first ----------------------------------

# [CORE]
round(apply(cc[, c("gdd", "rain_total", "soil_ph")], 2, sd), 1)
round(apply(X, 2, sd), 1)             # after scale(): all 1

# ---- 17) Ridge: turn the dial ----------------------------------------

# [CORE]
fit_ridge <- glmnet(X, y, alpha = 0)
round(cbind(lambda_1000 = coef(fit_ridge, s = 1000)[, 1],
            lambda_30000 = coef(fit_ridge, s = 30000)[, 1]), 1)
plot(fit_ridge, xvar = "lambda", label = TRUE)      # every slope shrinks, none hits 0

# (glmnet divides the misfit by the sample size, so its λ values are on
# its own scale. The slides fit biomass in t/ha, so their λ values
# differ from these by a factor of 1,000.)

# ---- 18) Lasso: slopes hit exactly zero ------------------------------

# [CORE]
fit_lasso <- glmnet(X, y, alpha = 1)
plot(fit_lasso, xvar = "lambda", label = TRUE)
coef(fit_lasso, s = 300)              # only gdd left
coef(fit_lasso, s = 50)               # a smaller price: more predictors in

# ---- 19) Why exactly zero? Circle vs diamond -------------------------

# [DEMO: misfit contours vs the ridge circle and lasso diamond]
set.seed(12); x1 <- rnorm(60); x2 <- 0.5 * x1 + sqrt(0.75) * rnorm(60); y2 <- 1.6 * x1 + 0.45 * x2 + rnorm(60, 0, 1.2)
X2 <- scale(cbind(x1, x2)); yc <- y2 - mean(y2)
gr <- expand.grid(b1 = seq(-0.6, 2.4, length.out = 151), b2 = seq(-1, 2, length.out = 151))
gr$rss <- apply(gr[, 1:2], 1, function(b) sum((yc - X2 %*% b)^2))
best <- function(ok) gr[ok, ][which.min(gr$rss[ok]), ]
rbind(ridge = best(gr$b1^2 + gr$b2^2 <= 1), lasso = best(abs(gr$b1) + abs(gr$b2) <= 1))   # lasso: b2 = 0

# ---- 20) Lasso vs stepwise on 200 resampled data sets ----------------

# The same 200 resamples as Week 5 (seed 2); λ by cross-validation
# (Wednesday).

# [DEMO: selection frequency, stepAIC vs lasso (about 30 s)]
P <- colnames(X)
set.seed(2); idx <- replicate(200, sample(50, 50, TRUE), simplify = FALSE)
sel_step <- sapply(idx, function(i) P %in% attr(terms(stepAIC(lm(biomass ~ ., cc[i, ]), trace = 0)), "term.labels"))
sel_las <- sapply(seq_along(idx), function(b) { i <- idx[[b]]; set.seed(1000 + b)
  cv <- cv.glmnet(scale(as.matrix(cc[i, P])), cc$biomass[i], alpha = 1, nfolds = 10)
  as.numeric(coef(cv, s = "lambda.1se"))[-1] != 0 })
data.frame(var = P, stepAIC = rowMeans(sel_step), lasso = rowMeans(sel_las))
c(stepAIC = sum(colSums(sel_step) == 1 & sel_step[P == "gdd", ]), lasso = sum(colSums(sel_las) == 1 & sel_las[P == "gdd", ]))   # gdd alone

# ---- 21) Ridge, lasso, elastic net -----------------------------------

# [CORE]
fit_enet <- glmnet(X, y, alpha = 0.5)   # half ridge, half lasso
coef(fit_enet, s = 300)

# ---- 22) Shrunk slopes have no p-values ------------------------------

# Use ridge and lasso to predict and to screen predictors. To test a
# hypothesis about a slope, fit the model you wrote down in advance
# with lm()/lmer() (Week 5).

########################################################################
# PART D. Cross-validation
########################################################################

# ---- 23) Which λ? Not the one that fits best -------------------------

# On the farms it was fitted to, error only falls as λ shrinks toward
# 0. That cannot choose λ.

# [CORE]
library(pROC)       # roc(), auc()
rmse <- function(obs, pred) sqrt(mean((obs - pred)^2))
y_t <- cc$biomass / 1000                         # t/ha
fit <- glmnet(X, y_t, alpha = 1)
train_err <- sapply(fit$lambda, function(L) rmse(y_t, predict(fit, X, s = L)))
plot(log(fit$lambda), train_err, type = "l", xlab = "log(lambda)", ylab = "Error on the fitted farms (t/ha)")

# ---- 24) Hold out half: the answer depends on the split --------------

# [DEMO: six random 25/25 splits]
lam <- exp(seq(log(1.5), log(0.002), length.out = 80))
for (s in 1:6) {
  set.seed(100 + s); tr <- sample(50, 25)
  f <- glmnet(X[tr, ], y_t[tr], alpha = 1, lambda = lam)
  e <- sapply(lam, function(L) rmse(y_t[-tr], predict(f, X[-tr, ], s = L)))
  if (s == 1) plot(log(lam), e, type = "l", ylim = c(1, 2.3), xlab = "log(lambda)", ylab = "Error on the other 25 farms") else lines(log(lam), e, col = s)
  points(log(lam)[which.min(e)], min(e), pch = 16, col = s)
}

# ---- 25) k-fold: every farm gets a turn ------------------------------

# [CORE]
set.seed(3)
fold <- sample(rep(1:10, length.out = nrow(cc)))
pred_gdd <- pred_all <- numeric(nrow(cc))
for (k in 1:10) {
  train <- cc[fold != k, ]; test <- cc[fold == k, ]
  pred_gdd[fold == k] <- predict(lm(biomass ~ gdd, data = train), test)
  pred_all[fold == k] <- predict(lm(biomass ~ ., data = train), test)
}
rmse(cc$biomass, pred_gdd) / 1000
rmse(cc$biomass, pred_all) / 1000

# ---- 26) Leave-one-out: k = n ----------------------------------------

# [CORE]
set.seed(1)
cv10  <- cv.glmnet(X, y_t, alpha = 1, nfolds = 10)
cvloo <- cv.glmnet(X, y_t, alpha = 1, nfolds = nrow(X), grouped = FALSE)
c(ten_fold = cv10$lambda.min, leave_one_out = cvloo$lambda.min)

# ---- 27) cv.glmnet(): lambda.min and lambda.1se ----------------------

# [CORE]
set.seed(1)
cv <- cv.glmnet(X, y_t, alpha = 1, nfolds = 10)
cv
plot(cv)
b <- cbind(min = coef(cv, s = "lambda.min")[, 1], se1 = coef(cv, s = "lambda.1se")[, 1])
round(b[rowSums(b != 0) > 0, ], 3)
predict(cv, X[1:3, ], s = "lambda.min")          # predictions at the chosen lambda

# ---- 28) Folds are random: so is λ -----------------------------------

# [CORE]
sapply(1:10, function(s) { set.seed(s); cv.glmnet(X, y_t, alpha = 1, nfolds = 10)$lambda.min })

# ---- 29) Compare whole recipes on unseen farms -----------------------

# λ is chosen inside each training fold (a cv.glmnet() within each
# fold), never on all the data.

# [CORE]
P <- colnames(X)
set.seed(3); fo <- sample(rep(1:10, length.out = nrow(cc)))
recipes <- c("mean", "lm_all", "ridge", "lasso", "lm_gdd")
pred <- sapply(recipes, function(m) {
  pp <- numeric(nrow(cc))
  for (k in 1:10) {
    d <- cc[fo != k, ]; nd <- cc[fo == k, ]
    Xt <- as.matrix(d[, P]); Xn <- as.matrix(nd[, P])
    pp[fo == k] <- switch(m,
      mean   = mean(d$biomass),
      lm_all = predict(lm(biomass ~ ., d), nd),
      lm_gdd = predict(lm(biomass ~ gdd, d), nd),
      ridge  = { set.seed(k); predict(cv.glmnet(Xt, d$biomass, alpha = 0), Xn, s = "lambda.min") },
      lasso  = { set.seed(k); predict(cv.glmnet(Xt, d$biomass, alpha = 1), Xn, s = "lambda.1se") })
  }
  pp / 1000
})
round(apply(pred, 2, function(p) rmse(y_t, p)), 2)

########################################################################
# PART E. CV traps
########################################################################

# ---- 30) Screening outside the folds ---------------------------------

# Pure noise: 100 rows, 200 random columns. Pick the 5 columns most
# correlated with y on all rows, then cross-validate (wrong), or pick
# them inside each fold (right).

# [CORE]
set.seed(41)
Z <- matrix(rnorm(100 * 200), 100); yy <- rnorm(100); f <- sample(rep(1:10, 10))
best5 <- order(-abs(cor(Z, yy)))[1:5]                 # chosen on ALL rows
p_out <- p_in <- p_mean <- numeric(100)
for (k in 1:10) {
  tr <- f != k
  p_out[!tr] <- cbind(1, Z[!tr, best5]) %*% coef(lm(yy[tr] ~ Z[tr, best5]))
  b5 <- order(-abs(cor(Z[tr, ], yy[tr])))[1:5]       # chosen on the training rows only
  p_in[!tr] <- cbind(1, Z[!tr, b5]) %*% coef(lm(yy[tr] ~ Z[tr, b5]))
  p_mean[!tr] <- mean(yy[tr])
}
c(outside = rmse(yy, p_out), inside = rmse(yy, p_in), mean = rmse(yy, p_mean))

# [DEMO: 200 noise data sets]
trap <- function(seed) { set.seed(seed); Z <- matrix(rnorm(100 * 200), 100); yy <- rnorm(100); f <- sample(rep(1:10, 10))
  sel <- order(-abs(cor(Z, yy)))[1:5]; o <- i <- m <- numeric(100)
  for (k in 1:10) { tr <- f != k
    o[!tr] <- cbind(1, Z[!tr, sel]) %*% coef(lm(yy[tr] ~ Z[tr, sel]))
    s2 <- order(-abs(cor(Z[tr, ], yy[tr])))[1:5]; i[!tr] <- cbind(1, Z[!tr, s2]) %*% coef(lm(yy[tr] ~ Z[tr, s2]))
    m[!tr] <- mean(yy[tr]) }
  c(outside = rmse(yy, o) < rmse(yy, m), inside = rmse(yy, i) < rmse(yy, m)) }
rowMeans(sapply(1:200, trap))     # share of data sets where CV says 'beats the mean'

# ---- 31) Rows that come in groups: leave one farm out ----------------

# [CORE]
set.seed(4)
f2 <- sample(rep(1:10, length.out = nrow(farms)))
p_random <- p_lofo <- numeric(nrow(farms))
for (k in 1:10) {
  m <- lmer(yield ~ nitrogen + (1 | farm), data = farms[f2 != k, ])
  p_random[f2 == k] <- predict(m, farms[f2 == k, ], allow.new.levels = TRUE)
}
for (fm in unique(farms$farm)) {
  m <- lmer(yield ~ nitrogen + (1 | farm), data = farms[farms$farm != fm, ])
  p_lofo[farms$farm == fm] <- predict(m, farms[farms$farm == fm, ], re.form = NA)
}
c(random_folds = rmse(farms$yield, p_random), leave_one_farm_out = rmse(farms$yield, p_lofo))

# [HANDY]
# grouped folds with cv.glmnet: give each row its group's fold number
# foldid <- as.integer(factor(d$site))        # one fold per site
# cv.glmnet(X, y, foldid = foldid)

########################################################################
# PART F. Classification
########################################################################

# ---- 32) Predict the species from climate ----------------------------

# The two pistachios from Week 5: P. terebinthus = 1, P. lentiscus = 0.
# Hold out 30% of the records; logistic lasso on the rest.

# [CORE]
pis <- read.csv("https://greymonroe.github.io/PLS_206/data/pistacia_niche.csv")
names(pis) <- sub("^(bio[0-9]+)_.*", "\\1", names(pis))
pis$y <- as.integer(pis$species_short == "terebinthus")
pis$effort <- log10(pis$plant_obs_effort)
Xp <- scale(as.matrix(pis[, c(paste0("bio", 1:19), "effort")]))
set.seed(6)
test <- sample(nrow(pis), round(0.3 * nrow(pis)))
cvp <- cv.glmnet(Xp[-test, ], pis$y[-test], family = "binomial", alpha = 1)
b <- coef(cvp, s = "lambda.1se")[, 1]
round(b[b != 0], 2)

# ---- 33) A probability, then a call ----------------------------------

# [CORE]
p_hat <- as.numeric(predict(cvp, Xp[test, ], s = "lambda.1se", type = "response"))
hist(p_hat[pis$y[test] == 0], breaks = 25, col = rgb(0.2, 0.5, 0.2, 0.6), xlim = c(0, 1), main = "", xlab = "Predicted P(terebinthus)")
hist(p_hat[pis$y[test] == 1], breaks = 25, col = rgb(0.7, 0.4, 0.1, 0.6), add = TRUE)
abline(v = 0.5, lty = 2)

# ---- 34) The confusion matrix ----------------------------------------

# [CORE]
call <- ifelse(p_hat > 0.5, "terebinthus", "lentiscus")
tab <- table(predicted = call, true = pis$species_short[test])
tab
c(accuracy    = sum(diag(tab)) / sum(tab),
  baseline    = mean(pis$species_short[test] == "lentiscus"),        # always 'lentiscus'
  sensitivity = tab["terebinthus", "terebinthus"] / sum(tab[, "terebinthus"]),
  specificity = tab["lentiscus", "lentiscus"] / sum(tab[, "lentiscus"]))

# ---- 35) Move the threshold ------------------------------------------

# [CORE]
yt <- pis$y[test]
thr <- c(0.3, 0.42, 0.5, 0.7)
data.frame(threshold = thr,
           sensitivity = sapply(thr, function(t) mean(p_hat[yt == 1] > t)),
           specificity = sapply(thr, function(t) mean(p_hat[yt == 0] <= t)))

# ---- 36) ROC curve and AUC -------------------------------------------

# [CORE]
m_bio1 <- glm(y ~ bio1, family = binomial, data = pis[-test, ])
p_bio1 <- predict(m_bio1, pis[test, ], type = "response")
r_lasso <- roc(yt, p_hat); r_bio1 <- roc(yt, p_bio1)
c(lasso = auc(r_lasso), bio1 = auc(r_bio1))
plot(r_lasso, col = "blue"); lines(r_bio1, col = "orange")

# ---- 37) AUC by cross-validation -------------------------------------

# [CORE]
set.seed(6)
cv_auc <- cv.glmnet(Xp[-test, ], pis$y[-test], family = "binomial", type.measure = "auc")
max(cv_auc$cvm)          # CV AUC on the training records; compare with the test AUC above

# ---- 38) A number y: RMSE, MAE, R² on unseen data --------------------

# The cross-validated predictions of lm(biomass ~ gdd) from section 29.

# [CORE]
p <- pred[, "lm_gdd"]
c(RMSE = rmse(y_t, p), MAE = mean(abs(y_t - p)), R2 = 1 - sum((y_t - p)^2) / sum((y_t - mean(y_t))^2),
  R2_fitted = summary(lm(biomass ~ gdd, cc))$r.squared)
