DRegression models · regression.penalized
Penalized regression for variable selection (lasso / elastic net / ridge)
Which predictors matter when they are shrunk together, with the penalty chosen by cross-validation?
Lasso, elastic net or ridge regression for a numeric or yes/no outcome: the whole regularization path on standardized predictors, the penalty λ chosen by k-fold cross-validation (minimum error or the one-standard-error rule), and the coefficients that survive at that λ on the original scale. A selection tool, not an inference tool: no p-values.
A real result
Example “Swiss lasso”, recorded in both engines. In the app, “Try this example” loads it into Analyze.
Lasso with λ = 0.5033 (one-SE rule, 10-fold CV) keeps 5 of 5 columns: agriculture, examination, education, catholic, infant mortality.
- Chosen λ
- 0.5033
- λ (minimum CV error)
- 0.0008
- λ (one-SE rule)
- 0.5033
- CV mean squared error at the chosen λ
- 70.391
Plots
View data
| high | low | log(λ) | mean squared error | set |
|---|---|---|---|---|
| 212.98 | 107.11 | 2.105 | 160.04 | cross-validation |
| 209.82 | 104.12 | 2.011 | 156.97 | cross-validation |
| 205.45 | 100.61 | 1.918 | 153.03 | cross-validation |
| 200.83 | 96.684 | 1.825 | 148.76 | cross-validation |
| 193.22 | 93.433 | 1.732 | 143.33 | cross-validation |
| 186.01 | 90.777 | 1.639 | 138.39 | cross-validation |
| 179.90 | 88.771 | 1.546 | 134.34 | cross-validation |
| 173.42 | 86.620 | 1.453 | 130.02 | cross-validation |
| 167.35 | 84.654 | 1.360 | 126.00 | cross-validation |
| 161.51 | 82.308 | 1.267 | 121.91 | cross-validation |
| 155.89 | 79.564 | 1.174 | 117.73 | cross-validation |
| 150.97 | 77.282 | 1.081 | 114.13 | cross-validation |
| 145.72 | 74.825 | 0.9881 | 110.27 | cross-validation |
| 141.23 | 72.833 | 0.8951 | 107.03 | cross-validation |
| 137.39 | 71.225 | 0.8020 | 104.31 | cross-validation |
| 133.74 | 69.701 | 0.7090 | 101.72 | cross-validation |
| 130.21 | 68.166 | 0.6160 | 99.186 | cross-validation |
| 127.19 | 66.899 | 0.5229 | 97.044 | cross-validation |
| 124.61 | 65.855 | 0.4299 | 95.235 | cross-validation |
| 120.63 | 64.988 | 0.3369 | 92.808 | cross-validation |
| 114.84 | 64.251 | 0.2438 | 89.547 | cross-validation |
| 109.90 | 63.626 | 0.1508 | 86.761 | cross-validation |
| 105.76 | 63.195 | 0.0578 | 84.479 | cross-validation |
| 102.20 | 62.769 | −0.0353 | 82.484 | cross-validation |
| 98.815 | 62.050 | −0.1283 | 80.432 | cross-validation |
| 95.022 | 61.214 | −0.2213 | 78.118 | cross-validation |
| 91.857 | 60.508 | −0.3144 | 76.183 | cross-validation |
| 89.219 | 59.907 | −0.4074 | 74.563 | cross-validation |
| 87.022 | 59.390 | −0.5004 | 73.206 | cross-validation |
| 84.666 | 58.744 | −0.5935 | 71.705 | cross-validation |
| 82.614 | 58.168 | −0.6865 | 70.391 | cross-validation |
| 80.880 | 57.672 | −0.7795 | 69.276 | cross-validation |
| 79.413 | 57.241 | −0.8726 | 68.327 | cross-validation |
| 78.172 | 56.866 | −0.9656 | 67.519 | cross-validation |
| 77.122 | 56.538 | −1.059 | 66.830 | cross-validation |
| 76.233 | 56.248 | −1.152 | 66.241 | cross-validation |
| 75.480 | 55.993 | −1.245 | 65.736 | cross-validation |
| 74.840 | 55.766 | −1.338 | 65.303 | cross-validation |
| 74.297 | 55.565 | −1.431 | 64.931 | cross-validation |
| 73.834 | 55.386 | −1.524 | 64.610 | cross-validation |
| 73.440 | 55.226 | −1.617 | 64.333 | cross-validation |
| 73.104 | 55.084 | −1.710 | 64.094 | cross-validation |
| 72.815 | 54.957 | −1.803 | 63.886 | cross-validation |
| 72.568 | 54.843 | −1.896 | 63.705 | cross-validation |
| 72.356 | 54.741 | −1.989 | 63.548 | cross-validation |
| 72.173 | 54.649 | −2.082 | 63.411 | cross-validation |
| 72.015 | 54.567 | −2.175 | 63.291 | cross-validation |
| 71.878 | 54.494 | −2.268 | 63.186 | cross-validation |
| 71.760 | 54.427 | −2.361 | 63.094 | cross-validation |
| 71.657 | 54.368 | −2.454 | 63.012 | cross-validation |
| 71.567 | 54.315 | −2.547 | 62.941 | cross-validation |
| 71.488 | 54.266 | −2.640 | 62.877 | cross-validation |
| 71.419 | 54.223 | −2.733 | 62.821 | cross-validation |
| 71.359 | 54.184 | −2.826 | 62.772 | cross-validation |
| 71.306 | 54.149 | −2.919 | 62.727 | cross-validation |
| 71.259 | 54.117 | −3.012 | 62.688 | cross-validation |
| 71.218 | 54.088 | −3.105 | 62.653 | cross-validation |
| 71.181 | 54.062 | −3.198 | 62.622 | cross-validation |
| 71.149 | 54.039 | −3.291 | 62.594 | cross-validation |
| 71.120 | 54.018 | −3.384 | 62.569 | cross-validation |
First 60 of 100 rows.
View data
| column | standardized coefficient |
|---|---|
| agriculture | −1.866 |
| examination | −1.548 |
| education | −6.974 |
| catholic | 3.480 |
| infant mortality | 3.051 |
Assumptions
- Selection, not inference — Penalized coefficients are shrunk toward zero and have no valid p-values; estimate effects on new data.
- Standardized predictors — Columns were standardized before penalizing; coefficients are on the original scale.
Coefficients at λ = 0.5033 (original scale)
| Column | Coefficient | Standardized |
|---|---|---|
| (Intercept) | 61.046 | 70.143 |
| agriculture | −0.0831 | −1.866 |
| examination | −0.1961 | −1.548 |
| education | −0.7331 | −6.974 |
| catholic | 0.0844 | 3.480 |
| infant mortality | 1.059 | 3.051 |
- Folds from seed 42; λ grid of 100 values from λ_max = 8.203. Cross-validated mean squared error.
Lasso with λ = 0.5033 (one-SE rule, 10-fold CV) keeps 5 of 5 columns: agriculture, examination, education, catholic, infant mortality.
- Chosen λ
- 0.5033
- λ (minimum CV error)
- 0.0008
- λ (one-SE rule)
- 0.5033
- CV mean squared error at the chosen λ
- 70.391
To keep this page light, the plots are shown once, under the R tab.
Assumptions
- Selection, not inference — Penalized coefficients are shrunk toward zero and have no valid p-values; estimate effects on new data.
- Standardized predictors — Columns were standardized before penalizing; coefficients are on the original scale.
Coefficients at λ = 0.5033 (original scale)
| Column | Coefficient | Standardized |
|---|---|---|
| (Intercept) | 61.046 | 70.143 |
| agriculture | −0.0831 | −1.866 |
| examination | −0.1961 | −1.548 |
| education | −0.7331 | −6.974 |
| catholic | 0.0844 | 3.480 |
| infant mortality | 1.059 | 3.051 |
- Folds from seed 42; λ grid of 100 values from λ_max = 8.203. Cross-validated mean squared error.
Do it in CodeSplash Run it on your own data, in Python or R, with the code to prove it.
Worked examples in the app
- Swiss lassos4_swiss · outcome: fertility · predictors: agriculture, examination, education, catholic, infant mortality
- Swiss enet mins4_swiss · outcome: fertility · predictors: agriculture, examination, education, catholic, infant mortality
- Birthwt logistic lassobirthwt · outcome: low · predictors: age, mother weight (lb), race, smoke, ptl, ht, ui, ftv
- Mtcars ridgemtcars · outcome: mpg · predictors: cyl_f, disp, hp, drat, wt, qsec, am_f
- Degenerate n3s4_swiss · outcome: fertility · predictors: agriculture, examination, education, catholic, infant mortality
In the guides
Where it sits in the decision guides
- Continuous outcome: linear regression · Statistics Guide · D — Predict an outcome
- Binary outcome: logistic regression (regularized) · Statistics Guide · D — Predict an outcome
- Model selection and structure (penalized, stepwise, SEM) · Statistics Guide · D — Predict an outcome
- Regression (linear, logistic, Poisson) · DS & ML Decision Guide · Predict — forecast or classify outcomes
What you need
- Outcomenumeric / boolean / categorical · 1 column · 2–2 levels
- The outcome: a number (linear) or yes/no (logistic).
- Candidate predictorsnumeric / categorical / boolean · 1–200 columns · 2–30 levels
- Candidate predictors; the penalty decides which matter.
Choices you make
statistics
- Modeldefault auto
Linear for numeric outcomes, logistic for yes/no. Automatic picks from the outcome type.
- Automatic (linear for numbers, logistic for yes/no)(default) — Uses linear for numeric outcomes and logistic for yes/no outcomes; the usual choice.
- Linear (squared error) — Minimizes squared error; pick it for a numeric outcome.
- Logistic (binomial deviance) — Minimizes binomial deviance; pick it for a yes/no outcome.
- Lasso share α (1 = lasso, 0 = ridge)default 1
Mix of penalties: 1 is lasso (selects predictors), 0 is ridge (shrinks all), in between is elastic net.
- Choose λ bydefault 1se
Choose λ with the minimum cross-validated error, or the 1-SE rule (simpler model, almost as good).
- One-standard-error rule (sparser, more stable)(default) — Takes the largest penalty within one SE of the best; sparser and more stable, so it's the usual choice.
- Minimum cross-validated error — Takes the penalty with the lowest cross-validated error; pick it when prediction comes first and more terms are fine.
- Cross-validation foldsdefault 10
Cross-validation folds used to choose λ. More folds use more data per fit but take longer.
- Number of λ valuesdefault 100
Number of λ values on the path tried by cross-validation.
- Event leveldefault —
Logistic models: the outcome level modeled as the event (default the last stored level).
Checks and remedies
CodeSplash checks each testable assumption on every run and shows the result on the card; premises the data can’t test are marked. If a check fails, these are the ways forward.
Selection, not inference
Penalized coefficients are biased toward zero and have no valid p-values; refit on new data to estimate effects.
Standardized predictors
Predictors are standardized before penalizing, so the penalty treats them equally; coefficients are reported on the original scale.
What it reports
- n
- How many independent units the analysis used; it sets precision and power.
- n_columns
- How many independent units the analysis used; it sets precision and power.
- family
- The exact variant that ran (for example Welch vs classic F), shown so the result can be reported and reproduced.
- alpha
- The false-positive rate you accept before looking at the data, usually 0.05.
- rule
- How λ was chosen: min (lowest cross-validated error) or 1se (largest λ within one standard error, a sparser model).
- lambda_max
- Shrinks coefficients towards zero to reduce overfitting; lasso can drop predictors entirely.
- lambda_min
- Shrinks coefficients towards zero to reduce overfitting; lasso can drop predictors entirely.
- lambda_1se
- Shrinks coefficients towards zero to reduce overfitting; lasso can drop predictors entirely.
- lambda
- Shrinks coefficients towards zero to reduce overfitting; lasso can drop predictors entirely.
- cvm_min
- Rotates which part of the data is held out, so every row is used for both training and validation.
- cvm
- Rotates which part of the data is held out, so every row is used for both training and validation.
- cvsd
- Rotates which part of the data is held out, so every row is used for both training and validation.
- n_nonzero
- How many independent units the analysis used; it sets precision and power.
- intercept
- A rank-based line through two methods' readings (median of pairwise slopes) that allows for error in both and resists outliers.
- selected
- Comma-separated design columns with a non-zero coefficient at the chosen λ, or (none). Ridge keeps every column.
Per group, level or term: coef[<column>]
Python and R
Python and R agree to 6 decimals (relative tolerance 1e-6). Python uses pandas, numpy, codesplash; R uses glmnet, nanoparquet, codesplashr.
Default traps between the two languages
- R fits glmnet (standardize = FALSE on the standardized design, thresh 1e-20, fdev 0); Python fits the same objective by covariance-update coordinate descent with glmnet's IRLS loop for the binomial case (cs selection.enet_path). For the Gaussian family glmnet standardizes y internally, so R passes α' = α / (α + s(1 − α)) and λ' = λα/α' (s = SD of y), which reproduces the (1/2n)·RSS objective.
- Folds come from the shared Wichmann–Hill permutation and the λ grid, cross-validation summaries and the one-SE rule are twins of cv.glmnet's, so both engines choose the same λ.
The exact script CodeSplash ran for example “Swiss lasso” · Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Penalized regression for variable selection (lasso / elastic net / ridge)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method regression.penalized 1.0.1 · spec c68639d19a986088
# Dataset: s4_swiss (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
import math
import numpy as np
import pandas as pd
import codesplash as cs
from codesplash.stats import selection as sel # glmnet's objective by coordinate descent; cv.glmnet's summaries (twins of codesplashr)
# %% Data
df = pd.read_parquet("tests/parity/fixtures/s4_swiss.parquet", columns=["fertility", "agriculture", "examination", "education", "catholic", "infant mortality"])
n_input = len(df)
df = df.dropna(subset=["fertility", "agriculture", "examination", "education", "catholic", "infant mortality"]) # listwise deletion over the analysis columns
n_dropped = n_input - len(df)
warnings = []
if n_dropped:
warnings.append(cs.cs_warning("CS_W_ROWS_DROPPED", dropped=n_dropped, total=n_input))
if n_input and not len(df):
cs.cs_error("CS_E_NO_ROWS")
cs.check_finite_columns(df, ["fertility", "agriculture", "examination", "education", "catholic", "infant mortality"]) # infinite values stop the run (registry/errors.yaml)
# %% Outcome and design
yname = "fertility"
predictors = ["agriculture", "examination", "education", "catholic", "infant mortality"]
kinds = {"agriculture":"numeric","catholic":"numeric","education":"numeric","examination":"numeric","fertility":"numeric","infant mortality":"numeric"}
family = "auto"
binary = kinds[yname] in ("boolean", "categorical")
if family == "auto":
family = "binomial" if binary else "gaussian"
if family == "binomial":
if not binary:
raise ValueError(f"Logistic models need a yes/no outcome; {yname} is numeric")
ylev = [str(v) for v in df[yname].cat.categories]
event = ylev[-1] # modeled level
y = (df[yname].astype(str) == event).to_numpy(dtype=float)
else:
if binary:
raise ValueError(f"Linear models need a numeric outcome; {yname} is categorical")
y = df[yname].to_numpy(dtype=float)
levels = {p: ([str(v) for v in df[p].cat.categories] if kinds[p] in ("categorical", "boolean") else None) for p in predictors}
x_full, names, _ = sel.design(df, predictors, levels)
x, names = x_full[:, 1:], names[1:] # the intercept is not penalized
n, p = x.shape
xs, xmean, xsd = sel.standardize(x) # population SD, as glmnet's standardize = TRUE
# %% Regularization path and cross-validation (scikit-learn's ElasticNet solves the same Gaussian objective)
alpha = 1
nfold = int(10)
cs.check_rows(n, nfold, f"{nfold}-fold cross-validation") # every fold needs a row to predict (same check in R)
nlambda = int(100)
rule = "1se"
seed = 42 # shared Wichmann–Hill stream: the same folds in Python and R
lambdas = sel.lambda_grid(xs, y, alpha, nlambda)
fold = sel.folds(n, nfold, seed)
fold_loss = np.zeros((nfold, len(lambdas)))
fold_n = np.zeros(nfold)
for f in range(nfold):
tr, te = fold != f, fold == f
b0s, bs = sel.enet_path(xs[tr], y[tr], family, alpha, lambdas)
eta = b0s[None, :] + xs[te] @ bs.T
pred = eta if family == "gaussian" else 1 / (1 + np.exp(-eta))
fold_loss[f] = sel.loss(y[te][:, None], pred, family).mean(axis=0)
fold_n[f] = te.sum()
cv = sel.cv_summary(fold_loss, fold_n, lambdas)
b0s, bs = sel.enet_path(xs, y, family, alpha, lambdas)
i = cv["i1se"] if rule == "1se" else cv["imin"]
coef = np.where(xsd > 0, bs[i] / np.where(xsd > 0, xsd, 1), 0.0) # back to the original scale
intercept = float(b0s[i] - coef @ xmean)
nonzero = [nm for nm, b in zip(names, coef) if b != 0]
# %% Assumptions
assumptions = [
{"key": "no_inference", "label": "Selection, not inference", "status": "info",
"detail": "Penalized coefficients are shrunk toward zero and have no valid p-values; estimate effects on new data."},
{"key": "scaling", "label": "Standardized predictors", "status": "pass", "detail": "Columns were standardized before penalizing; coefficients are on the original scale."},
]
# %% Result
kind = "lasso" if alpha == 1 else ("ridge" if alpha == 0 else "elastic net")
values = {
"n": n, "n_columns": p, "family": family, "alpha": alpha, "rule": rule,
"lambda_max": float(lambdas[0]), "lambda_min": float(lambdas[cv["imin"]]), "lambda_1se": float(lambdas[cv["i1se"]]),
"lambda": float(lambdas[i]), "cvm_min": float(cv["cvm"][cv["imin"]]), "cvm": float(cv["cvm"][i]), "cvsd": float(cv["cvsd"][i]),
"n_nonzero": len(nonzero), "intercept": intercept, "selected": ", ".join(nonzero) if nonzero else "(none)",
}
for nm, b in zip(names, coef):
values[f"coef[{nm}]"] = float(b)
err = "mean squared error" if family == "gaussian" else "binomial deviance"
loglam = [math.log(v) for v in lambdas]
cs.publish({
"method": "regression.penalized",
"methodVersion": "1.0.1",
"title": f"Penalized regression ({kind})",
"engine": cs.engine_info("pandas", "numpy"),
"n": n,
"summary": f"{kind.capitalize()} with λ = {lambdas[i]:.4g} ({'one-SE rule' if rule == '1se' else 'minimum CV error'}, {nfold}-fold CV) keeps {len(nonzero)} of {p} columns: {values['selected']}.",
"statistics": [
{"key": "lambda", "label": "Chosen λ", "value": float(lambdas[i])},
{"key": "lambda_min", "label": "λ (minimum CV error)", "value": float(lambdas[cv["imin"]])},
{"key": "lambda_1se", "label": "λ (one-SE rule)", "value": float(lambdas[cv["i1se"]])},
{"key": "cvm", "label": f"CV {err} at the chosen λ", "value": float(cv["cvm"][i])},
],
"tables": [{
"key": "coefficients", "title": f"Coefficients at λ = {lambdas[i]:.4g} (original scale)",
"columns": [{"key": "term", "label": "Column", "type": "string"}, {"key": "b", "label": "Coefficient", "type": "number"},
{"key": "std", "label": "Standardized", "type": "number"}],
"rows": [{"term": "(Intercept)", "b": intercept, "std": float(b0s[i])}]
+ [{"term": nm, "b": float(b), "std": float(bstd)} for nm, b, bstd in zip(names, coef, bs[i])],
}],
"assumptions": assumptions,
"warnings": warnings,
"notes": [f"Folds from seed {seed}; λ grid of {nlambda} values from λ_max = {lambdas[0]:.4g}. Cross-validated {err}."],
"charts": [
cs.chart("cv", "learning-curve", f"Cross-validated {err} by log(λ)",
{"n": cs.col("log(λ)", loglam), "score": cs.col(err, [float(v) for v in cv["cvm"]]), "set": cs.col("set", ["cross-validation"] * len(loglam)),
"low": cs.col("low", [float(a - b) for a, b in zip(cv["cvm"], cv["cvsd"])]), "high": cs.col("high", [float(a + b) for a, b in zip(cv["cvm"], cv["cvsd"])])}),
cs.chart("coefficients", "cleveland-dot", "Standardized coefficients at the chosen λ",
{"category": cs.col("column", names), "value": cs.col("standardized coefficient", [float(v) for v in bs[i]])}),
],
"values": values,
})
The exact script CodeSplash ran for example “Swiss lasso” · R version 4.5.1 (2025-06-13)
# Penalized regression for variable selection (lasso / elastic net / ridge)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method regression.penalized 1.0.1 · spec c68639d19a986088
# Dataset: s4_swiss (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
suppressPackageStartupMessages(library(glmnet))
library(codesplashr) # cs_sel_* (design names, lambda grid, folds, cv.glmnet summaries — twins of codesplash.stats.selection)
# %% Data
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/s4_swiss.parquet", col_select = c("fertility", "agriculture", "examination", "education", "catholic", "infant mortality")))
n_input <- nrow(df)
df <- df[stats::complete.cases(df[c("fertility", "agriculture", "examination", "education", "catholic", "infant mortality")]), , drop = FALSE] # listwise deletion
df[] <- lapply(df, function(x) if (is.factor(x)) droplevels(x) else x)
n_dropped <- n_input - nrow(df)
warnings <- list()
if (n_dropped > 0) {
warnings <- c(warnings, cs_warning("CS_W_ROWS_DROPPED", dropped = n_dropped, total = n_input))
}
if (n_input > 0 && nrow(df) == 0) cs_error("CS_E_NO_ROWS")
cs_check_finite_columns(df, c("fertility", "agriculture", "examination", "education", "catholic", "infant mortality")) # infinite values stop the run (registry/errors.yaml)
# %% Outcome and design
yname <- "fertility"
predictors <- c("agriculture", "examination", "education", "catholic", "infant mortality")
binary <- is.factor(df[[yname]])
family <- "auto"
if (family == "auto") family <- if (binary) "binomial" else "gaussian"
if (family == "binomial") {
if (!binary) stop(sprintf("Logistic models need a yes/no outcome; %s is numeric", yname))
ylev <- levels(df[[yname]])
event <- ylev[length(ylev)] # modeled level
y <- as.numeric(as.character(df[[yname]]) == event)
} else {
if (binary) stop(sprintf("Linear models need a numeric outcome; %s is categorical", yname))
y <- as.numeric(df[[yname]])
}
x <- cs_sel_design(df, predictors)[, -1, drop = FALSE] # the intercept is not penalized
names_ <- colnames(x)
n <- nrow(x)
p <- ncol(x)
st <- cs_sel_standardize(x) # population SD, as glmnet's standardize = TRUE
xs <- st$x
# %% Regularization path and cross-validation (glmnet on the standardized design)
alpha <- 1
nfold <- as.integer(10)
cs_check_rows(n, nfold, sprintf("%d-fold cross-validation", nfold)) # every fold needs a row to predict (same check in Python)
nlambda <- as.integer(100)
rule <- "1se"
seed <- 42 # shared Wichmann–Hill stream: the same folds in Python and R
lambdas <- cs_sel_lambda_grid(xs, y, alpha, nlambda)
ctrl <- list(thresh = 1e-20, maxit = 1e8, fdev = 0, devmax = 1)
pad <- function(m) if (ncol(m) == 1L) cbind(m, 0) else m # glmnet needs two columns
path_of <- function(xtr, ytr) {
fit <- if (family == "gaussian") {
g <- cs_ml_glmnet_gaussian_args(ytr, NULL, lambdas, alpha) # glmnet standardizes y: map to the (1/2n)·RSS objective
glmnet(pad(xtr), ytr, family = "gaussian", alpha = g$alpha, lambda = g$lambda, standardize = FALSE, control = ctrl)
} else {
glmnet(pad(xtr), ytr, family = "binomial", alpha = alpha, lambda = lambdas, standardize = FALSE, control = ctrl)
}
cf <- as.matrix(stats::coef(fit)) # (1 + p) x L
list(b0 = cf[1, ], b = cf[1 + seq_len(p), , drop = FALSE])
}
fold <- cs_sel_folds(n, nfold, seed)
fold_loss <- matrix(0, nfold, length(lambdas))
fold_n <- numeric(nfold)
for (f in seq_len(nfold)) {
tr <- fold != f
te <- fold == f
pf <- path_of(xs[tr, , drop = FALSE], y[tr])
eta <- sweep(xs[te, , drop = FALSE] %*% pf$b, 2, pf$b0, "+")
pred <- if (family == "gaussian") eta else 1 / (1 + exp(-eta))
fold_loss[f, ] <- colMeans(cs_sel_loss(y[te], pred, family))
fold_n[f] <- sum(te)
}
cv <- cs_sel_cv_summary(fold_loss, fold_n)
full <- path_of(xs, y)
i <- if (rule == "1se") cv$i1se else cv$imin
bstd <- full$b[, i]
coef <- ifelse(st$sd > 0, bstd / ifelse(st$sd > 0, st$sd, 1), 0) # back to the original scale
intercept <- unname(full$b0[i] - sum(coef * st$mean))
nonzero <- names_[coef != 0]
# %% Assumptions
assumptions <- list(
list(key = "no_inference", label = "Selection, not inference", status = "info",
detail = "Penalized coefficients are shrunk toward zero and have no valid p-values; estimate effects on new data."),
list(key = "scaling", label = "Standardized predictors", status = "pass", detail = "Columns were standardized before penalizing; coefficients are on the original scale.")
)
# %% Result
kind <- if (alpha == 1) "lasso" else if (alpha == 0) "ridge" else "elastic net"
values <- list(
n = n, n_columns = p, family = family, alpha = alpha, rule = rule,
lambda_max = lambdas[1], lambda_min = lambdas[cv$imin], lambda_1se = lambdas[cv$i1se],
lambda = lambdas[i], cvm_min = cv$cvm[cv$imin], cvm = cv$cvm[i], cvsd = cv$cvsd[i],
n_nonzero = length(nonzero), intercept = intercept, selected = if (length(nonzero)) paste(nonzero, collapse = ", ") else "(none)"
)
for (j in seq_len(p)) values[[sprintf("coef[%s]", names_[j])]] <- unname(coef[j])
err <- if (family == "gaussian") "mean squared error" else "binomial deviance"
loglam <- log(lambdas)
cs_publish(list(
method = "regression.penalized",
methodVersion = "1.0.1",
title = sprintf("Penalized regression (%s)", kind),
engine = cs_engine_info("glmnet", "nanoparquet"),
n = n,
summary = sprintf("%s with λ = %.4g (%s, %d-fold CV) keeps %d of %d columns: %s.", paste0(toupper(substr(kind, 1, 1)), substring(kind, 2)), lambdas[i],
if (rule == "1se") "one-SE rule" else "minimum CV error", nfold, length(nonzero), p, values$selected),
statistics = list(
list(key = "lambda", label = "Chosen λ", value = lambdas[i]),
list(key = "lambda_min", label = "λ (minimum CV error)", value = lambdas[cv$imin]),
list(key = "lambda_1se", label = "λ (one-SE rule)", value = lambdas[cv$i1se]),
list(key = "cvm", label = sprintf("CV %s at the chosen λ", err), value = cv$cvm[i])
),
tables = list(list(
key = "coefficients", title = sprintf("Coefficients at λ = %.4g (original scale)", lambdas[i]),
columns = list(list(key = "term", label = "Column", type = "string"), list(key = "b", label = "Coefficient", type = "number"),
list(key = "std", label = "Standardized", type = "number")),
rows = c(list(list(term = "(Intercept)", b = intercept, std = unname(full$b0[i]))),
lapply(seq_len(p), function(j) list(term = names_[j], b = unname(coef[j]), std = unname(bstd[j]))))
)),
assumptions = assumptions,
warnings = warnings,
notes = list(sprintf("Folds from seed %d; λ grid of %d values from λ_max = %.4g. Cross-validated %s.", seed, nlambda, lambdas[1], err)),
charts = list(
cs_chart("cv", "learning-curve", sprintf("Cross-validated %s by log(λ)", err),
list(n = cs_col("log(λ)", loglam), score = cs_col(err, cv$cvm), set = cs_col("set", rep("cross-validation", length(loglam))),
low = cs_col("low", cv$cvm - cv$cvsd), high = cs_col("high", cv$cvm + cv$cvsd))),
cs_chart("coefficients", "cleveland-dot", "Standardized coefficients at the chosen λ",
list(category = cs_col("column", names_), value = cs_col("standardized coefficient", unname(bstd))))
),
values = values
))
Sources
- Tibshirani, R. (1996). Regression shrinkage and selection via the lasso. JRSS B, 58, 267–288.
- Zou, H., & Hastie, T. (2005). Regularization and variable selection via the elastic net. JRSS B, 67, 301–320.
- Friedman, J., Hastie, T., & Tibshirani, R. (2010). Regularization paths for generalized linear models via coordinate descent. Journal of Statistical Software, 33(1).
From the CodeSplash method registry · regression.penalized v1.0.1.