Skip to content

Choosing predictors: penalized regression versus stepwise

Automated selection is seductive and dangerous. See what lasso, ridge and stepwise each do, why p-values after selection mislead, and when to use which.

Applied ~12 min11 steps

What runs in CodeSplash

You will be able to

  • Explain how a penalty shrinks coefficients
  • Compare lasso, ridge and elastic net
  • Choose λ with cross-validation and the one-standard-error rule
  • Explain why p-values after stepwise selection are too small

Read first

01

Too many candidates

Read

You have dozens of possible predictors and limited rows. Which should go in? Two families of automated answers exist.

Stepwise methods add or drop one term at a time, checking AIC or BIC at each step. Penalized methods keep every candidate, and shrink their coefficients toward zero by adding a cost to the fit.

Both are useful for prediction. Neither frees you from thinking about the question.

02

The penalty

Read

Penalized regression minimizes the usual error plus a cost on the coefficients:

∑i(yi−y^i)2+λ[α∑j∣βj∣+1−α2∑jβj2]\sum_i (y_i - \hat y_i)^2 + \lambda\Big[\alpha\sum_j |\beta_j| + \tfrac{1-\alpha}{2}\sum_j \beta_j^2\Big]

With α=1\alpha = 1 it's the lassoLassoPenalized regression that shrinks coefficients by their absolute size, setting some exactly to zero., which sets some coefficients exactly to zero. With α=0\alpha = 0 it's ridgeRidge regressionPenalized regression that shrinks coefficients by their squared size. It keeps every predictor and handles overlap well., which shrinks them all but keeps every one. In between is the elastic netElastic netPenalized regression that mixes the lasso and ridge penalties, so groups of correlated predictors tend to stay together.. Larger λ\lambda means more shrinkage.

03

Trace the paths

Explore

DExplorable · Regularization paths

What happens to each coefficient as the penalty gets stronger?

Three of the eight predictors really matter. How many coefficients will be exactly zero at this penalty?

4
How sure?

Penalty

−0.50
0.30
60
2.0
this penaltybest

Blue paths are the three predictors that matter; gray are the five that don't. Below, training error (orange) and new-data error (blue).

Commit your prediction above to see the result

Make your prediction first; the figure appears when you commit.

Make your prediction to see the result.

Slide λ\lambda up and watch coefficients shrink. Under lasso they hit zero one at a time. Under ridge they approach zero but never reach it. With two correlated predictors, lasso tends to keep one, and ridge splits the credit.

04

Choosing λ

Read

Cross-validation estimates prediction error for each λ\lambda. CodeSplash offers two ways to pick:

  • Minimum error: the λ\lambda with the lowest cross-validated error.
  • One standard error: the largest λ\lambda whose error is within one standard error of that minimum. It's simpler and nearly as good, so it's the default.

On Swiss fertility data, the minimum is at λ\lambda = 0.0008, and the one-standard-error rule picks 0.503. It keeps 5 of 5 predictors, all shrunk.

05

Make a prediction

Predict

Predict first

On the same data with the same five candidates, stepwise AIC, moving both ways. What does it do?

It keeps all fiveIt drops one or moreIt drops all five
Reveal

It keeps 4: agriculture, education, catholic, infant mortality. AIC moved from 190.7 to 189.9. A very small change, which means the two models are nearly tied and the choice between them is fragile.

06

What stepwise p-values really mean

Read

Stepwise selection and then reporting the final model as if you had planned it causes real trouble:

  • Standard errors are too small because the search isn't counted.
  • p-values are too small for the same reason.
  • Coefficients are biased away from zero: terms get picked when they happen to look large.
  • The selection is unstable: a slightly different sample picks different terms.

The same warnings apply to the lasso's chosen set: don't read a normal tt test or interval on it.

07

Read a selection

In the app
Stepwise linear regressionRecorded · Python and R agreeRecorded 2026-11-25 · 23 values compared
R

Backward selection by BIC kept 3 of 7 predictors: wt, qsec, am_f (BIC 78.7 → 67.2).

BIC of the starting model
78.695
BIC of the selected model
67.170

Plots

Selected model (intervals ignore the selection)How large are several estimates, how precise, and which exclude the null?
View data
estimatehightermlow
−3.917−2.460wt−5.373
1.2261.817qsec0.6346
2.9365.826am_f[manual]0.0457

Assumptions

  • Inference after selection — Standard errors, p-values and intervals below ignore the selection; they are too optimistic. Confirm on new data or use penalized regression.
  • Enough events per candidate — 4.6 observations per candidate predictor (≥ 10 recommended for a stable selection).

Selection path

StepChangeBIC
0(start)78.695
1- cyl_f73.717
2- drat70.956
3- disp68.844
4- hp67.170

Selected model

TermEstimateSEtp (unadjusted for selection)
(Intercept)9.6186.9601.3820.1779
wt−3.9170.7112−5.5076.953e-6
qsec1.2260.28874.2470.0002
am_f[manual]2.9361.4112.0810.0467
  • Stepwise selection is exploratory: the selected predictors, p-values and intervals are biased by the search. Treat the result as a hypothesis to confirm.
  • Linear model; criterion BIC with k = 3.466 (step / extractAIC).
The exact R script · R R version 4.5.1 (2025-06-13)
# Stepwise regression (AIC / BIC)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method regression.stepwise 1.0.1 · spec 567c3497e45824a0
# Dataset: mtcars (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.

# %% Setup
library(codesplashr) # cs_sel_coef_names (coefficient names shared with the Python twin)

# %% Data
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/mtcars.parquet", col_select = c("mpg", "cyl_f", "disp", "hp", "drat", "wt", "qsec", "am_f")))
n_input <- nrow(df)
df[["cyl_f"]] <- factor(df[["cyl_f"]], levels = c("4", "6", "8"))  # stored level order
df[["am_f"]] <- factor(df[["am_f"]], levels = c("automatic", "manual"))  # stored level order
df <- df[stats::complete.cases(df[c("mpg", "cyl_f", "disp", "hp", "drat", "wt", "qsec", "am_f")]), , 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("mpg", "cyl_f", "disp", "hp", "drat", "wt", "qsec", "am_f"))  # infinite values stop the run (registry/errors.yaml)

# %% Outcome and family
yname <- "mpg"
predictors <- c("cyl_f", "disp", "hp", "drat", "wt", "qsec", "am_f")
binary <- is.factor(df[[yname]])
family <- "auto"
if (family == "auto") family <- if (binary) "binomial" else "gaussian"
if (family == "binomial") {
  if (!binary) stop(sprintf("Logistic regression needs a yes/no outcome; %s is numeric", yname))
  ylev <- levels(df[[yname]])
  event <- ylev[length(ylev)]  # modeled level
  df$.y <- as.numeric(as.character(df[[yname]]) == event)
} else {
  if (binary) stop(sprintf("%s regression needs a numeric outcome", family))
  df$.y <- as.numeric(df[[yname]])
  if (family == "poisson" && (any(df$.y < 0) || any(df$.y != round(df$.y)))) stop(sprintf("Poisson regression needs whole-number counts ≥ 0 in %s", yname))
}
n <- nrow(df)
# Degenerate input stops with a catalog error; Python runs the same checks in the same order.
cs_check_rows(n, length(cs_design_labels(df, predictors)) + 1, "Stepwise selection")  # more rows than coefficients of the full model
for (col in c(yname, predictors)) cs_check_not_constant(df[[col]], col)  # one value (or one level with data) is no variation

# %% Selection with step() (k = 2 for AIC, log n for BIC)
direction <- "backward"
criterion <- "bic"
k <- if (criterion == "aic") 2 else log(n)
rhs <- paste(sprintf("`%s`", predictors), collapse = " + ")
fit_of <- function(f) {
  if (family == "gaussian") stats::lm(f, data = df)
  else stats::glm(f, family = family, data = df, control = stats::glm.control(epsilon = 1e-14, maxit = 100))
}
start <- fit_of(stats::as.formula(if (direction == "forward") ".y ~ 1" else paste(".y ~", rhs)))
fit <- stats::step(start, scope = list(lower = ~1, upper = stats::as.formula(paste("~", rhs))), direction = direction, k = k, trace = 0)
path <- fit$anova
final <- predictors[predictors %in% gsub("`", "", attr(stats::terms(fit), "term.labels"), fixed = TRUE)]

# %% Selected model
conf <- 0.95
names_ <- cs_sel_coef_names(fit)
coef <- unname(stats::coef(fit))
se <- sqrt(diag(stats::vcov(fit)))
stat <- coef / se
if (family == "gaussian") {
  dfree <- stats::df.residual(fit)
  pval <- 2 * stats::pt(-abs(stat), dfree)
  crit <- stats::qt(1 - (1 - conf) / 2, dfree)
} else {
  pval <- 2 * stats::pnorm(-abs(stat))
  crit <- stats::qnorm(1 - (1 - conf) / 2)
}

# %% Assumptions
events <- if (family == "binomial") min(sum(df$.y), n - sum(df$.y)) else n
epv <- events / max(length(predictors), 1)
assumptions <- list(
  list(key = "selection_bias", label = "Inference after selection", status = "warn",
       detail = "Standard errors, p-values and intervals below ignore the selection; they are too optimistic. Confirm on new data or use penalized regression."),
  list(key = "epv", label = "Enough events per candidate", status = if (epv >= 10) "pass" else "warn",
       detail = sprintf("%.1f %s per candidate predictor (≥ 10 recommended for a stable selection).", epv, if (family == "binomial") "events" else "observations"))
)
warnings <- c(warnings, "Stepwise selection is exploratory: the selected predictors, p-values and intervals are biased by the search. Treat the result as a hypothesis to confirm.")

# %% Result
label <- c(gaussian = "Linear", binomial = "Logistic", poisson = "Poisson")[[family]]
crit_name <- toupper(criterion)
crit_path <- path$AIC
values <- list(
  n = n, family = family, direction = direction, criterion = criterion, k_penalty = k,
  n_steps = nrow(path) - 1L, criterion_start = crit_path[1], criterion_final = crit_path[length(crit_path)],
  selected = if (length(final)) paste(final, collapse = ", ") else "(intercept only)", n_selected = length(final), n_candidates = length(predictors)
)
for (i in seq_along(names_)) {
  values[[sprintf("coef[%s]", names_[i])]] <- coef[i]
  values[[sprintf("se[%s]", names_[i])]] <- se[i]
  values[[sprintf("p[%s]", names_[i])]] <- pval[i]
}
changes <- gsub("`", "", as.character(path$Step), fixed = TRUE)
changes[1] <- "(start)"
eff <- seq_along(names_)[-1]
cs_publish(list(
  method = "regression.stepwise",
  methodVersion = "1.0.1",
  title = sprintf("Stepwise %s regression", tolower(label)),
  engine = cs_engine_info("stats", "nanoparquet"),
  n = n,
  summary = sprintf("%s selection by %s kept %d of %d predictors: %s (%s %.1f → %.1f).", paste0(toupper(substr(direction, 1, 1)), substring(direction, 2)),
                    crit_name, length(final), length(predictors), values$selected, crit_name, values$criterion_start, values$criterion_final),
  statistics = list(
    list(key = "criterion_start", label = sprintf("%s of the starting model", crit_name), value = values$criterion_start),
    list(key = "criterion_final", label = sprintf("%s of the selected model", crit_name), value = values$criterion_final)
  ),
  tables = list(
    list(key = "path", title = "Selection path",
         columns = list(list(key = "step", label = "Step", type = "integer"), list(key = "change", label = "Change", type = "string"),
                        list(key = "criterion", label = crit_name, type = "number")),
         rows = lapply(seq_len(nrow(path)), function(i) list(step = i - 1L, change = changes[i], criterion = crit_path[i]))),
    list(key = "coefficients", title = "Selected model",
         columns = list(list(key = "term", label = "Term", type = "string"), list(key = "b", label = "Estimate", type = "number"),
                        list(key = "se", label = "SE", type = "number"), list(key = "stat", label = if (family == "gaussian") "t" else "z", type = "number"),
                        list(key = "p", label = "p (unadjusted for selection)", type = "number", format = "p")),
         rows = lapply(seq_along(names_), function(i) list(term = names_[i], b = coef[i], se = se[i], stat = stat[i], p = pval[i])))
  ),
  assumptions = assumptions,
  warnings = warnings,
  notes = list(sprintf("%s model; criterion %s with k = %.3f (step / extractAIC).", label, crit_name, k)),
  charts = if (length(eff)) list(cs_chart(
    "coefficients", "forest", "Selected model (intervals ignore the selection)",
    list(label = cs_col("term", names_[eff]), estimate = cs_col("estimate", coef[eff]),
         low = cs_col("low", coef[eff] - crit * se[eff]), high = cs_col("high", coef[eff] + crit * se[eff]))
  )) else list(),
  values = values
))
Python

Backward selection by BIC kept 3 of 7 predictors: wt, qsec, am_f (BIC 78.7 → 67.2).

BIC of the starting model
78.695
BIC of the selected model
67.170

To keep this page light, the plots are shown once, under the R tab.

Assumptions

  • Inference after selection — Standard errors, p-values and intervals below ignore the selection; they are too optimistic. Confirm on new data or use penalized regression.
  • Enough events per candidate — 4.6 observations per candidate predictor (≥ 10 recommended for a stable selection).

Selection path

StepChangeBIC
0(start)78.695
1- cyl_f73.717
2- drat70.956
3- disp68.844
4- hp67.170

Selected model

TermEstimateSEtp (unadjusted for selection)
(Intercept)9.6186.9601.3820.1779
wt−3.9170.7112−5.5076.953e-6
qsec1.2260.28874.2470.0002
am_f[manual]2.9361.4112.0810.0467
  • Stepwise selection is exploratory: the selected predictors, p-values and intervals are biased by the search. Treat the result as a hypothesis to confirm.
  • Linear model; criterion BIC with k = 3.466 (R's step / extractAIC).
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Stepwise regression (AIC / BIC)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method regression.stepwise 1.0.1 · spec 567c3497e45824a0
# Dataset: mtcars (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
from scipy import stats

import codesplash as cs
from codesplash.errors import check_not_constant
from codesplash.stats import selection as sel  # twin of R's step() (codesplashr: step() itself)

# %% Data
df = pd.read_parquet("tests/parity/fixtures/mtcars.parquet", columns=["mpg", "cyl_f", "disp", "hp", "drat", "wt", "qsec", "am_f"])
n_input = len(df)
df["cyl_f"] = pd.Categorical(df["cyl_f"], categories=["4", "6", "8"])  # stored level order
df["am_f"] = pd.Categorical(df["am_f"], categories=["automatic", "manual"])  # stored level order
df = df.dropna(subset=["mpg", "cyl_f", "disp", "hp", "drat", "wt", "qsec", "am_f"])  # listwise deletion over the analysis columns
df["cyl_f"] = df["cyl_f"].cat.remove_unused_categories()
df["am_f"] = df["am_f"].cat.remove_unused_categories()
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, ["mpg", "cyl_f", "disp", "hp", "drat", "wt", "qsec", "am_f"])  # infinite values stop the run (registry/errors.yaml)

# %% Outcome and family
yname = "mpg"
predictors = ["cyl_f", "disp", "hp", "drat", "wt", "qsec", "am_f"]
kinds = {"am_f":"categorical","cyl_f":"categorical","disp":"numeric","drat":"numeric","hp":"numeric","mpg":"numeric","qsec":"numeric","wt":"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 regression needs 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"{family} regression needs a numeric outcome")
    y = df[yname].to_numpy(dtype=float)
    if family == "poisson" and (np.any(y < 0) or np.any(y != np.round(y))):
        raise ValueError(f"Poisson regression needs whole-number counts ≥ 0 in {yname}")
n = len(y)
levels = {p: ([str(v) for v in df[p].cat.categories] if kinds[p] in ("categorical", "boolean") else None) for p in predictors}
# Degenerate input stops with a catalog error; R runs the same checks in the same order.
k_full = sel.design(df, predictors, levels)[0].shape[1]
cs.check_rows(n, k_full + 1, "Stepwise selection")  # more rows than coefficients of the full model
for col in [yname] + predictors:
    check_not_constant(df[col], col)  # one value (or one level with data) is no variation

# %% Selection (R's step(): k = 2 for AIC, log n for BIC)
direction = "backward"
criterion = "bic"
k = 2.0 if criterion == "aic" else math.log(n)
start = [] if direction == "forward" else list(predictors)
res = sel.stepwise(df, y, start, predictors, levels, family, direction, k)
final = [p for p in predictors if p in res["terms"]]

# %% Selected model
x, names, _ = sel.design(df, res["terms"], levels)
fit = sel.fit_model(x, y, family)
coef = fit["coef"]
conf = 0.95
if family == "gaussian":
    dfree = n - fit["rank"]
    sigma2 = fit["rss"] / dfree
    cov = sigma2 * np.linalg.inv(x.T @ x)
    se = np.sqrt(np.diag(cov))
    stat = coef / se
    pval = 2 * stats.t.sf(np.abs(stat), dfree)
    crit = stats.t.ppf(1 - (1 - conf) / 2, dfree)
else:
    mu = fit["mu"]
    w = mu * (1 - mu) if family == "binomial" else mu
    cov = np.linalg.inv(x.T @ (x * w[:, None]))
    se = np.sqrt(np.diag(cov))
    stat = coef / se
    pval = 2 * stats.norm.sf(np.abs(stat))
    crit = stats.norm.ppf(1 - (1 - conf) / 2)

# %% Assumptions
events = int(min(y.sum(), n - y.sum())) if family == "binomial" else n
epv = events / max(len(predictors), 1)
assumptions = [
    {"key": "selection_bias", "label": "Inference after selection", "status": "warn",
     "detail": "Standard errors, p-values and intervals below ignore the selection; they are too optimistic. Confirm on new data or use penalized regression."},
    {"key": "epv", "label": "Enough events per candidate", "status": "pass" if epv >= 10 else "warn",
     "detail": f"{epv:.1f} {'events' if family == 'binomial' else 'observations'} per candidate predictor (≥ 10 recommended for a stable selection)."},
]
warnings.append("Stepwise selection is exploratory: the selected predictors, p-values and intervals are biased by the search. Treat the result as a hypothesis to confirm.")

# %% Result
label = {"gaussian": "Linear", "binomial": "Logistic", "poisson": "Poisson"}[family]
values = {
    "n": n, "family": family, "direction": direction, "criterion": criterion, "k_penalty": k,
    "n_steps": len(res["path"]) - 1, "criterion_start": res["start"], "criterion_final": res["criterion"],
    "selected": ", ".join(final) if final else "(intercept only)", "n_selected": len(final), "n_candidates": len(predictors),
}
for nm, b, s, pv in zip(names, coef, se, pval):
    values[f"coef[{nm}]"] = float(b)
    values[f"se[{nm}]"] = float(s)
    values[f"p[{nm}]"] = float(pv)
crit_name = criterion.upper()
eff = [i for i in range(1, len(names))]
cs.publish({
    "method": "regression.stepwise",
    "methodVersion": "1.0.1",
    "title": f"Stepwise {label.lower()} regression",
    "engine": cs.engine_info("pandas", "numpy", "scipy"),
    "n": n,
    "summary": f"{direction.capitalize()} selection by {crit_name} kept {len(final)} of {len(predictors)} predictors: {values['selected']} ({crit_name} {res['start']:.1f} → {res['criterion']:.1f}).",
    "statistics": [
        {"key": "criterion_start", "label": f"{crit_name} of the starting model", "value": res["start"]},
        {"key": "criterion_final", "label": f"{crit_name} of the selected model", "value": res["criterion"]},
    ],
    "tables": [
        {"key": "path", "title": "Selection path",
         "columns": [{"key": "step", "label": "Step", "type": "integer"}, {"key": "change", "label": "Change", "type": "string"},
                     {"key": "criterion", "label": crit_name, "type": "number"}],
         "rows": [{"step": s["step"], "change": s["change"], "criterion": s["criterion"]} for s in res["path"]]},
        {"key": "coefficients", "title": "Selected model",
         "columns": [{"key": "term", "label": "Term", "type": "string"}, {"key": "b", "label": "Estimate", "type": "number"},
                     {"key": "se", "label": "SE", "type": "number"}, {"key": "stat", "label": "t" if family == "gaussian" else "z", "type": "number"},
                     {"key": "p", "label": "p (unadjusted for selection)", "type": "number", "format": "p"}],
         "rows": [{"term": nm, "b": float(b), "se": float(s), "stat": float(t), "p": float(pv)} for nm, b, s, t, pv in zip(names, coef, se, stat, pval)]},
    ],
    "assumptions": assumptions,
    "warnings": warnings,
    "notes": [f"{label} model; criterion {crit_name} with k = {k:.3f} (R's step / extractAIC)."],
    "charts": [cs.chart(
        "coefficients", "forest", "Selected model (intervals ignore the selection)",
        {"label": cs.col("term", [names[i] for i in eff]), "estimate": cs.col("estimate", [float(coef[i]) for i in eff]),
         "low": cs.col("low", [float(coef[i] - crit * se[i]) for i in eff]), "high": cs.col("high", [float(coef[i] + crit * se[i]) for i in eff])},
    )] if eff else [],
    "values": values,
})

Backward BIC on mtcars keeps wt, qsec, am_f from 7 candidates. A result like this is a hypothesis to check on new data, not a finding.

08

Which to use?

Reflect
GoalApproach
Test a hypothesisDecide the model beforehand; no automated selection
Predict wellLasso or elastic net, judged on held-out data
Handle correlated predictorsRidge or elastic net
Screen variables to study nextLasso, then confirm on fresh data

Which of these is your goal? If you can't say, that's worth settling before you run anything.

09

Check your understanding

Checkpoint

Check yourself

What's the key practical difference between lasso and ridge?

Show the answer

Answer: a

The absolute-value penalty has corners at zero, which lets the lasso remove terms. Ridge's squared penalty doesn't.

Check yourself

Why should predictors be on comparable scales before a penalized fit?

Show the answer

Answer: a

A predictor in millimeters would have a tiny coefficient and pay almost no penalty. Software standardizes internally for this reason.

Check yourself

A stepwise search over 30 candidates keeps 4 terms, each with p < .01. How should you read those p-values?

Show the answer

Answer: b

Picking the best-looking terms out of 30 inflates them. Even pure noise can produce four terms that look like this.

10

Try both

In the app

Add your candidates. For the penalized method, set Lasso share α and Choose λ by. For stepwise, set Direction and Criterion. Compare which terms each keeps.

Python
import pandas as pd
from sklearn.linear_model import LassoCV
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler

df = pd.read_csv("mtcars.csv")
X = df[["cyl", "disp", "hp", "drat", "wt", "qsec"]]
model = make_pipeline(StandardScaler(), LassoCV(cv=5, random_state=1)).fit(X, df["mpg"])
print(dict(zip(X.columns, model[-1].coef_.round(3))), model[-1].alpha_)
R
# install.packages("glmnet")
library(glmnet)
df <- read.csv("mtcars.csv")
X <- as.matrix(df[, c("cyl", "disp", "hp", "drat", "wt", "qsec")])
set.seed(1)
cv <- cv.glmnet(X, df$mpg, alpha = 1, nfolds = 5)
coef(cv, s = "lambda.1se")
11

Recap

Recap
  • Penalties shrink coefficients. Lasso zeroes some, ridge zeroes none, and elastic net sits between.
  • Choose λ\lambda with cross-validation; the one-standard-error rule favors simplicity.
  • Standard p-values after any selection are too small.
  • Use selection to predict or to screen. Don't use it to confirm a hypothesis.

Concepts in this lesson