Investigation: Regularized regression#
Regularization trades fit against a penalty to control effective complexity. Ridge shrinks coefficients, usually without setting them to zero; lasso can produce sparse coefficients; elastic net combines penalties. Selected features are not automatically mechanisms.
Question. Tune ridge, lasso, and elastic net using identical inner folds and training-only scaling, refit the selected specification, and report its held-out error against a mean baseline.
Before running: write the result you expect and what would challenge it. Data are simulated unless explicitly identified otherwise.
# Open this notebook from book/notebooks (or book/exercises).
course_path <- if (file.exists("../R/course.R")) "../R/course.R" else "book/R/course.R"
stopifnot(file.exists(course_path))
source(course_path)
set.seed(432)
library(glmnet)
d <- simulate_features(n=160,p=40)
s <- split_groups(seq_len(nrow(d$x)))
x <- d$x[s$train,,drop=FALSE]; y <- d$y[s$train]
fold <- group_folds(seq_along(y))
grid <- expand.grid(alpha=c(0,.5,1),lambda=10^seq(-3,1,length.out=16))
errors <- matrix(NA_real_,nrow(x),nrow(grid))
for(f in unique(fold)) {
a <- which(fold!=f); v <- which(fold==f)
scaler <- fit_scaler(x[a,,drop=FALSE])
xa <- apply_scaler(x[a,,drop=FALSE],scaler)
xv <- apply_scaler(x[v,,drop=FALSE],scaler)
for(j in seq_len(nrow(grid))) {
model <- glmnet(xa,y[a],alpha=grid$alpha[j],lambda=grid$lambda[j],standardize=FALSE)
errors[v,j] <- (y[v]-drop(predict(model,newx=xv,s=grid$lambda[j])))^2
}
}
grid$validation_mse <- colMeans(errors)
best <- grid[which.min(grid$validation_mse),]
best
Loading required package: Matrix
Loaded glmnet 4.1-4
| alpha | lambda | validation_mse | |
|---|---|---|---|
| <dbl> | <dbl> | <dbl> | |
| 34 | 0 | 0.8576959 | 1.182115 |
Refit once, evaluate once#
All learned scaling and tuning used training-side observations. The final model may use the entire training set after selecting its specification. There is no need to reserve a separate subset just to estimate coefficients. Explicit positive row indices avoid confusing exclusion vectors with sample identifiers.
stopifnot(length(intersect(s$train,s$test))==0)
scaler <- fit_scaler(x)
final <- glmnet(apply_scaler(x,scaler),y,alpha=best$alpha,lambda=best$lambda,standardize=FALSE)
pred <- drop(predict(final,newx=apply_scaler(d$x[s$test,,drop=FALSE],scaler),s=best$lambda))
c(model_mse=mse(d$y[s$test],pred),baseline_mse=mse(d$y[s$test],rep(mean(y),length(s$test))))
head(as.matrix(coef(final)))
- model_mse
- 0.800926833277669
- baseline_mse
- 5.40283993722958
| s0 | |
|---|---|
| (Intercept) | -0.06980208 |
| x1 | 0.17769537 |
| x2 | -0.16588238 |
| x3 | 0.16347764 |
| x4 | -0.02547949 |
| x5 | 0.04637042 |
# Ridge remains well-defined with more predictors than observations.
high <- simulate_features(n=35,p=60)
ridge <- glmnet(high$x,high$y,alpha=0,lambda=1)
c(n=nrow(high$x),p=ncol(high$x),nonzero_predictor_coefficients=sum(as.vector(coef(ridge))[-1]!=0))
stopifnot(all(is.finite(as.vector(coef(ridge)))))
- n
- 35
- p
- 60
- nonzero_predictor_coefficients
- 60
Ridge shrinkage is not sparsity. Lasso selection among correlated features can be unstable; do not interpret a nonzero coefficient as identifying a causal mechanism. Frozen embeddings can supply many predictors, but document their origin, compare with simple features, and fit any subsequent scaling or selection inside resampling.
Interpret and verify#
Verify disjoint row identifiers, compare coefficient stability, and interpret shrinkage separately from feature selection.
Failure to consider: Negative R indices specify exclusions; they are not row identifiers that can safely be sampled as a test set. Hyperparameter selection must not depend on final test outcomes.
Report the target, the numerical result with its units, the relevant uncertainty, and one limitation. Distinguish what is established by the simulation from what would require real data.
AI audit: critique the saved faulty claim in the companion exercise before using any live assistant. If you use AI, record the relevant suggestion, your independent check, and the final decision.
Use the preceding model-selection framework and compare penalization with dimension reduction next.
sessionInfo()
R version 4.2.1 (2022-06-23)
Platform: aarch64-apple-darwin20 (64-bit)
Running under: macOS 15.7.7
Matrix products: default
BLAS: /Library/Frameworks/R.framework/Versions/4.2-arm64/Resources/lib/libRblas.0.dylib
LAPACK: /Library/Frameworks/R.framework/Versions/4.2-arm64/Resources/lib/libRlapack.dylib
locale:
[1] C.UTF-8/C.UTF-8/C.UTF-8/C/C.UTF-8/C.UTF-8
attached base packages:
[1] stats graphics grDevices utils datasets methods base
other attached packages:
[1] glmnet_4.1-4 Matrix_1.4-1
loaded via a namespace (and not attached):
[1] Rcpp_1.0.9 splines_4.2.1 uuid_1.1-0
[4] lattice_0.20-45 rlang_1.0.6 fastmap_1.1.0
[7] foreach_1.5.2 fansi_1.0.3 tools_4.2.1
[10] grid_4.2.1 utf8_1.2.2 cli_3.3.0
[13] htmltools_0.5.3 iterators_1.0.14 survival_3.3-1
[16] digest_0.6.29 lifecycle_1.0.1 crayon_1.5.1
[19] IRdisplay_1.1 repr_1.1.4 base64enc_0.1-3
[22] vctrs_0.4.1 codetools_0.2-18 IRkernel_1.3.0.9000
[25] shape_1.4.6 glue_1.6.2 evaluate_0.15
[28] pbdZMQ_0.3-7 compiler_4.2.1 pillar_1.8.0
[31] jsonlite_1.8.0
Attribution#
Notebook authored by Ven Popov and edited by Krista Bond, Charles Wu, Patience Stevens, and Amy Sentis.
Revised investigation: 2026 course revision. Original authorship is retained; examples and explanatory text have been updated.