Skip to content

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.

Verified in Python and R Python and R agree to 6 decimals

A real result

Example “Swiss lasso”, recorded in both engines. In the app, “Try this example” loads it into Analyze.

Penalized regression (lasso)Recorded · Python and R agreeRecorded 2026-11-25 · 20 values compared
R

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

Cross-validated mean squared error by log(λ)Would more data help, or is the model limited by bias or variance?
View data
highlowlog(λ)mean squared errorset
212.98107.112.105160.04cross-validation
209.82104.122.011156.97cross-validation
205.45100.611.918153.03cross-validation
200.8396.6841.825148.76cross-validation
193.2293.4331.732143.33cross-validation
186.0190.7771.639138.39cross-validation
179.9088.7711.546134.34cross-validation
173.4286.6201.453130.02cross-validation
167.3584.6541.360126.00cross-validation
161.5182.3081.267121.91cross-validation
155.8979.5641.174117.73cross-validation
150.9777.2821.081114.13cross-validation
145.7274.8250.9881110.27cross-validation
141.2372.8330.8951107.03cross-validation
137.3971.2250.8020104.31cross-validation
133.7469.7010.7090101.72cross-validation
130.2168.1660.616099.186cross-validation
127.1966.8990.522997.044cross-validation
124.6165.8550.429995.235cross-validation
120.6364.9880.336992.808cross-validation
114.8464.2510.243889.547cross-validation
109.9063.6260.150886.761cross-validation
105.7663.1950.057884.479cross-validation
102.2062.769−0.035382.484cross-validation
98.81562.050−0.128380.432cross-validation
95.02261.214−0.221378.118cross-validation
91.85760.508−0.314476.183cross-validation
89.21959.907−0.407474.563cross-validation
87.02259.390−0.500473.206cross-validation
84.66658.744−0.593571.705cross-validation
82.61458.168−0.686570.391cross-validation
80.88057.672−0.779569.276cross-validation
79.41357.241−0.872668.327cross-validation
78.17256.866−0.965667.519cross-validation
77.12256.538−1.05966.830cross-validation
76.23356.248−1.15266.241cross-validation
75.48055.993−1.24565.736cross-validation
74.84055.766−1.33865.303cross-validation
74.29755.565−1.43164.931cross-validation
73.83455.386−1.52464.610cross-validation
73.44055.226−1.61764.333cross-validation
73.10455.084−1.71064.094cross-validation
72.81554.957−1.80363.886cross-validation
72.56854.843−1.89663.705cross-validation
72.35654.741−1.98963.548cross-validation
72.17354.649−2.08263.411cross-validation
72.01554.567−2.17563.291cross-validation
71.87854.494−2.26863.186cross-validation
71.76054.427−2.36163.094cross-validation
71.65754.368−2.45463.012cross-validation
71.56754.315−2.54762.941cross-validation
71.48854.266−2.64062.877cross-validation
71.41954.223−2.73362.821cross-validation
71.35954.184−2.82662.772cross-validation
71.30654.149−2.91962.727cross-validation
71.25954.117−3.01262.688cross-validation
71.21854.088−3.10562.653cross-validation
71.18154.062−3.19862.622cross-validation
71.14954.039−3.29162.594cross-validation
71.12054.018−3.38462.569cross-validation

First 60 of 100 rows.

Standardized coefficients at the chosen λHow do categories compare on one value — and across up to three groups?
View data
columnstandardized coefficient
agriculture−1.866
examination−1.548
education−6.974
catholic3.480
infant mortality3.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)

ColumnCoefficientStandardized
(Intercept)61.04670.143
agriculture−0.0831−1.866
examination−0.1961−1.548
education−0.7331−6.974
catholic0.08443.480
infant mortality1.0593.051
  • Folds from seed 42; λ grid of 100 values from λ_max = 8.203. Cross-validated mean squared error.
Python

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)

ColumnCoefficientStandardized
(Intercept)61.04670.143
agriculture−0.0831−1.866
examination−0.1961−1.548
education−0.7331−6.974
catholic0.08443.480
infant mortality1.0593.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 λ.
Python

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,
})
R

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.