Week 6: Shrinkage and cross-validation
PLS 206 — the code behind the lectures
One page for the whole week. It follows the slides (Week6_Shrinkage_CV.pptx) in order, and has the code behind every figure and number in the lecture, with the output underneath.
To run it yourself, download either version and open it in RStudio. It reads the data straight from the course website, so there is no file to download and no working directory to set:
- Week6_Shrinkage_CV.R: the plain script. Each block is tagged
[CORE],[HANDY], or[DEMO]in a comment. - Week6_Shrinkage_CV.qmd: this page as a Quarto notebook (open in RStudio, run chunk by chunk, or click Render).
Every block of code on this page carries one of three labels:
- Core The analysis. Code you would run on your own data: fit the model, read the output, check the diagnostics, report it. Start here for the problem sets.
- Handy Useful, not essential. Wrangling, plotting, and small helpers that make the core easier. Worth knowing; skip on a first read.
- Demo For the lecture only. Simulated data, sums done by hand, and the code behind slide figures. It shows why the core works. Folded: click to open.
# 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 5Which 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.
farms <- read.csv("https://greymonroe.github.io/PLS_206/data/farm_plots.csv")
head(farms) farm cover nitrogen yield rust
1 farm01 no 115 7.77 1
2 farm01 no 197 6.47 0
3 farm02 no 24 5.71 0
4 farm02 no 67 3.87 1
5 farm03 yes 97 3.82 0
6 farm03 yes 165 4.52 0
table(farms$farm)
farm01 farm02 farm03 farm04 farm05 farm06 farm07 farm08 farm09 farm10 farm11
2 2 3 4 5 6 8 10 12 15 20
farm12
25
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), ] nitrogen farm fit lwr upr plots
1 100 farm01 6.596074 5.060093 8.132056 2
11 100 farm11 5.901633 5.420295 6.382972 20
4 100 farm04 5.352876 4.272084 6.433668 4
2 100 farm02 5.299892 3.764689 6.835095 2
5 100 farm05 5.012638 4.050166 5.975110 5
3 100 farm03 4.827690 3.569239 6.086140 3
6 100 farm06 4.651135 3.772582 5.529688 6
8 100 farm08 4.637770 3.949037 5.326503 10
9 100 farm09 4.378740 3.757595 4.999884 12
10 100 farm10 4.117489 3.561714 4.673264 15
12 100 farm12 3.733240 3.302929 4.163551 25
7 100 farm07 3.395713 2.633580 4.157847 8
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")] farm plots fit truth
1 farm01 2 6.596074 4.915685
11 farm11 20 5.901633 6.082281
4 farm04 4 5.352876 6.081756
2 farm02 2 5.299892 4.196012
5 farm05 5 5.012638 4.719350
3 farm03 3 4.827690 5.394928
6 farm06 6 4.651135 4.994420
8 farm08 10 4.637770 5.290898
9 farm09 12 4.378740 4.735898
10 farm10 15 4.117489 3.861282
12 farm12 25 3.733240 3.757120
7 farm07 8 3.395713 3.652637
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.
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")] farm plots fit shrunk truth
1 farm01 2 6.596074 5.641004 4.915685
11 farm11 20 5.901633 5.793073 6.082281
4 farm04 4 5.352876 5.135445 6.081756
2 farm02 2 5.299892 5.016129 4.196012
5 farm05 5 5.012638 4.927945 4.719350
3 farm03 3 4.827690 4.778423 5.394928
6 farm06 6 4.651135 4.671565 4.994420
8 farm08 10 4.637770 4.658983 5.290898
9 farm09 12 4.378740 4.430372 4.735898
10 farm10 15 4.117489 4.192081 3.861282
12 farm12 25 3.733240 3.809207 3.757120
7 farm07 8 3.395713 3.665364 3.652637
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)) farm plots error_own error_shrunk
1 farm01 2 0.74 0.43
2 farm02 2 0.73 0.50
3 farm03 3 0.60 0.46
4 farm04 4 0.51 0.57
5 farm05 5 0.55 0.43
6 farm06 6 0.44 0.36
7 farm07 8 0.35 0.37
8 farm08 10 0.42 0.37
9 farm09 12 0.29 0.26
10 farm10 15 0.31 0.31
11 farm11 20 0.28 0.29
12 farm12 25 0.23 0.22
Part B. Mixed models
5) Three ways to treat farm
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 (σ).
VarCorr(m_mixed) Groups Name Std.Dev.
farm (Intercept) 0.75542
Residual 1.08355
ranef(m_mixed)$farm # each farm's estimated offset from the average farm (Intercept)
farm01 0.91437160
farm02 0.28949645
farm03 0.05179048
farm04 0.40881274
farm05 0.20131185
farm06 -0.05506794
farm07 -1.06126831
farm08 -0.06764957
farm09 -0.29626026
farm10 -0.53455161
farm11 1.06644063
farm12 -0.91742608
7) Shrinkage: small farms borrow strength
Each farm keeps a weight w = σ²_farm / (σ²_farm + σ² / n) of its own estimate.
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) [1] 0.49 0.49 0.59 0.66 0.71 0.74 0.80 0.83 0.85 0.88 0.91 0.92
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()
summary(m_mixed)Linear mixed model fit by REML. t-tests use Satterthwaite's method [
lmerModLmerTest]
Formula: yield ~ nitrogen + (1 | farm)
Data: farms
REML criterion at convergence: 363.7
Scaled residuals:
Min 1Q Median 3Q Max
-2.67404 -0.71433 0.06569 0.68969 2.07931
Random effects:
Groups Name Variance Std.Dev.
farm (Intercept) 0.5707 0.7554
Residual 1.1741 1.0836
Number of obs: 112, groups: farm, 12
Fixed effects:
Estimate Std. Error df t value Pr(>|t|)
(Intercept) 3.765e+00 3.186e-01 2.457e+01 11.818 1.25e-11 ***
nitrogen 9.614e-03 1.877e-03 1.048e+02 5.122 1.38e-06 ***
---
Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
Correlation of Fixed Effects:
(Intr)
nitrogen -0.606
coef(summary(m_fixed))["nitrogen", ] # the slope barely changes: nitrogen varies within farms Estimate Std. Error t value Pr(>|t|)
9.355818e-03 1.913966e-03 4.888185e+00 3.930525e-06
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.
coef(summary(m_mixed)) Estimate Std. Error df t value Pr(>|t|)
(Intercept) 3.76527368 0.318601077 24.57483 11.818145 1.251857e-11
nitrogen 0.00961359 0.001876815 104.77084 5.122291 1.381929e-06
anova(m_mixed) # F test for each fixed termType III Analysis of Variance Table with Satterthwaite's method
Sum Sq Mean Sq NumDF DenDF F value Pr(>F)
nitrogen 30.805 30.805 1 104.77 26.238 1.382e-06 ***
---
Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
10) Why it matters: a treatment chosen per farm
Six of the 12 farmers grew a cover crop. In the simulation it does nothing.
m_plots <- lm(yield ~ nitrogen + cover, data = farms) # plots as independent: wrong
coef(summary(m_plots))["coveryes", ] Estimate Std. Error t value Pr(>|t|)
1.021919e+00 2.347593e-01 4.353048e+00 3.040905e-05
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 Estimate Std. Error df t value Pr(>|t|)
0.4169686 0.4974548 8.3182642 0.8382038 0.4253449
11) Random slopes
Rescale nitrogen to 100s of kg so lmer() converges, then test the extra variance.
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)Data: farms
Models:
m_int: yield ~ n100 + (1 | farm)
m_slope: yield ~ n100 + (n100 | farm)
npar AIC BIC logLik -2*log(L) Chisq Df Pr(>Chisq)
m_int 4 362.51 373.38 -177.25 354.51
m_slope 6 348.91 365.22 -168.45 336.91 17.602 2 0.0001506 ***
---
Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
VarCorr(m_slope) Groups Name Std.Dev. Corr
farm (Intercept) 0.66919
n100 1.04310 -0.715
Residual 0.94968
coef(m_slope)$farm # each farm's own intercept and slope (shrunk) (Intercept) n100
farm01 3.556113 1.8096814
farm02 3.972884 0.6624263
farm03 3.158982 1.5526480
farm04 3.169027 1.9009641
farm05 3.233617 1.7239312
farm06 4.257568 0.1423608
farm07 3.416304 0.3026083
farm08 2.556270 2.6738120
farm09 3.738894 0.6294319
farm10 3.856759 0.2425173
farm11 3.446890 2.4119869
farm12 3.248445 0.5636322
12) glmer(): yes/no and counts
m_rust <- glmer(rust ~ nitrogen + (1 | farm), data = farms, family = binomial)
summary(m_rust)Generalized linear mixed model fit by maximum likelihood (Laplace
Approximation) [glmerMod]
Family: binomial ( logit )
Formula: rust ~ nitrogen + (1 | farm)
Data: farms
AIC BIC logLik -2*log(L) df.resid
142.7 150.9 -68.3 136.7 109
Scaled residuals:
Min 1Q Median 3Q Max
-2.0657 -0.7554 0.4122 0.6670 2.0785
Random effects:
Groups Name Variance Std.Dev.
farm (Intercept) 0.8995 0.9484
Number of obs: 112, groups: farm, 12
Fixed effects:
Estimate Std. Error z value Pr(>|z|)
(Intercept) -1.514598 0.606916 -2.496 0.012576 *
nitrogen 0.015022 0.004443 3.381 0.000722 ***
---
Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
Correlation of Fixed Effects:
(Intr)
nitrogen -0.780
exp(10 * fixef(m_rust)["nitrogen"]) # odds ratio per 10 kg Nnitrogen
1.16209
# counts: glmer(aphids ~ nitrogen + (1 | farm), family = poisson, data = ...)# 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
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
# 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.
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 (Intercept) Xlatitude Xlongitude Xelevation Xgdd
4252.9 294.4 -159.1 202.2 1902.6
Xtmean_winter Xtmin_coldest Xfrost_days Xrain_total Xrain_wettest
-682.3 279.7 -111.9 -539.9 546.8
Xrain_driest Xdry_spell Xsand Xsilt Xsoil_ph
-245.7 -108.1 -185.8 -38.4 -172.0
Xorganic_matter
177.9
16) Scale the predictors first
round(apply(cc[, c("gdd", "rain_total", "soil_ph")], 2, sd), 1) gdd rain_total soil_ph
203.0 160.0 0.5
round(apply(X, 2, sd), 1) # after scale(): all 1 latitude longitude elevation gdd tmean_winter
1 1 1 1 1
tmin_coldest frost_days rain_total rain_wettest rain_driest
1 1 1 1 1
dry_spell sand silt soil_ph organic_matter
1 1 1 1 1
17) Ridge: turn the dial
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) lambda_1000 lambda_30000
(Intercept) 4252.9 4252.9
latitude -35.7 -32.9
longitude -112.6 -6.3
elevation -4.5 -21.3
gdd 524.8 68.9
tmean_winter 190.4 55.9
tmin_coldest 191.1 54.9
frost_days -202.1 -55.2
rain_total -80.5 -10.4
rain_wettest 41.5 -7.0
rain_driest -47.0 -11.2
dry_spell 33.7 3.3
sand -178.5 -24.1
silt -100.0 -15.1
soil_ph -37.8 5.5
organic_matter 52.7 5.5
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
fit_lasso <- glmnet(X, y, alpha = 1)
plot(fit_lasso, xvar = "lambda", label = TRUE)
coef(fit_lasso, s = 300) # only gdd left16 x 1 sparse Matrix of class "dgCMatrix"
s=300
(Intercept) 4252.900
latitude .
longitude .
elevation .
gdd 1117.041
tmean_winter .
tmin_coldest .
frost_days .
rain_total .
rain_wettest .
rain_driest .
dry_spell .
sand .
silt .
soil_ph .
organic_matter .
coef(fit_lasso, s = 50) # a smaller price: more predictors in16 x 1 sparse Matrix of class "dgCMatrix"
s=50
(Intercept) 4252.900000
latitude 86.357875
longitude -90.457874
elevation .
gdd 1399.374819
tmean_winter .
tmin_coldest .
frost_days .
rain_total -45.080019
rain_wettest .
rain_driest -20.018130
dry_spell .
sand -146.107620
silt -9.274056
soil_ph -54.475892
organic_matter 51.200682
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 b1 b2 rss
ridge 0.96 0.26 101.3944
lasso 1.00 0.00 106.3289
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)) var stepAIC lasso
1 latitude 0.535 0.120
2 longitude 0.450 0.190
3 elevation 0.520 0.175
4 gdd 0.990 1.000
5 tmean_winter 0.425 0.025
6 tmin_coldest 0.415 0.025
7 frost_days 0.425 0.060
8 rain_total 0.515 0.100
9 rain_wettest 0.520 0.045
10 rain_driest 0.520 0.115
11 dry_spell 0.350 0.085
12 sand 0.430 0.280
13 silt 0.400 0.165
14 soil_ph 0.575 0.165
15 organic_matter 0.430 0.100
Demo: selection frequency, stepAIC vs lasso (about 30 s)
c(stepAIC = sum(colSums(sel_step) == 1 & sel_step[P == "gdd", ]), lasso = sum(colSums(sel_las) == 1 & sel_las[P == "gdd", ])) # gdd alonestepAIC lasso
0 97
21) Ridge, lasso, elastic net
fit_enet <- glmnet(X, y, alpha = 0.5) # half ridge, half lasso
coef(fit_enet, s = 300)16 x 1 sparse Matrix of class "dgCMatrix"
s=300
(Intercept) 4252.900000
latitude .
longitude -6.788096
elevation .
gdd 1156.902022
tmean_winter .
tmin_coldest .
frost_days .
rain_total .
rain_wettest .
rain_driest .
dry_spell .
sand -67.006509
silt .
soil_ph .
organic_matter .
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 λ.
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
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[1] 1.149457
rmse(cc$biomass, pred_all) / 1000[1] 1.506994
26) Leave-one-out: k = n
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) ten_fold leave_one_out
0.2186992 0.2186992
27) cv.glmnet(): lambda.min and lambda.1se
set.seed(1)
cv <- cv.glmnet(X, y_t, alpha = 1, nfolds = 10)
cv
Call: cv.glmnet(x = X, y = y_t, nfolds = 10, alpha = 1)
Measure: Mean-Squared Error
Lambda Index Measure SE Nonzero
min 0.2187 21 1.354 0.2601 1
1se 0.5052 12 1.558 0.3212 1
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) min se1
(Intercept) 4.253 4.253
gdd 1.199 0.910
predict(cv, X[1:3, ], s = "lambda.min") # predictions at the chosen lambda lambda.min
1 3.744131
2 2.793216
3 2.763684
28) Folds are random: so is λ
sapply(1:10, function(s) { set.seed(s); cv.glmnet(X, y_t, alpha = 1, nfolds = 10)$lambda.min }) [1] 0.2186992 0.2400221 0.1992705 0.2400221 0.1992705 0.1992705 0.2186992
[8] 0.1992705 0.2186992 0.2400221
29) Compare whole recipes on unseen farms
λ is chosen inside each training fold (a cv.glmnet() within each fold), never on all the data.
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) mean lm_all ridge lasso lm_gdd
1.83 1.51 1.40 1.27 1.15
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).
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)) outside inside mean
0.8513070 1.1714896 0.9900128
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'outside inside
1.00 0.05
31) Rows that come in groups: leave one farm out
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)) random_folds leave_one_farm_out
1.169358 1.417998
# 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.
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)(Intercept) bio3 bio4 bio5 bio6 bio8
-0.37 0.00 0.12 -0.05 -0.46 -0.20
bio9 bio11 bio13 bio15 effort
0.01 -0.08 0.06 0.11 0.14
33) A probability, then a call
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
call <- ifelse(p_hat > 0.5, "terebinthus", "lentiscus")
tab <- table(predicted = call, true = pis$species_short[test])
tab true
predicted lentiscus terebinthus
lentiscus 911 417
terebinthus 201 361
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"])) accuracy baseline sensitivity specificity
0.6730159 0.5883598 0.4640103 0.8192446
35) Move the threshold
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))) threshold sensitivity specificity
1 0.30 0.88431877 0.3417266
2 0.42 0.65809769 0.6429856
3 0.50 0.46401028 0.8192446
4 0.70 0.09897172 0.9937050
36) ROC curve and AUC
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)) lasso bio1
0.7132295 0.6627247
plot(r_lasso, col = "blue"); lines(r_bio1, col = "orange")
37) AUC by cross-validation
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[1] 0.6986302
38) A number y: RMSE, MAE, R² on unseen data
The cross-validated predictions of lm(biomass ~ gdd) from section 29.
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) RMSE MAE R2 R2_fitted
1.1494568 0.9917339 0.5813587 0.6261994