DRegression models · regression.stepwise
Stepwise regression (AIC / BIC)
Which subset of candidate predictors gives the most parsimonious model by AIC or BIC?
Forward, backward or bidirectional selection of predictors for a linear, logistic or Poisson model by AIC or BIC, exactly as R's step(): every move (drop one term, add one term) is scored and the best is taken until no move improves the criterion. Shows the selection path and the selected model — with a warning that p-values and intervals after selection are too optimistic.
A real result
Example “Swiss both aic”, recorded in both engines. In the app, “Try this example” loads it into Analyze.
Both selection by AIC kept 4 of 5 predictors: agriculture, education, catholic, infant mortality (AIC 190.7 → 189.9).
- AIC of the starting model
- 190.69
- AIC of the selected model
- 189.86
Plots
View data
| estimate | high | term | low |
|---|---|---|---|
| −0.1546 | −0.0170 | agriculture | −0.2922 |
| −0.9803 | −0.6813 | education | −1.279 |
| 0.1247 | 0.1830 | catholic | 0.0664 |
| 1.078 | 1.849 | infant mortality | 0.3078 |
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 — 9.4 observations per candidate predictor (≥ 10 recommended for a stable selection).
Selection path
| Step | Change | AIC |
|---|---|---|
| 0 | (start) | 190.69 |
| 1 | - examination | 189.86 |
Selected model
| Term | Estimate | SE | t | p (unadjusted for selection) |
|---|---|---|---|---|
| (Intercept) | 62.101 | 9.605 | 6.466 | 8.492e-8 |
| agriculture | −0.1546 | 0.0682 | −2.267 | 0.0286 |
| education | −0.9803 | 0.1481 | −6.617 | 5.140e-8 |
| catholic | 0.1247 | 0.0289 | 4.315 | 9.503e-5 |
| infant mortality | 1.078 | 0.3819 | 2.824 | 0.0072 |
- 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 AIC with k = 2.000 (step / extractAIC).
Both selection by AIC kept 4 of 5 predictors: agriculture, education, catholic, infant mortality (AIC 190.7 → 189.9).
- AIC of the starting model
- 190.69
- AIC of the selected model
- 189.86
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 — 9.4 observations per candidate predictor (≥ 10 recommended for a stable selection).
Selection path
| Step | Change | AIC |
|---|---|---|
| 0 | (start) | 190.69 |
| 1 | - examination | 189.86 |
Selected model
| Term | Estimate | SE | t | p (unadjusted for selection) |
|---|---|---|---|---|
| (Intercept) | 62.101 | 9.605 | 6.466 | 8.492e-8 |
| agriculture | −0.1546 | 0.0682 | −2.267 | 0.0286 |
| education | −0.9803 | 0.1481 | −6.617 | 5.140e-8 |
| catholic | 0.1247 | 0.0289 | 4.315 | 9.503e-5 |
| infant mortality | 1.078 | 0.3819 | 2.824 | 0.0072 |
- 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 AIC with k = 2.000 (R's step / extractAIC).
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 both aics4_swiss · outcome: fertility · predictors: agriculture, examination, education, catholic, infant mortality
- Mtcars backward bicmtcars · outcome: mpg · predictors: cyl_f, disp, hp, drat, wt, qsec, am_f
- Birthwt logisticbirthwt · outcome: low · predictors: age, mother weight (lb), race, smoke, ptl, ht, ui, ftv
- Quine poisson forwardquine · outcome: Days · predictors: Eth, Sex, Age, Lrn
- Degenerate constants4_swiss · outcome: fertility · predictors: agriculture, examination, education, catholic, infant mortality
- 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
What you need
- Outcomenumeric / boolean / categorical · 1 column · 2–2 levels
- A numeric outcome (linear or Poisson) or a yes/no outcome (logistic).
- Candidate predictorsnumeric / categorical / boolean · 1–30 columns · 2–30 levels
- Candidate predictors the search may add or drop.
Choices you make
statistics
- Modeldefault auto
Model type to select terms for. Automatic picks linear or logistic 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 regression — Fits linear regression; pick it for a numeric outcome.
- Logistic regression — Fits logistic regression; pick it for a yes/no outcome.
- Poisson regression (counts) — Fits Poisson regression; pick it for count outcomes.
- Directiondefault both
Start from all predictors and drop, start from none and add, or allow both moves.
- Both (start from all predictors, drop or add)(default) — Starts with all predictors and can drop or re-add at each step; the usual choice.
- Backward (start from all predictors, drop) — Starts with all predictors and only drops; pick it when rows far outnumber predictors.
- Forward (start from the intercept, add) — Starts from the intercept and only adds; pick it when there are many predictors for the rows.
- Criteriondefault aic
AIC favors prediction; BIC penalizes extra terms more and gives smaller models.
- AIC (k = 2)(default) — Adds or drops terms by AIC (penalty 2 per coefficient); favors prediction and keeps more terms.
- BIC (k = log n) — Adds or drops terms by BIC (penalty log n per coefficient); favors smaller models, more so in large samples.
- Event leveldefault —
Logistic models: the outcome level modeled as the event (default the last stored level).
hypothesis
- Confidence leveldefault 0.95
How sure the intervals should be: 0.95 gives 95% confidence intervals. Higher confidence means wider intervals.
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.
Inference after selection
Standard errors, p-values and intervals of the selected model ignore that it was chosen from the data; they are too optimistic. Validate on new data or use penalized regression.
Enough events per candidate
With few observations (or events) per candidate predictor the selected set is unstable.
What it reports
- n
- 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.
- direction
- How the search moved: both (start full, drop or re-add), backward (start full, drop only) or forward (start empty, add).
- criterion
- Which information criterion guided the search: aic or bic. BIC's penalty, log(n), exceeds AIC's 2 in all but tiny samples.
- k_penalty
- Penalty added per estimated parameter: 2 for AIC, log(n) for BIC. A larger penalty favors smaller models.
- n_steps
- How many independent units the analysis used; it sets precision and power.
- criterion_start
- AIC or BIC of the model the search began from: all candidates (backward, both) or intercept only (forward). Lower is better.
- criterion_final
- AIC or BIC of the model the search ended with. Lower is better; compare it with the starting value.
- selected
- Comma-separated predictors in the final model, or (intercept only) when none were kept.
- n_selected
- How many independent units the analysis used; it sets precision and power.
- n_candidates
- How many independent units the analysis used; it sets precision and power.
Per group, level or term: coef[<term>], se[<term>], p[<term>]
Python and R
Python and R agree to 6 decimals (relative tolerance 1e-8). Python uses pandas, numpy, scipy, codesplash; R uses stats, nanoparquet, codesplashr.
Default traps between the two languages
- R runs step(); Python runs a twin of step() (cs selection.stepwise) with the same candidate moves, ordering, tie rule and stopping rule. Criteria are R's extractAIC (lm: n·log(RSS/n) + k·edf; glm: −2·logLik + k·edf). GLMs are fitted by IRLS in both engines to R's deviance criterion at 1e-14.
The exact script CodeSplash ran for example “Swiss both aic” · 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 eb7b1925de2433bb
# 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
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/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 family
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 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 = "both"
criterion = "aic"
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,
})
The exact script CodeSplash ran for example “Swiss both aic” · 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 eb7b1925de2433bb
# Dataset: s4_swiss (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/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 family
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 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 <- "both"
criterion <- "aic"
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
))
Sources
- Venables, W. N., & Ripley, B. D. (2002). Modern Applied Statistics with S (4th ed.), §6.8. Springer.
- Harrell, F. E. (2015). Regression Modeling Strategies (2nd ed.), §4.3 (problems with stepwise selection). Springer.
From the CodeSplash method registry · regression.stepwise v1.0.1.