Marginal effects, predictions and their intervals
Coefficients are rarely what people ask about. Turn a model into changes in probability, adjusted means and predictions, and pick the interval that answers the question you were asked.
What runs in CodeSplash
- Logistic regression (binary outcome) Verified in Python and R
- Linear regression (OLS) Verified in Python and R
- Quantile regression Verified in Python and R
You will be able to
- Say why an odds ratio doesn't translate into one change in probability
- Read average marginal effects and estimated marginal means from a card
- Tell a confidence interval for the mean from a prediction interval for one new case
- Use quantile regression when the spread changes with the predictors
Read first
Same odds ratio, different effect
PredictPredict first
A treatment has an odds ratio of 2. In one group, the baseline risk is 50%. In another, it's 1%. Where does the risk change more, in percentage points?
Reveal
At 50%: odds of 1 become 2, so risk goes to , up about 17 points. At 1%: odds of about double, so risk goes to about 2%, up about 1 point. One odds ratio, two very different changes.
See it on the curve
ExploreDExplorable · GLM link functions
If a coefficient is constant on the link scale, what does it mean on the probability scale?
How much does one more unit of x change the probability here?
Link
Commit your prediction above to see the result
Make your prediction to see the result.
Keep Slope fixed and drag At x. The odds ratio doesn't move, but the change in probability does: it's largest near the middle of the curve and small near either end.
So "what does one more unit do to the probability?" has no single answer. You have to say at which rows.
Average marginal effects
ReadAn average marginal effectAverage marginal effectThe change in predicted probability per unit of x, worked out for each row and then averaged. answers it by averaging. For every row in your data, work out how much a small change in moves that row's predicted probability, then take the mean.
χ²(6, N = 189) = 26.79, p < .001, Nagelkerke R² = .19
- LR χ²
- 26.794
- p
- < .001
- AUC
- 0.7173
- Nagelkerke R²
- 0.1859
- AIC
- 221.88
Effect size
- AUC (C statistic) 0.7173
- Nagelkerke R² 0.1859
- Tjur R² 0.1335
Plots
View data
| False-positive rate | True-positive rate |
|---|---|
| 0 | 0 |
| 0.0077 | 0 |
| 0.0077 | 0.0169 |
| 0.0077 | 0.0339 |
| 0.0077 | 0.0508 |
| 0.0077 | 0.0678 |
| 0.0077 | 0.0847 |
| 0.0154 | 0.0847 |
| 0.0154 | 0.1017 |
| 0.0154 | 0.1186 |
| 0.0154 | 0.1356 |
| 0.0154 | 0.1525 |
| 0.0154 | 0.1695 |
| 0.0154 | 0.1864 |
| 0.0231 | 0.1864 |
| 0.0231 | 0.2034 |
| 0.0308 | 0.2034 |
| 0.0385 | 0.2034 |
| 0.0462 | 0.2034 |
| 0.0462 | 0.2203 |
| 0.0538 | 0.2203 |
| 0.0538 | 0.2373 |
| 0.0538 | 0.2542 |
| 0.0538 | 0.2712 |
| 0.0615 | 0.2712 |
| 0.0692 | 0.2712 |
| 0.0769 | 0.2712 |
| 0.0846 | 0.2712 |
| 0.1000 | 0.2712 |
| 0.1000 | 0.2881 |
| 0.1077 | 0.2881 |
| 0.1154 | 0.2881 |
| 0.1308 | 0.2881 |
| 0.1308 | 0.3051 |
| 0.1385 | 0.3051 |
| 0.1538 | 0.3051 |
| 0.1538 | 0.3220 |
| 0.1538 | 0.3390 |
| 0.1615 | 0.3390 |
| 0.1692 | 0.3390 |
| 0.1692 | 0.3559 |
| 0.1769 | 0.3559 |
| 0.1846 | 0.3559 |
| 0.1846 | 0.3729 |
| 0.1923 | 0.3729 |
| 0.1923 | 0.3898 |
| 0.1923 | 0.4068 |
| 0.2000 | 0.4068 |
| 0.2077 | 0.4068 |
| 0.2077 | 0.4237 |
| 0.2154 | 0.4237 |
| 0.2154 | 0.4407 |
| 0.2231 | 0.4407 |
| 0.2231 | 0.4576 |
| 0.2308 | 0.4576 |
| 0.2308 | 0.4746 |
| 0.2385 | 0.4746 |
| 0.2385 | 0.4915 |
| 0.2385 | 0.5085 |
| 0.2462 | 0.5085 |
First 60 of 181 rows.
View data
| n | Observed proportion | Predicted probability |
|---|---|---|
| 19 | 0 | 0.0688 |
| 19 | 0.2105 | 0.1189 |
| 19 | 0.2105 | 0.1715 |
| 19 | 0.1579 | 0.2488 |
| 19 | 0.3158 | 0.2948 |
| 18 | 0.2222 | 0.3233 |
| 19 | 0.5789 | 0.3568 |
| 19 | 0.4737 | 0.3979 |
| 19 | 0.2632 | 0.4748 |
| 19 | 0.6842 | 0.6668 |
View data
| Odds ratio | high | Term | low |
|---|---|---|---|
| 0.9791 | 1.048 | age | 0.9142 |
| 0.9829 | 0.9962 | mother weight (lb) | 0.9697 |
| 3.451 | 9.681 | race: black | 1.230 |
| 2.507 | 5.791 | race: other | 1.085 |
| 2.900 | 6.218 | smoke: true | 1.352 |
| 5.657 | 21.787 | ht: true | 1.469 |
Assumptions
- No separation — No fitted probability is numerically 0 or 1.
- Events per variable — 59 events of the rarer outcome for 6 slope(s): 9.8 per variable (≥ 10 recommended).
- Multicollinearity — Largest VIF 1.21 (mother weight (lb)), from the predictors' correlations.
- Calibration — Hosmer–Lemeshow χ²(8) = 12.83, p = .118 over 10 risk groups.
- Linearity in the logit — Numeric predictors act linearly on the log odds; add a squared term or interaction if a smooth plot of the residuals bends.
Coefficients (log odds) and odds ratios
| Term | B | SE | z | p | Odds ratio | 95% CI low | 95% CI high |
|---|---|---|---|---|---|---|---|
| (Intercept) | 0.7773 | 1.160 | 0.6699 | .503 | 2.176 | 0.2238 | 21.147 |
| age | −0.0212 | 0.0350 | −0.6054 | .545 | 0.9791 | 0.9142 | 1.048 |
| mother weight (lb) | −0.0173 | 0.0069 | −2.519 | .012 | 0.9829 | 0.9697 | 0.9962 |
| race: black | 1.239 | 0.5263 | 2.354 | .019 | 3.451 | 1.230 | 9.681 |
| race: other | 0.9191 | 0.4272 | 2.151 | .031 | 2.507 | 1.085 | 5.791 |
| smoke: true | 1.065 | 0.3892 | 2.736 | .006 | 2.900 | 1.352 | 6.218 |
| ht: true | 1.733 | 0.6879 | 2.519 | .012 | 5.657 | 1.469 | 21.787 |
Modeled event: low = true; Wald intervals; Wald z tests.
Average marginal effects (probability scale)
| Predictor | AME | SE | p | 95% CI low | 95% CI high |
|---|---|---|---|---|---|
| age | −0.0039 | 0.0065 | .544 | −0.0166 | 0.0088 |
| mother weight (lb) | −0.0032 | 0.0012 | .008 | −0.0056 | −0.0009 |
Average over the rows of the change in P(event) per one-unit increase (delta-method SEs).
Classification at p ≥ 0.5
| Observed | Predicted true | Predicted other |
|---|---|---|
| true | 16 | 43 |
| false | 8 | 122 |
Accuracy 73.0%, sensitivity 27.1%, specificity 93.8%.
Hosmer–Lemeshow risk groups
| Group | n | Observed events | Expected events |
|---|---|---|---|
| 1 | 19 | 0 | 1.307 |
| 2 | 19 | 4 | 2.259 |
| 3 | 19 | 4 | 3.259 |
| 4 | 19 | 3 | 4.726 |
| 5 | 19 | 6 | 5.601 |
| 6 | 18 | 4 | 5.819 |
| 7 | 19 | 11 | 6.779 |
| 8 | 19 | 9 | 7.560 |
| 9 | 19 | 5 | 9.021 |
| 10 | 19 | 13 | 12.668 |
- Maximum likelihood (IRLS); logit link; P(low = true) modeled; categorical predictors against their first level; AUC is apparent (not cross-validated).
The exact R script · R R version 4.5.1 (2025-06-13)
# Logistic regression (binary outcome)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method regression.logistic 2.0.2 · spec d91d02049e4e7c5a
# Dataset: birthwt (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
library(codesplashr)
# %% Data
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/birthwt.parquet", col_select = c("low", "age", "mother weight (lb)", "race", "smoke", "ht")))
n_input <- nrow(df)
df[["low"]] <- factor(df[["low"]], levels = c("false", "true")) # stored level order
df[["race"]] <- factor(df[["race"]], levels = c("white", "black", "other")) # stored level order
df[["smoke"]] <- factor(df[["smoke"]], levels = c("false", "true")) # stored level order
df[["ht"]] <- factor(df[["ht"]], levels = c("false", "true")) # stored level order
df <- df[stats::complete.cases(df[c("low", "age", "mother weight (lb)", "race", "smoke", "ht")]), , 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("low", "age", "mother weight (lb)", "race", "smoke", "ht")) # infinite values stop the run (registry/errors.yaml)
# %% Outcome and model
outcome <- "low"
predictors <- c("age", "mother weight (lb)", "race", "smoke", "ht")
conf <- 0.95
interactions <- "none" # none | first-two | all-pairs
ci_method <- "wald" # wald | profile
threshold <- 0.5
levels_y <- levels(df[[outcome]])
if (length(levels_y) != 2) cs_error("CS_E_GROUP_COUNT", column = outcome, expected = 2, k = length(levels_y))
event <- levels_y[2] # default: the second stored level ("true" for yes/no)
if (!(event %in% levels_y)) cs_error("CS_E_NOT_A_LEVEL", level = event, column = outcome)
data <- df
data[[".event"]] <- as.numeric(as.character(df[[outcome]]) == event)
y <- data[[".event"]]
# Degenerate input stops with a catalog error; Python runs the same checks in the same order.
cs_check_rows(nrow(df), length(cs_design_labels(df, predictors, interactions)) + 1, "Logistic regression") # more rows than coefficients
for (p in predictors) cs_check_not_constant(df[[p]], p) # one value (or one level with data) is no variation
# Treatment contrasts: the first stored level of each categorical predictor is the reference.
fml <- cs_model_formula(".event", predictors, interactions)
# Maximum likelihood by IRLS with a tight convergence tolerance; separation is reported below.
fit <- suppressWarnings(glm(fml, family = binomial(), data = data, control = glm.control(epsilon = 1e-12, maxit = 200)))
# polish: one more IRLS pass from the converged coefficients, so vcov uses their working weights
if (!anyNA(coef(fit))) fit <- suppressWarnings(glm(fml, family = binomial(), data = data, start = coef(fit), control = glm.control(epsilon = 1e-12, maxit = 200)))
if (anyNA(coef(fit))) cs_error("CS_E_COLLINEAR")
X <- model.matrix(fit)
terms <- cs_design_labels(df, predictors, interactions)
stopifnot(length(terms) == ncol(X))
colnames(X) <- terms
n <- nrow(X)
k <- ncol(X)
b <- setNames(coef(fit), terms)
V <- vcov(fit)
dimnames(V) <- list(terms, terms)
se <- sqrt(diag(V))
z <- b / se
pval <- 2 * pnorm(abs(z), lower.tail = FALSE)
zc <- qnorm(1 - (1 - conf) / 2)
log_lik <- as.numeric(logLik(fit))
deviance <- -2 * log_lik
ci <- if (ci_method == "profile") cs_logistic_profile_ci(X, y, b, se, deviance, conf) else cbind(b - zc * se, b + zc * se)
n_events <- sum(y)
pbar <- n_events / n
null_log_lik <- n_events * log(pbar) + (n - n_events) * log(1 - pbar)
lr_chi2 <- 2 * (log_lik - null_log_lik)
lr_df <- k - 1
lr_p <- pchisq(lr_chi2, lr_df, lower.tail = FALSE)
mcfadden <- 1 - log_lik / null_log_lik
cox_snell <- 1 - exp(2 * (null_log_lik - log_lik) / n)
nagelkerke <- cox_snell / (1 - exp(2 * null_log_lik / n))
phat <- plogis(drop(X %*% b))
# Rounded to 12 decimals before ranking and grouping, so near-ties are ties in both engines.
phat_r <- round(phat, 12)
tjur <- mean(phat[y == 1]) - mean(phat[y == 0])
aic <- -2 * log_lik + 2 * k
bic <- -2 * log_lik + log(n) * k
auc <- cs_auc(y, phat_r)
hl <- cs_hosmer_lemeshow(y, phat_r, as.integer(10))
pred <- phat_r >= threshold
tp <- sum(pred & y == 1)
fn <- sum(!pred & y == 1)
tn <- sum(!pred & y == 0)
fp <- sum(pred & y == 0)
accuracy <- (tp + tn) / n
sensitivity <- tp / (tp + fn)
specificity <- tn / (tn + fp)
# %% Average marginal effects (numeric predictors outside interactions)
values <- list()
ame_rows <- list()
if (TRUE) {
in_interaction <- predictors[unique(unlist(cs_interaction_pairs(length(predictors), interactions)))]
for (p in predictors) {
if (is.factor(df[[p]]) || p %in% in_interaction) next
j <- match(p, terms)
a <- cs_logistic_ame(X, b, V, j)
row <- list(term = p, ame = unname(a["ame"]), se = unname(a["se"]), ci_low = unname(a["ame"] - zc * a["se"]),
ci_high = unname(a["ame"] + zc * a["se"]), p = 2 * pnorm(abs(a[["ame"]] / a[["se"]]), lower.tail = FALSE))
ame_rows[[length(ame_rows) + 1]] <- row
values[[sprintf("ame[%s]", p)]] <- row$ame
values[[sprintf("ame_se[%s]", p)]] <- row$se
values[[sprintf("ame_ci_low[%s]", p)]] <- row$ci_low
values[[sprintf("ame_ci_high[%s]", p)]] <- row$ci_high
}
}
# %% Assumptions
assumptions <- list()
add_assumption <- function(a) assumptions[[length(assumptions) + 1]] <<- a
n_extreme <- sum(phat < 1e-8 | phat > 1 - 1e-8)
add_assumption(list(key = "separation", label = "No separation", status = if (n_extreme > 0) "warn" else "pass", statistic = n_extreme,
detail = if (n_extreme > 0) sprintf("%d row(s) have fitted probabilities numerically 0 or 1: a predictor (nearly) separates the outcomes, so some estimates and standard errors are unreliable; consider fewer predictors or Firth's penalized likelihood.", n_extreme)
else "No fitted probability is numerically 0 or 1."))
epv <- min(n_events, n - n_events) / max(k - 1, 1)
add_assumption(list(key = "sample_size", label = "Events per variable", status = if (epv >= 10) "pass" else if (epv >= 5) "warn" else "fail", statistic = epv,
detail = paste0(sprintf("%d events of the rarer outcome for %d slope(s): %.1f per variable", min(n_events, n - n_events), k - 1, epv),
if (epv < 10) " (≥ 10 recommended)." else ".")))
main_cols <- terms[-1][!grepl(" × ", terms[-1], fixed = TRUE)]
vifs <- cs_gvif(X, main_cols, df, predictors) # one generalized VIF per factor
max_vif <- NULL
if (length(vifs)) {
max_vif <- max(vifs)
add_assumption(list(key = "multicollinearity", label = "Multicollinearity", status = if (max_vif < 5) "pass" else if (max_vif < 10) "warn" else "fail",
statistic = max_vif, detail = sprintf("Largest VIF %.2f (%s), from the predictors' correlations.", max_vif, names(vifs)[which.max(vifs)])))
}
if (!is.null(hl$p)) {
add_assumption(list(key = "calibration", label = "Calibration", status = if (hl$p < 0.05) "warn" else "pass", statistic = hl$chi2, p = hl$p,
detail = sprintf("Hosmer–Lemeshow χ²(%d) = %.2f, %s over %d risk groups.", hl$df, hl$chi2, cs_fmt_p(hl$p), length(hl$groups))))
}
add_assumption(list(key = "linearity", label = "Linearity in the logit", status = "info",
detail = "Numeric predictors act linearly on the log odds; add a squared term or interaction if a smooth plot of the residuals bends."))
# %% Result
coefs <- lapply(seq_along(terms), function(j) list(term = terms[j], estimate = unname(b[j]), se = unname(se[j]), z = unname(z[j]), p = unname(pval[j]),
ci_low = unname(ci[j, 1]), ci_high = unname(ci[j, 2]), or = unname(exp(b[j])),
or_ci_low = unname(exp(ci[j, 1])), or_ci_high = unname(exp(ci[j, 2]))))
for (cf in coefs) {
for (pair in list(c("coef", "estimate"), c("se", "se"), c("z", "z"), c("p", "p"), c("ci_low", "ci_low"), c("ci_high", "ci_high"),
c("or", "or"), c("or_ci_low", "or_ci_low"), c("or_ci_high", "or_ci_high"))) {
values[[sprintf("%s[%s]", pair[1], cf$term)]] <- cf[[pair[2]]]
}
}
values <- c(values, list(n = n, n_events = n_events, k = k, event_level = event, log_lik = log_lik, null_log_lik = null_log_lik,
deviance = deviance, lr_chi2 = lr_chi2, lr_df = lr_df, lr_p = lr_p, mcfadden_r2 = mcfadden, cox_snell_r2 = cox_snell,
nagelkerke_r2 = nagelkerke, tjur_r2 = tjur, aic = aic, bic = bic, auc = auc, hl_chi2 = hl$chi2, hl_df = hl$df,
hl_p = hl$p, accuracy = accuracy, sensitivity = sensitivity, specificity = specificity, epv = epv, max_vif = max_vif,
n_extreme = n_extreme, ci_method = ci_method,
separation = n_extreme > 0, converged = isTRUE(fit$converged), n_params = k, max_interaction_order = if (interactions != "none" && length(predictors) >= 2) 2 else 1,
missing_share = if (n_input > 0) n_dropped / n_input else 0))
pct <- sprintf("%.0f%%", conf * 100)
ci_name <- if (ci_method == "profile") "profile" else "Wald"
alpha <- 1 - conf
significant <- vapply(Filter(function(cf) cf$p < alpha, coefs[-1]), `[[`, "", "term")
summary <- paste0(sprintf("The model of %s = %s (n = %d, %d events) %s on the intercept alone (χ²(%d) = %.2f, %s; AUC = %.2f). ",
outcome, event, n, n_events, if (lr_p < alpha) "improves" else "does not significantly improve", lr_df, lr_chi2, cs_fmt_p(lr_p), auc),
if (length(significant)) sprintf("Significant terms: %s.", paste(significant, collapse = ", ")) else "No individual term is significant.")
tables <- list(list(key = "coefficients", title = "Coefficients (log odds) and odds ratios", columns = list(
list(key = "term", label = "Term", type = "string"), list(key = "estimate", label = "B", type = "number"),
list(key = "se", label = "SE", type = "number"), list(key = "z", label = "z", type = "number"), list(key = "p", label = "p", type = "pvalue"),
list(key = "or", label = "Odds ratio", type = "number"), list(key = "or_ci_low", label = paste(pct, "CI low"), type = "number"),
list(key = "or_ci_high", label = paste(pct, "CI high"), type = "number")), rows = coefs,
note = sprintf("Modeled event: %s = %s; %s intervals; Wald z tests.", outcome, event, ci_name)))
if (length(ame_rows)) {
tables[[length(tables) + 1]] <- list(key = "ame", title = "Average marginal effects (probability scale)", columns = list(
list(key = "term", label = "Predictor", type = "string"), list(key = "ame", label = "AME", type = "number"),
list(key = "se", label = "SE", type = "number"), list(key = "p", label = "p", type = "pvalue"),
list(key = "ci_low", label = paste(pct, "CI low"), type = "number"), list(key = "ci_high", label = paste(pct, "CI high"), type = "number")),
rows = ame_rows, note = "Average over the rows of the change in P(event) per one-unit increase (delta-method SEs).")
}
tables[[length(tables) + 1]] <- list(key = "classification", title = sprintf("Classification at p ≥ %s", format(threshold)), columns = list(
list(key = "observed", label = "Observed", type = "string"), list(key = "pred_event", label = paste("Predicted", event), type = "integer"),
list(key = "pred_other", label = "Predicted other", type = "integer")),
rows = list(list(observed = event, pred_event = tp, pred_other = fn), list(observed = setdiff(levels_y, event)[1], pred_event = fp, pred_other = tn)),
note = sprintf("Accuracy %.1f%%, sensitivity %.1f%%, specificity %.1f%%.", accuracy * 100, sensitivity * 100, specificity * 100))
tables[[length(tables) + 1]] <- list(key = "calibration", title = "Hosmer–Lemeshow risk groups", columns = list(
list(key = "group", label = "Group", type = "integer"), list(key = "n", label = "n", type = "integer"),
list(key = "observed", label = "Observed events", type = "number"), list(key = "expected", label = "Expected events", type = "number")),
rows = lapply(hl$groups, function(g) g[c("group", "n", "observed", "expected")]))
roc <- cs_glm_roc_points(y, phat_r)
slopes <- coefs[-1]
charts <- list(
cs_chart("roc", "roc-curve", sprintf("ROC curve (AUC = %.3f)", auc), list(fpr = cs_col("False-positive rate", roc$fpr), tpr = cs_col("True-positive rate", roc$tpr))),
cs_chart("calibration", "calibration", "Calibration by risk group", list(
predicted = cs_col("Predicted probability", vapply(hl$groups, `[[`, 0, "mean_p")),
observed = cs_col("Observed proportion", vapply(hl$groups, `[[`, 0, "rate")), n = cs_col("n", vapply(hl$groups, `[[`, 0, "n")))),
cs_chart("odds", "forest", "Odds ratios", list(
label = cs_col("Term", vapply(slopes, `[[`, "", "term"), kind = "categorical"), estimate = cs_col("Odds ratio", vapply(slopes, `[[`, 0, "or")),
low = cs_col("low", vapply(slopes, `[[`, 0, "or_ci_low")), high = cs_col("high", vapply(slopes, `[[`, 0, "or_ci_high"))),
controls = list(reference = 1, log = TRUE))
)
cs_publish(list(
method = "regression.logistic",
methodVersion = "2.0.2",
title = "Logistic regression",
engine = cs_engine_info("stats", "nanoparquet"),
n = n,
summary = summary,
apa = sprintf("χ²(%d, N = %d) = %s, %s, Nagelkerke R² = %s", lr_df, n, cs_fmt_num(lr_chi2), cs_fmt_p(lr_p), cs_fmt_num(nagelkerke, leading_zero = FALSE)),
statistics = list(list(key = "lr_chi2", label = "LR χ²", value = lr_chi2), list(key = "lr_p", label = "p", value = lr_p, format = "p"),
list(key = "auc", label = "AUC", value = auc), list(key = "nagelkerke_r2", label = "Nagelkerke R²", value = nagelkerke),
list(key = "aic", label = "AIC", value = aic)),
tables = tables,
effectSizes = list(list(key = "auc", label = "AUC (C statistic)", value = auc, method = "Mann–Whitney concordance of fitted probabilities"),
list(key = "nagelkerke_r2", label = "Nagelkerke R²", value = nagelkerke), list(key = "tjur_r2", label = "Tjur R²", value = tjur)),
assumptions = assumptions,
warnings = warnings,
notes = list(sprintf("Maximum likelihood (IRLS); logit link; P(%s = %s) modeled; categorical predictors against their first level; AUC is apparent (not cross-validated).", outcome, event)),
charts = charts,
values = values
))
χ²(6, N = 189) = 26.79, p < .001, Nagelkerke R² = .19
- LR χ²
- 26.794
- p
- < .001
- AUC
- 0.7173
- Nagelkerke R²
- 0.1859
- AIC
- 221.88
Effect size
- AUC (C statistic) 0.7173
- Nagelkerke R² 0.1859
- Tjur R² 0.1335
To keep this page light, the plots are shown once, under the R tab.
Assumptions
- No separation — No fitted probability is numerically 0 or 1.
- Events per variable — 59 events of the rarer outcome for 6 slope(s): 9.8 per variable (≥ 10 recommended).
- Multicollinearity — Largest VIF 1.21 (mother weight (lb)), from the predictors' correlations.
- Calibration — Hosmer–Lemeshow χ²(8) = 12.83, p = .118 over 10 risk groups.
- Linearity in the logit — Numeric predictors act linearly on the log odds; add a squared term or interaction if a smooth plot of the residuals bends.
Coefficients (log odds) and odds ratios
| Term | B | SE | z | p | Odds ratio | 95% CI low | 95% CI high |
|---|---|---|---|---|---|---|---|
| (Intercept) | 0.7773 | 1.160 | 0.6699 | .503 | 2.176 | 0.2238 | 21.147 |
| age | −0.0212 | 0.0350 | −0.6054 | .545 | 0.9791 | 0.9142 | 1.048 |
| mother weight (lb) | −0.0173 | 0.0069 | −2.519 | .012 | 0.9829 | 0.9697 | 0.9962 |
| race: black | 1.239 | 0.5263 | 2.354 | .019 | 3.451 | 1.230 | 9.681 |
| race: other | 0.9191 | 0.4272 | 2.151 | .031 | 2.507 | 1.085 | 5.791 |
| smoke: true | 1.065 | 0.3892 | 2.736 | .006 | 2.900 | 1.352 | 6.218 |
| ht: true | 1.733 | 0.6879 | 2.519 | .012 | 5.657 | 1.469 | 21.787 |
Modeled event: low = true; Wald intervals; Wald z tests.
Average marginal effects (probability scale)
| Predictor | AME | SE | p | 95% CI low | 95% CI high |
|---|---|---|---|---|---|
| age | −0.0039 | 0.0065 | .544 | −0.0166 | 0.0088 |
| mother weight (lb) | −0.0032 | 0.0012 | .008 | −0.0056 | −0.0009 |
Average over the rows of the change in P(event) per one-unit increase (delta-method SEs).
Classification at p ≥ 0.5
| Observed | Predicted true | Predicted other |
|---|---|---|
| true | 16 | 43 |
| false | 8 | 122 |
Accuracy 73.0%, sensitivity 27.1%, specificity 93.8%.
Hosmer–Lemeshow risk groups
| Group | n | Observed events | Expected events |
|---|---|---|---|
| 1 | 19 | 0 | 1.307 |
| 2 | 19 | 4 | 2.259 |
| 3 | 19 | 4 | 3.259 |
| 4 | 19 | 3 | 4.726 |
| 5 | 19 | 6 | 5.601 |
| 6 | 18 | 4 | 5.819 |
| 7 | 19 | 11 | 6.779 |
| 8 | 19 | 9 | 7.560 |
| 9 | 19 | 5 | 9.021 |
| 10 | 19 | 13 | 12.668 |
- Maximum likelihood (IRLS); logit link; P(low = true) modeled; categorical predictors against their first level; AUC is apparent (not cross-validated).
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Logistic regression (binary outcome)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method regression.logistic 2.0.2 · spec d91d02049e4e7c5a
# Dataset: birthwt (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
import numpy as np
import pandas as pd
import statsmodels.api as sm
from scipy import special, stats
import codesplash as cs
from codesplash.errors import check_not_constant
from codesplash.stats import glm as csglm
from codesplash.stats import regression as csreg
# %% Data
df = pd.read_parquet("tests/parity/fixtures/birthwt.parquet", columns=["low", "age", "mother weight (lb)", "race", "smoke", "ht"])
n_input = len(df)
df["low"] = pd.Categorical(df["low"], categories=["false", "true"]) # stored level order
df["race"] = pd.Categorical(df["race"], categories=["white", "black", "other"]) # stored level order
df["smoke"] = pd.Categorical(df["smoke"], categories=["false", "true"]) # stored level order
df["ht"] = pd.Categorical(df["ht"], categories=["false", "true"]) # stored level order
df = df.dropna(subset=["low", "age", "mother weight (lb)", "race", "smoke", "ht"]) # listwise deletion over the analysis columns
df["low"] = df["low"].cat.remove_unused_categories()
df["race"] = df["race"].cat.remove_unused_categories()
df["smoke"] = df["smoke"].cat.remove_unused_categories()
df["ht"] = df["ht"].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, ["low", "age", "mother weight (lb)", "race", "smoke", "ht"]) # infinite values stop the run (registry/errors.yaml)
# %% Outcome and design matrix
outcome = "low"
predictors = ["age", "mother weight (lb)", "race", "smoke", "ht"]
conf = 0.95
interactions = "none" # none | first-two | all-pairs
ci_method = "wald" # wald | profile
threshold = 0.5
levels_y = [str(x) for x in df[outcome].cat.categories]
if len(levels_y) != 2:
cs.cs_error("CS_E_GROUP_COUNT", column=outcome, expected=2, k=len(levels_y))
event = levels_y[1] # default: the second stored level ("true" for yes/no)
if event not in levels_y:
cs.cs_error("CS_E_NOT_A_LEVEL", level=event, column=outcome)
y = (df[outcome].astype(str) == event).to_numpy(dtype=float)
# Treatment contrasts: the first stored level of each categorical predictor is the reference.
X = csreg.design_matrix(df, predictors, interactions)
# Degenerate input stops with a catalog error; R runs the same checks in the same order.
cs.check_rows(len(df), X.shape[1] + 1, "Logistic regression") # more rows than coefficients
for p in predictors:
check_not_constant(df[p], p) # one value (or one level with data) is no variation
if np.linalg.matrix_rank(X.to_numpy()) < X.shape[1]:
cs.cs_error("CS_E_COLLINEAR")
n, k = X.shape
terms = list(X.columns)
Xm = X.to_numpy()
# %% Fit (maximum likelihood by IRLS, tight convergence)
fit = sm.GLM(y, X, family=sm.families.Binomial()).fit(method="IRLS", tol=1e-10, maxiter=200)
# polish: one more IRLS pass from the converged coefficients, so the covariance uses their weights
fit = sm.GLM(y, X, family=sm.families.Binomial()).fit(method="IRLS", tol=1e-10, maxiter=200, start_params=np.asarray(fit.params))
b = fit.params.to_numpy()
V = np.asarray(fit.cov_params())
se = np.sqrt(np.diag(V))
z = b / se
pval = 2 * stats.norm.sf(np.abs(z))
zc = stats.norm.ppf(1 - (1 - conf) / 2)
log_lik = float(fit.llf)
deviance = -2 * log_lik
if ci_method == "profile":
ci = csglm.logistic_profile_ci(Xm, y, b, se, deviance, conf) # exact roots of the profile deviance
else:
ci = np.column_stack([b - zc * se, b + zc * se])
n_events = int(y.sum())
pbar = n_events / n
null_log_lik = n_events * np.log(pbar) + (n - n_events) * np.log(1 - pbar)
lr_chi2 = 2 * (log_lik - null_log_lik)
lr_df = k - 1
lr_p = float(stats.chi2.sf(lr_chi2, lr_df))
mcfadden = 1 - log_lik / null_log_lik
cox_snell = 1 - np.exp(2 * (null_log_lik - log_lik) / n)
nagelkerke = cox_snell / (1 - np.exp(2 * null_log_lik / n))
phat = special.expit(Xm @ b)
# Rounded to 12 decimals before ranking and grouping, so near-ties are ties in both engines.
phat_r = np.round(phat, 12)
tjur = float(phat[y == 1].mean() - phat[y == 0].mean())
aic = -2 * log_lik + 2 * k
bic = -2 * log_lik + np.log(n) * k
auc = csglm.auc(y, phat_r)
hl = csglm.hosmer_lemeshow(y, phat_r, int(10))
pred = phat_r >= threshold
tp, fn = int((pred & (y == 1)).sum()), int((~pred & (y == 1)).sum())
tn, fp = int((~pred & (y == 0)).sum()), int((pred & (y == 0)).sum())
accuracy, sensitivity, specificity = (tp + tn) / n, tp / (tp + fn), tn / (tn + fp)
# %% Average marginal effects (numeric predictors outside interactions)
values = {}
ame_rows = []
if True:
in_interaction = {predictors[i] for pair in csreg.interaction_pairs(len(predictors), interactions) for i in pair}
for p in predictors:
if isinstance(df[p].dtype, pd.CategoricalDtype) or p in in_interaction:
continue
j = terms.index(p)
ame, ame_se = csglm.logistic_ame(Xm, b, V, j)
row = {"term": p, "ame": ame, "se": ame_se, "ci_low": ame - zc * ame_se, "ci_high": ame + zc * ame_se,
"p": float(2 * stats.norm.sf(abs(ame / ame_se)))}
ame_rows.append(row)
values.update({f"ame[{p}]": ame, f"ame_se[{p}]": ame_se, f"ame_ci_low[{p}]": row["ci_low"], f"ame_ci_high[{p}]": row["ci_high"]})
# %% Assumptions
assumptions = []
n_extreme = int(np.sum((phat < 1e-8) | (phat > 1 - 1e-8)))
assumptions.append({"key": "separation", "label": "No separation", "status": "warn" if n_extreme else "pass", "statistic": n_extreme,
"detail": f"{n_extreme} row(s) have fitted probabilities numerically 0 or 1: a predictor (nearly) separates the outcomes, so some estimates and standard errors are unreliable; consider fewer predictors or Firth's penalized likelihood."
if n_extreme else "No fitted probability is numerically 0 or 1."})
epv = min(n_events, n - n_events) / max(k - 1, 1)
assumptions.append({"key": "sample_size", "label": "Events per variable", "status": "pass" if epv >= 10 else ("warn" if epv >= 5 else "fail"), "statistic": epv,
"detail": f"{min(n_events, n - n_events)} events of the rarer outcome for {k - 1} slope(s): {epv:.1f} per variable" + (" (≥ 10 recommended)." if epv < 10 else ".")})
main_cols = [c for c in terms[1:] if csreg.TIMES not in c]
vifs = csreg.gvif(X, main_cols, df, predictors) # one generalized VIF per factor
max_vif = None
if vifs:
worst = max(vifs, key=vifs.get)
max_vif = vifs[worst]
assumptions.append({"key": "multicollinearity", "label": "Multicollinearity", "status": "pass" if max_vif < 5 else ("warn" if max_vif < 10 else "fail"),
"statistic": max_vif, "detail": f"Largest VIF {max_vif:.2f} ({worst}), from the predictors' correlations."})
if hl["p"] is not None:
assumptions.append({"key": "calibration", "label": "Calibration", "status": "warn" if hl["p"] < 0.05 else "pass", "statistic": hl["chi2"], "p": hl["p"],
"detail": f"Hosmer–Lemeshow χ²({hl['df']}) = {hl['chi2']:.2f}, {cs.fmt_p(hl['p'])} over {len(hl['groups'])} risk groups."})
assumptions.append({"key": "linearity", "label": "Linearity in the logit", "status": "info",
"detail": "Numeric predictors act linearly on the log odds; add a squared term or interaction if a smooth plot of the residuals bends."})
# %% Result
coefs = [{"term": t, "estimate": float(b[j]), "se": float(se[j]), "z": float(z[j]), "p": float(pval[j]), "ci_low": float(ci[j, 0]), "ci_high": float(ci[j, 1]),
"or": float(np.exp(b[j])), "or_ci_low": float(np.exp(ci[j, 0])), "or_ci_high": float(np.exp(ci[j, 1]))} for j, t in enumerate(terms)]
for c in coefs:
values.update({f"{key}[{c['term']}]": c[key2] for key, key2 in (("coef", "estimate"), ("se", "se"), ("z", "z"), ("p", "p"), ("ci_low", "ci_low"),
("ci_high", "ci_high"), ("or", "or"), ("or_ci_low", "or_ci_low"), ("or_ci_high", "or_ci_high"))})
values.update({"n": n, "n_events": n_events, "k": k, "event_level": event, "log_lik": log_lik, "null_log_lik": float(null_log_lik),
"deviance": deviance, "lr_chi2": float(lr_chi2), "lr_df": float(lr_df), "lr_p": lr_p, "mcfadden_r2": float(mcfadden),
"cox_snell_r2": float(cox_snell), "nagelkerke_r2": float(nagelkerke), "tjur_r2": tjur, "aic": float(aic), "bic": float(bic),
"auc": auc, "hl_chi2": hl["chi2"], "hl_df": float(hl["df"]), "hl_p": hl["p"], "accuracy": accuracy, "sensitivity": sensitivity,
"specificity": specificity, "epv": float(epv), "max_vif": max_vif, "n_extreme": n_extreme, "ci_method": ci_method,
"separation": n_extreme > 0, "converged": bool(fit.converged), "n_params": k, "max_interaction_order": 2 if interactions != "none" and len(predictors) >= 2 else 1,
"missing_share": n_dropped / n_input if n_input else 0.0})
pct = f"{conf:.0%}"
ci_name = "profile" if ci_method == "profile" else "Wald"
alpha = 1 - conf
significant = [c["term"] for c in coefs[1:] if c["p"] < alpha]
summary = (
f"The model of {outcome} = {event} (n = {n}, {n_events} events) {'improves' if lr_p < alpha else 'does not significantly improve'} on the intercept alone "
f"(χ²({lr_df}) = {lr_chi2:.2f}, {cs.fmt_p(lr_p)}; AUC = {auc:.2f}). "
+ (f"Significant terms: {', '.join(significant)}." if significant else "No individual term is significant.")
)
tables = [{"key": "coefficients", "title": "Coefficients (log odds) and odds ratios", "columns": [
{"key": "term", "label": "Term", "type": "string"}, {"key": "estimate", "label": "B", "type": "number"},
{"key": "se", "label": "SE", "type": "number"}, {"key": "z", "label": "z", "type": "number"}, {"key": "p", "label": "p", "type": "pvalue"},
{"key": "or", "label": "Odds ratio", "type": "number"}, {"key": "or_ci_low", "label": f"{pct} CI low", "type": "number"},
{"key": "or_ci_high", "label": f"{pct} CI high", "type": "number"}], "rows": coefs,
"note": f"Modeled event: {outcome} = {event}; {ci_name} intervals; Wald z tests."}]
if ame_rows:
tables.append({"key": "ame", "title": "Average marginal effects (probability scale)", "columns": [
{"key": "term", "label": "Predictor", "type": "string"}, {"key": "ame", "label": "AME", "type": "number"},
{"key": "se", "label": "SE", "type": "number"}, {"key": "p", "label": "p", "type": "pvalue"},
{"key": "ci_low", "label": f"{pct} CI low", "type": "number"}, {"key": "ci_high", "label": f"{pct} CI high", "type": "number"}],
"rows": ame_rows, "note": "Average over the rows of the change in P(event) per one-unit increase (delta-method SEs)."})
tables.append({"key": "classification", "title": f"Classification at p ≥ {threshold:g}", "columns": [
{"key": "observed", "label": "Observed", "type": "string"}, {"key": "pred_event", "label": f"Predicted {event}", "type": "integer"},
{"key": "pred_other", "label": "Predicted other", "type": "integer"}],
"rows": [{"observed": event, "pred_event": tp, "pred_other": fn}, {"observed": [lv for lv in levels_y if lv != event][0], "pred_event": fp, "pred_other": tn}],
"note": f"Accuracy {accuracy:.1%}, sensitivity {sensitivity:.1%}, specificity {specificity:.1%}."})
tables.append({"key": "calibration", "title": "Hosmer–Lemeshow risk groups", "columns": [
{"key": "group", "label": "Group", "type": "integer"}, {"key": "n", "label": "n", "type": "integer"},
{"key": "observed", "label": "Observed events", "type": "number"}, {"key": "expected", "label": "Expected events", "type": "number"}],
"rows": [{k2: g[k2] for k2 in ("group", "n", "observed", "expected")} for g in hl["groups"]]})
fpr, tpr = csglm.roc_points(y, phat_r)
slopes = [c for c in coefs if c["term"] != "(Intercept)"]
charts = [
cs.chart("roc", "roc-curve", f"ROC curve (AUC = {auc:.3f})", {"fpr": cs.col("False-positive rate", fpr), "tpr": cs.col("True-positive rate", tpr)}),
cs.chart("calibration", "calibration", "Calibration by risk group", {
"predicted": cs.col("Predicted probability", [g["mean_p"] for g in hl["groups"]]),
"observed": cs.col("Observed proportion", [g["rate"] for g in hl["groups"]]), "n": cs.col("n", [g["n"] for g in hl["groups"]])}),
cs.chart("odds", "forest", "Odds ratios", {
"label": cs.col("Term", [c["term"] for c in slopes], kind="categorical"), "estimate": cs.col("Odds ratio", [c["or"] for c in slopes]),
"low": cs.col("low", [c["or_ci_low"] for c in slopes]), "high": cs.col("high", [c["or_ci_high"] for c in slopes])},
controls={"reference": 1, "log": True}),
]
cs.publish({
"method": "regression.logistic",
"methodVersion": "2.0.2",
"title": "Logistic regression",
"engine": cs.engine_info("pandas", "numpy", "statsmodels", "scipy"),
"n": n,
"summary": summary,
"apa": f"χ²({lr_df}, N = {n}) = {cs.fmt_num(lr_chi2)}, {cs.fmt_p(lr_p)}, Nagelkerke R² = {cs.fmt_num(nagelkerke, leading_zero=False)}",
"statistics": [{"key": "lr_chi2", "label": "LR χ²", "value": float(lr_chi2)}, {"key": "lr_p", "label": "p", "value": lr_p, "format": "p"},
{"key": "auc", "label": "AUC", "value": auc}, {"key": "nagelkerke_r2", "label": "Nagelkerke R²", "value": float(nagelkerke)},
{"key": "aic", "label": "AIC", "value": float(aic)}],
"tables": tables,
"effectSizes": [{"key": "auc", "label": "AUC (C statistic)", "value": auc, "method": "Mann–Whitney concordance of fitted probabilities"},
{"key": "nagelkerke_r2", "label": "Nagelkerke R²", "value": float(nagelkerke)}, {"key": "tjur_r2", "label": "Tjur R²", "value": tjur}],
"assumptions": assumptions,
"warnings": warnings,
"notes": [f"Maximum likelihood (IRLS); logit link; P({outcome} = {event}) modeled; categorical predictors against their first level; AUC is apparent (not cross-validated)."],
"charts": charts,
"values": values,
})
Find the average marginal effects on this card. They're on the probability scale. For the mother's weight it's −0.0032 (95% CI −0.0056 to −0.0009): about a third of a percentage point lower per pound, averaged over these 189 mothers.
They cover numeric predictors that aren't part of an interaction. Say that it's an average: individual rows can differ a lot from it.
Adjusted means for factors
ReadEstimated marginal meansEstimated marginal meansGroup means predicted by the model, averaged over the other factors; the basis for adjusted comparisons. do a similar job for a categorical predictor. They ask what the mean of each level would be, with the other predictors held at the same values for every level.
R² = .84, adjusted R² = .81, F(4, 27) = 34.79, p < .001
- R²
- 0.8375
- Adjusted R²
- 0.8134
- F
- 34.792
- p (F test)
- < .001
- Residual SE
- 2.603
- AIC
- 158.61
Effect size
- Cohen's f² 5.154
- R² 0.8375
Plots
View data
| Cook's distance | Fitted | Leverage | Residual | Standardized residual |
|---|---|---|---|---|
| 0.0015 | 21.394 | 0.2015 | −0.3944 | −0.1696 |
| 0.0016 | 20.591 | 0.2057 | 0.4087 | 0.1762 |
| 0.0600 | 26.597 | 0.1113 | −3.797 | −1.547 |
| 0.0331 | 19.370 | 0.1820 | 2.030 | 0.8621 |
| 0.0174 | 16.840 | 0.1294 | 1.860 | 0.7658 |
| 0.0019 | 18.599 | 0.1756 | −0.4987 | −0.2110 |
| 0.0187 | 16.430 | 0.1104 | −2.130 | −0.8677 |
| 0.0044 | 23.706 | 0.1999 | 0.6936 | 0.2979 |
| 0.0096 | 23.832 | 0.1967 | −1.032 | −0.4425 |
| 0.0022 | 18.662 | 0.1756 | 0.5383 | 0.2278 |
| 0.0057 | 18.662 | 0.1756 | −0.8617 | −0.3646 |
| 0.0062 | 14.856 | 0.0752 | 1.544 | 0.6169 |
| 0.0063 | 15.926 | 0.0925 | 1.374 | 0.5539 |
| 0.0010 | 15.769 | 0.0882 | −0.5690 | −0.2289 |
| 0.0064 | 11.139 | 0.2336 | −0.7391 | −0.3243 |
| 0.0006 | 10.591 | 0.2856 | −0.1911 | −0.0868 |
| 0.2103 | 10.840 | 0.2611 | 3.860 | 1.725 |
| 0.1152 | 26.975 | 0.1060 | 5.425 | 2.204 |
| 0.0127 | 28.817 | 0.1301 | 1.583 | 0.6520 |
| 0.1387 | 28.124 | 0.1113 | 5.776 | 2.354 |
| 0.1894 | 25.990 | 0.2025 | −4.490 | −1.931 |
| 0.0053 | 16.588 | 0.1172 | −1.088 | −0.4448 |
| 0.0139 | 16.856 | 0.1303 | −1.656 | −0.6820 |
| 0.0153 | 15.580 | 0.0838 | −2.280 | −0.9151 |
| 0.0388 | 15.564 | 0.0835 | 3.636 | 1.459 |
| 0.0010 | 27.809 | 0.1066 | −0.5092 | −0.2070 |
| 0.0052 | 27.164 | 0.1046 | −1.164 | −0.4724 |
| 0.0091 | 29.138 | 0.1429 | 1.262 | 0.5235 |
| 0.0402 | 17.840 | 0.2060 | −2.040 | −0.8796 |
| 0.0140 | 20.922 | 0.2020 | −1.222 | −0.5255 |
| 0.0246 | 16.581 | 0.2086 | −1.581 | −0.6825 |
| 0.0975 | 25.148 | 0.1643 | −3.748 | −1.575 |
View data
| high | low | mpg (EMM) | cyl_f |
|---|---|---|---|
| 25.898 | 21.494 | 23.696 | 4 |
| 21.484 | 17.393 | 19.438 | 6 |
| 19.510 | 15.723 | 17.616 | 8 |
View data
| Row | Term | Predictor given the others | mpg given the others |
|---|---|---|---|
| row 1 | weight (1000 lbs) | −0.0599 | −0.2057 |
| row 2 | weight (1000 lbs) | 0.1951 | −0.2057 |
| row 3 | weight (1000 lbs) | 0.2429 | −4.562 |
| row 4 | weight (1000 lbs) | −0.2301 | 2.754 |
| row 5 | weight (1000 lbs) | −0.6685 | 3.966 |
| row 6 | weight (1000 lbs) | 0.0149 | −0.5457 |
| row 7 | weight (1000 lbs) | −0.5385 | −0.4343 |
| row 8 | weight (1000 lbs) | 0.3478 | −0.4019 |
| row 9 | weight (1000 lbs) | 0.3078 | −2.002 |
| row 10 | weight (1000 lbs) | −0.0051 | 0.5543 |
| row 11 | weight (1000 lbs) | −0.0051 | −0.8457 |
| row 12 | weight (1000 lbs) | −0.0385 | 1.666 |
| row 13 | weight (1000 lbs) | −0.3785 | 2.566 |
| row 14 | weight (1000 lbs) | −0.3285 | 0.4657 |
| row 15 | weight (1000 lbs) | 1.141 | −4.334 |
| row 16 | weight (1000 lbs) | 1.315 | −4.334 |
| row 17 | weight (1000 lbs) | 1.236 | −0.0343 |
| row 18 | weight (1000 lbs) | 0.1229 | 5.038 |
| row 19 | weight (1000 lbs) | −0.4621 | 3.038 |
| row 20 | weight (1000 lbs) | −0.2421 | 6.538 |
| row 21 | weight (1000 lbs) | −0.3772 | −3.302 |
| row 22 | weight (1000 lbs) | −0.5885 | 0.7657 |
| row 23 | weight (1000 lbs) | −0.6735 | 0.4657 |
| row 24 | weight (1000 lbs) | −0.2685 | −1.434 |
| row 25 | weight (1000 lbs) | −0.2635 | 4.466 |
| row 26 | weight (1000 lbs) | −0.1421 | −0.0618 |
| row 27 | weight (1000 lbs) | 0.0629 | −1.362 |
| row 28 | weight (1000 lbs) | −0.5641 | 3.038 |
| row 29 | weight (1000 lbs) | −0.1734 | −1.494 |
| row 30 | weight (1000 lbs) | 0.0901 | −1.506 |
| row 31 | weight (1000 lbs) | 0.2266 | −2.294 |
| row 32 | weight (1000 lbs) | 0.7029 | −5.962 |
| row 1 | cyl_f: 6 | 0.6046 | −2.968 |
| row 2 | cyl_f: 6 | 0.5409 | −1.894 |
| row 3 | cyl_f: 6 | −0.3206 | −2.432 |
| row 4 | cyl_f: 6 | 0.4659 | 0.0463 |
| row 5 | cyl_f: 6 | 0.1410 | 1.260 |
| row 6 | cyl_f: 6 | 0.4047 | −2.222 |
| row 7 | cyl_f: 6 | 0.1085 | −2.592 |
| row 8 | cyl_f: 6 | −0.5279 | 2.941 |
| row 9 | cyl_f: 6 | −0.5179 | 1.173 |
| row 10 | cyl_f: 6 | 0.4097 | −1.206 |
| row 11 | cyl_f: 6 | 0.4097 | −2.606 |
| row 12 | cyl_f: 6 | −0.0163 | 1.614 |
| row 13 | cyl_f: 6 | 0.0686 | 1.081 |
| row 14 | cyl_f: 6 | 0.0561 | −0.8079 |
| row 15 | cyl_f: 6 | −0.3108 | 0.5841 |
| row 16 | cyl_f: 6 | −0.3542 | 1.317 |
| row 17 | cyl_f: 6 | −0.3345 | 5.284 |
| row 18 | cyl_f: 6 | −0.2906 | 6.663 |
| row 19 | cyl_f: 6 | −0.1446 | 2.198 |
| row 20 | cyl_f: 6 | −0.1995 | 6.625 |
| row 21 | cyl_f: 6 | −0.3469 | −3.013 |
| row 22 | cyl_f: 6 | 0.1210 | −1.603 |
| row 23 | cyl_f: 6 | 0.1422 | −2.261 |
| row 24 | cyl_f: 6 | 0.0411 | −2.455 |
| row 25 | cyl_f: 6 | 0.0399 | 3.466 |
| row 26 | cyl_f: 6 | −0.2245 | 0.4464 |
| row 27 | cyl_f: 6 | −0.2756 | 0.0099 |
| row 28 | cyl_f: 6 | −0.1191 | 1.769 |
First 60 of 128 rows.
View data
| Row | Component + residual | Term | Predictor |
|---|---|---|---|
| row 1 | −8.646 | weight (1000 lbs) | 2.620 |
| row 2 | −8.646 | weight (1000 lbs) | 2.875 |
| row 3 | −11.104 | weight (1000 lbs) | 2.320 |
| row 4 | −8.096 | weight (1000 lbs) | 3.215 |
| row 5 | −8.974 | weight (1000 lbs) | 3.440 |
| row 6 | −11.396 | weight (1000 lbs) | 3.460 |
| row 7 | −13.374 | weight (1000 lbs) | 3.570 |
| row 8 | −9.354 | weight (1000 lbs) | 3.190 |
| row 9 | −10.954 | weight (1000 lbs) | 3.150 |
| row 10 | −10.296 | weight (1000 lbs) | 3.440 |
| row 11 | −11.696 | weight (1000 lbs) | 3.440 |
| row 12 | −11.274 | weight (1000 lbs) | 4.070 |
| row 13 | −10.374 | weight (1000 lbs) | 3.730 |
| row 14 | −12.474 | weight (1000 lbs) | 3.780 |
| row 15 | −17.274 | weight (1000 lbs) | 5.250 |
| row 16 | −17.274 | weight (1000 lbs) | 5.424 |
| row 17 | −12.974 | weight (1000 lbs) | 5.345 |
| row 18 | −1.504 | weight (1000 lbs) | 2.200 |
| row 19 | −3.504 | weight (1000 lbs) | 1.615 |
| row 20 | −0.0037 | weight (1000 lbs) | 1.835 |
| row 21 | −12.254 | weight (1000 lbs) | 2.465 |
| row 22 | −12.174 | weight (1000 lbs) | 3.520 |
| row 23 | −12.474 | weight (1000 lbs) | 3.435 |
| row 24 | −14.374 | weight (1000 lbs) | 3.840 |
| row 25 | −8.474 | weight (1000 lbs) | 3.845 |
| row 26 | −6.604 | weight (1000 lbs) | 1.935 |
| row 27 | −7.904 | weight (1000 lbs) | 2.140 |
| row 28 | −3.504 | weight (1000 lbs) | 1.513 |
| row 29 | −12.025 | weight (1000 lbs) | 3.170 |
| row 30 | −9.946 | weight (1000 lbs) | 2.770 |
| row 31 | −12.825 | weight (1000 lbs) | 3.570 |
| row 32 | −12.504 | weight (1000 lbs) | 2.780 |
View data
| Cook's distance | Row |
|---|---|
| 0.0015 | 1 |
| 0.0016 | 2 |
| 0.0600 | 3 |
| 0.0331 | 4 |
| 0.0174 | 5 |
| 0.0019 | 6 |
| 0.0187 | 7 |
| 0.0044 | 8 |
| 0.0096 | 9 |
| 0.0022 | 10 |
| 0.0057 | 11 |
| 0.0062 | 12 |
| 0.0063 | 13 |
| 0.0010 | 14 |
| 0.0064 | 15 |
| 0.0006 | 16 |
| 0.2103 | 17 |
| 0.1152 | 18 |
| 0.0127 | 19 |
| 0.1387 | 20 |
| 0.1894 | 21 |
| 0.0053 | 22 |
| 0.0139 | 23 |
| 0.0153 | 24 |
| 0.0388 | 25 |
| 0.0010 | 26 |
| 0.0052 | 27 |
| 0.0091 | 28 |
| 0.0402 | 29 |
| 0.0140 | 30 |
| 0.0246 | 31 |
| 0.0975 | 32 |
Assumptions
- Normality of residuals — Shapiro–Wilk W = 0.959, p = .260.
- Constant variance — Breusch–Pagan (Koenker) χ²(4) = 6.87, p = .143.
- Multicollinearity — Largest VIF 3.61 (weight (1000 lbs)).
- Linearity — RESET F(2, 25) = 2.94, p = .071.
- Independent residuals — Durbin–Watson = 1.80 (≈ 2 when residuals in row order are uncorrelated; only meaningful for ordered rows).
- Influential points — 3 row(s) with Cook's distance above 4/n = 0.125; largest 0.210.
Coefficients
| Term | Estimate | SE | t | p | 95% CI low | 95% CI high | β (std.) |
|---|---|---|---|---|---|---|---|
| (Intercept) | 33.754 | 2.813 | 11.997 | < .001 | 27.981 | 39.526 | — |
| weight (1000 lbs) | −3.150 | 0.9080 | −3.469 | .002 | −5.013 | −1.286 | −0.5113 |
| cyl_f: 6 | −4.257 | 1.411 | −3.017 | .006 | −7.153 | −1.362 | −0.2967 |
| cyl_f: 8 | −6.079 | 1.684 | −3.611 | .001 | −9.534 | −2.624 | −0.5084 |
| manual: true | 0.1501 | 1.300 | 0.1154 | .909 | −2.518 | 2.818 | 0.0124 |
Standard errors: classical; t tests with 27 df.
Estimated marginal means
| Factor | Level | EMM | SE | 95% CI low | 95% CI high |
|---|---|---|---|---|---|
| cyl_f | 4 | 23.696 | 1.073 | 21.494 | 25.898 |
| cyl_f | 6 | 19.438 | 0.9970 | 17.393 | 21.484 |
| cyl_f | 8 | 17.616 | 0.9228 | 15.723 | 19.510 |
| manual | false | 20.175 | 0.7119 | 18.714 | 21.636 |
| manual | true | 20.325 | 0.9158 | 18.446 | 22.204 |
Other factors averaged with equal weights; numeric predictors at their means.
Pairwise comparisons of marginal means
| Factor | Contrast | Difference | SE | t | p (adj.) | CI low | CI high |
|---|---|---|---|---|---|---|---|
| cyl_f | 4 - 6 | 4.257 | 1.411 | 3.017 | .015 | 0.7583 | 7.756 |
| cyl_f | 4 - 8 | 6.079 | 1.684 | 3.611 | .003 | 1.904 | 10.254 |
| cyl_f | 6 - 8 | 1.822 | 1.383 | 1.317 | .398 | −1.608 | 5.252 |
| manual | false - true | −0.1501 | 1.300 | −0.1154 | .909 | −2.818 | 2.518 |
Adjustment: tukey (within each factor).
Most influential rows (Cook's distance)
| Row | Fitted | Residual | Studentized | Leverage | Cook's D |
|---|---|---|---|---|---|
| 17 | 10.840 | 3.860 | 1.795 | 0.2611 | 0.2103 |
| 21 | 25.990 | −4.490 | −2.041 | 0.2025 | 0.1894 |
| 20 | 28.124 | 5.776 | 2.591 | 0.1113 | 0.1387 |
| 18 | 26.975 | 5.425 | 2.389 | 0.1060 | 0.1152 |
| 32 | 25.148 | −3.748 | −1.622 | 0.1643 | 0.0975 |
| 3 | 26.597 | −3.797 | −1.590 | 0.1113 | 0.0600 |
| 29 | 17.840 | −2.040 | −0.8758 | 0.2060 | 0.0402 |
| 25 | 15.564 | 3.636 | 1.492 | 0.0835 | 0.0388 |
| 4 | 19.370 | 2.030 | 0.8579 | 0.1820 | 0.0331 |
| 31 | 16.581 | −1.581 | −0.6756 | 0.2086 | 0.0246 |
Row numbers count the rows used in the analysis (after missing values were left out).
- Fewer than 10 rows per coefficient (32 rows, 4 slopes): estimates may be unstable.
- Ordinary least squares; categorical predictors use treatment contrasts with the first stored level as reference; classical standard errors.
The exact R script · R R version 4.5.1 (2025-06-13)
# Linear regression (OLS)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method regression.linear 2.0.1 · spec fe7c9c92f10ad7e6
# 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)
# %% Data
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/mtcars.parquet", col_select = c("mpg", "weight (1000 lbs)", "cyl_f", "manual")))
n_input <- nrow(df)
df[["cyl_f"]] <- factor(df[["cyl_f"]], levels = c("4", "6", "8")) # stored level order
df[["manual"]] <- factor(df[["manual"]], levels = c("false", "true")) # stored level order
df <- df[stats::complete.cases(df[c("mpg", "weight (1000 lbs)", "cyl_f", "manual")]), , 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", "weight (1000 lbs)", "cyl_f", "manual")) # infinite values stop the run (registry/errors.yaml)
# %% Fit
y <- "mpg"
predictors <- c("weight (1000 lbs)", "cyl_f", "manual")
conf <- 0.95
interactions <- "none" # none | first-two | all-pairs
se_type <- "classical" # classical | HC0-HC3 | cluster | HAC
diagnostics <- "standard" # standard | full
cluster <- NULL
if (se_type == "cluster" && is.null(cluster)) stop("Cluster-robust standard errors need a cluster column (the Cluster role).")
# Treatment contrasts (R's default for unordered factors): the first stored level is the reference.
intercept <- TRUE
if (!intercept && any(vapply(predictors, function(p) is.factor(df[[p]]), logical(1)))) {
stop("A model without an intercept takes numeric predictors only (a categorical predictor would need every level as a column).")
}
# Degenerate input stops with a catalog error; Python runs the same checks in the same order.
cs_check_rows(nrow(df), length(cs_design_labels(df, predictors, interactions, intercept = intercept)) + 1, "Linear regression") # more rows than coefficients
cs_check_not_constant(df[[y]], y)
if (intercept) {
for (p in predictors) cs_check_not_constant(df[[p]], p) # one value (or one level with data) is no variation
}
fml <- cs_model_formula(y, predictors, interactions, intercept = intercept) # intercept = FALSE: y ~ 0 + ...
fit0 <- lm(fml, data = df)
if (anyNA(coef(fit0))) cs_error("CS_E_COLLINEAR")
X <- model.matrix(fit0)
terms <- cs_design_labels(df, predictors, interactions, intercept = intercept)
stopifnot(length(terms) == ncol(X))
colnames(X) <- terms
n <- nrow(X)
k <- ncol(X)
yv <- df[[y]]
b <- setNames(coef(fit0), terms)
e <- unname(residuals(fit0))
order_col <- NULL
ord_idx <- seq_len(n)
hac_lag <- NULL
# Covariance of the coefficients: classical, HC0-HC3 (sandwich::vcovHC formulas) or CR1 (Stata factor)
V <- if (se_type == "classical") {
vcov(fit0)
} else if (se_type == "cluster") {
cs_vcov_cluster(X, e, df[[cluster]])
} else if (se_type == "HAC") {
hac <- cs_hac_cov(X[ord_idx, , drop = FALSE], e[ord_idx], NULL)
hac_lag <- hac$lag
hac$V
} else {
cs_vcov_hc(X, e, se_type)
}
dimnames(V) <- list(terms, terms)
n_clusters <- if (se_type == "cluster") length(unique(df[[cluster]])) else NULL
dfree <- if (se_type == "cluster") n_clusters - 1 else n - k # cluster-robust: t with G - 1 df
se <- sqrt(diag(V))
tval <- b / se
pval <- 2 * pt(abs(tval), dfree, lower.tail = FALSE)
crit <- qt(1 - (1 - conf) / 2, dfree)
beta <- cs_std_beta(X, yv, b)
coefs <- lapply(seq_along(terms), function(j) {
list(term = terms[j], estimate = unname(b[j]), se = unname(se[j]), t = unname(tval[j]), p = unname(pval[j]),
ci_low = unname(b[j] - crit * se[j]), ci_high = unname(b[j] + crit * se[j]),
std_beta = if (terms[j] == "(Intercept)") NULL else unname(beta[terms[j]]))
})
s <- summary(fit0)
r2 <- s$r.squared
adj_r2 <- s$adj.r.squared
slope_idx <- which(terms != "(Intercept)")
wf <- cs_wald_f(b, V, slope_idx) # = the classical F with classical SEs (all coefficients when there is no intercept)
f <- wf[1]
df1 <- wf[2]
df2 <- dfree
f_p <- pf(f, df1, df2, lower.tail = FALSE)
f2 <- if (r2 < 1) r2 / (1 - r2) else Inf # an exact fit has R^2 = 1
sigma <- s$sigma
log_lik <- as.numeric(logLik(fit0))
aic <- -2 * log_lik + 2 * (k + 1) # k coefficients + sigma (= AIC(fit0))
bic <- -2 * log_lik + log(n) * (k + 1)
# %% Assumptions
assumptions <- list()
add_assumption <- function(a) assumptions[[length(assumptions) + 1]] <<- a
sw <- if (n >= 3 && n <= 5000) shapiro.test(e) else NULL
if (!is.null(sw)) {
status <- if (sw$p.value >= 0.05) "pass" else if (n >= 50) "info" else "warn"
add_assumption(list(key = "normality", label = "Normality of residuals", status = status, statistic = unname(sw$statistic), p = sw$p.value,
detail = paste0(sprintf("Shapiro–Wilk W = %.3f, %s", sw$statistic, cs_fmt_p(sw$p.value)),
if (status == "info") " (with large n, judge the Q–Q plot)." else ".")))
}
# Koenker's studentized Breusch-Pagan (n * R^2 of e^2 on X, with a constant even when the model has none)
bp_X <- if (intercept) X else cbind(1, X)
bpt <- cs_breusch_pagan(bp_X, e)
bp <- bpt$statistic
bp_p <- bpt$p
robust <- se_type != "classical"
add_assumption(list(key = "homoscedasticity", label = "Constant variance", status = if (robust) "info" else if (bp_p < 0.05) "warn" else "pass",
statistic = bp, p = bp_p,
detail = paste0(sprintf("Breusch–Pagan (Koenker) χ²(%d) = %.2f, %s", ncol(bp_X) - 1, bp, cs_fmt_p(bp_p)),
if (robust) "; the robust standard errors do not assume it." else if (bp_p < 0.05) "; consider robust (HC3) standard errors." else ".")))
main_cols <- terms[terms != "(Intercept)" & !grepl(" × ", terms, fixed = TRUE)]
vifs <- cs_gvif(X, main_cols, df, predictors) # one generalized VIF per factor
max_vif <- NULL
if (length(vifs)) {
max_vif <- max(vifs)
status <- if (max_vif < 5) "pass" else if (max_vif < 10) "warn" else "fail"
add_assumption(list(key = "multicollinearity", label = "Multicollinearity", status = status, statistic = max_vif,
detail = paste0(sprintf("Largest VIF %.2f (%s)", max_vif, names(vifs)[which.max(vifs)]),
if (length(main_cols) < length(slope_idx)) "; interaction columns are left out (their correlation with main effects is structural)." else ".")))
}
# Ramsey RESET (powers of yhat, or of each numeric predictor) -- not defined when they add nothing
# (e.g. a model that fits every cell mean).
fitted_v <- unname(fitted(fit0))
reset_type <- "fitted"
reset_power <- as.integer(3)
reset_f <- NULL
reset_p <- NULL
reset_df1 <- NULL
reset_df2 <- NULL
reset <- cs_reset_test(X, yv, fitted_v, reset_power, reset_type)
if (!is.null(reset)) {
reset_f <- reset$statistic
reset_p <- reset$p
reset_df1 <- reset$df1
reset_df2 <- reset$df2
add_assumption(list(key = "linearity", label = "Linearity", status = if (reset_p < 0.05) "warn" else "pass", statistic = reset_f, p = reset_p,
detail = paste0(sprintf("RESET F(%d, %d) = %.2f, %s", as.integer(reset_df1), as.integer(reset_df2), reset_f, cs_fmt_p(reset_p)),
if (reset_p < 0.05) "; look for curvature or missing interactions." else ".")))
} else {
add_assumption(list(key = "linearity", label = "Linearity", status = "info",
detail = if (reset_type == "fitted") "RESET does not apply: the model already fits a separate mean for every combination of predictor values."
else "RESET does not apply: no numeric predictor with more than two values to raise to powers."))
}
Xo <- X[ord_idx, , drop = FALSE]
yo <- yv[ord_idx]
eo <- e[ord_idx]
order_note <- if (!is.null(order_col)) sprintf("rows ordered by %s", order_col) else "rows in stored order"
dw <- cs_durbin_watson(eo)
battery <- NULL
if (diagnostics == "full") {
lag_order <- as.integer(1)
battery <- list(bp_classic = cs_bp_classic(X, e), white = cs_white(X, e), gq = cs_goldfeld_quandt(Xo, yo),
hmc = cs_harrison_mccabe(Xo, eo), dw = cs_durbin_watson_exact(Xo, eo), bg = cs_breusch_godfrey(Xo, eo, lag_order),
arch = cs_arch_lm(eo, lag_order), hc = cs_harvey_collier(Xo, yo), rainbow = cs_rainbow(Xo, yo))
}
if (!is.null(battery)) {
bgt <- battery$bg
dwx <- battery$dw
add_assumption(list(key = "independence", label = "Independent residuals", status = if (bgt$p < 0.05) "warn" else "pass", statistic = bgt$statistic, p = bgt$p,
detail = paste0(sprintf("Breusch–Godfrey χ²(%d) = %.2f, %s; Durbin–Watson = %.2f", as.integer(bgt$df), bgt$statistic, cs_fmt_p(bgt$p), dw),
if (!is.null(dwx$p)) sprintf(" (exact %s for positive autocorrelation)", cs_fmt_p(dwx$p)) else "",
sprintf("; %s.", order_note),
if (bgt$p < 0.05) " Consider Newey–West standard errors or an AR(1) error model." else "")))
} else {
add_assumption(list(key = "independence", label = "Independent residuals", status = if (dw < 1.5 || dw > 2.5) "warn" else "info", statistic = dw,
detail = paste0(sprintf("Durbin–Watson = %.2f (≈ 2 when residuals in row order are uncorrelated; ", dw),
if (!is.null(order_col)) sprintf("%s).", order_note) else "only meaningful for ordered rows).")))
}
lev <- unname(hatvalues(fit0))
cooks <- unname(cooks.distance(fit0))
stud <- unname(rstudent(fit0))
std_resid <- unname(rstandard(fit0))
n_influential <- sum(cooks > 4 / n)
max_cooks <- max(cooks)
max_leverage <- max(lev)
add_assumption(list(key = "influence", label = "Influential points", status = if (max_cooks >= 1) "warn" else if (n_influential > 0) "info" else "pass",
statistic = max_cooks,
detail = paste0(sprintf("%d row(s) with Cook's distance above 4/n = %.3f; largest %.3f", n_influential, 4 / n, max_cooks),
if (max_cooks >= 1) " (≥ 1: refit without it to see whether conclusions change)." else ".")))
if (n < 10 * length(slope_idx)) warnings <- c(warnings, sprintf("Fewer than 10 rows per coefficient (%d rows, %d slopes): estimates may be unstable.", n, length(slope_idx)))
if (se_type == "cluster" && n_clusters < 30) {
warnings <- c(warnings, sprintf("Only %d clusters: cluster-robust standard errors can be too small with fewer than 30–50 clusters.", n_clusters))
}
if (!is.null(battery)) battery$outlier <- cs_bonferroni_outlier(stud, n - k - 1)
top <- head(order(-cooks, method = "radix"), 10)
influence_rows <- lapply(top, function(i) list(row = i, fitted = fitted_v[i], residual = e[i], studentized = stud[i], leverage = lev[i], cooks = cooks[i]))
# %% Simple slopes and Johnson-Neyman (first interacting pair with a numeric predictor)
values <- list()
slopes <- NULL
if (interactions != "none" && length(predictors) >= 2) slopes <- cs_simple_slopes(df, predictors, b, V, dfree, conf)
jn <- NULL
if (!is.null(slopes)) {
for (r in slopes$rows) {
values[[sprintf("slope[%s]", r$at)]] <- r$slope
values[[sprintf("slope_se[%s]", r$at)]] <- r$se
values[[sprintf("slope_p[%s]", r$at)]] <- r$p
values[[sprintf("slope_ci_low[%s]", r$at)]] <- r$ci_low
values[[sprintf("slope_ci_high[%s]", r$at)]] <- r$ci_high
}
if (!is.factor(df[[slopes$moderator]])) {
inter <- if (predictors[1] == slopes$focal) paste0(slopes$focal, " × ", slopes$moderator) else paste0(slopes$moderator, " × ", slopes$focal)
m <- df[[slopes$moderator]]
jn <- cs_johnson_neyman(b, V, slopes$focal, inter, dfree, 1 - conf, min(m), max(m))
values$jn_low <- jn$low
values$jn_high <- jn$high
values$jn_region <- jn$region
}
}
# %% Estimated marginal means (categorical predictors)
factors <- predictors[vapply(predictors, function(p) is.factor(df[[p]]), logical(1))]
covariates <- setdiff(predictors, factors)
emm_rows <- list()
pair_rows <- list()
simple_rows <- list()
emm_chart <- NULL
adjust <- "tukey"
if (TRUE && length(factors)) {
for (fac in factors) {
em <- cs_emmeans(fit0, df, fac, factors, covariates, conf = conf, vcov = V, df = dfree)
ct <- cs_emm_contrasts(fit0, df, fac, factors, covariates, adjust = adjust, conf = conf, vcov = V, df = dfree)
for (i in seq_len(nrow(em))) {
emm_rows[[length(emm_rows) + 1]] <- list(factor = fac, level = em$level[i], emm = em$emm[i], se = em$se[i], ci_low = em$ci_low[i], ci_high = em$ci_high[i])
values[[sprintf("emm[%s|%s]", fac, em$level[i])]] <- em$emm[i]
values[[sprintf("emm_se[%s|%s]", fac, em$level[i])]] <- em$se[i]
}
for (i in seq_len(nrow(ct))) {
pair_rows[[length(pair_rows) + 1]] <- list(factor = fac, contrast = ct$contrast[i], estimate = ct$estimate[i], se = ct$se[i], t = ct$t[i],
p_adj = ct$p_adj[i], ci_low = ct$ci_low[i], ci_high = ct$ci_high[i])
values[[sprintf("emm_diff[%s|%s]", fac, ct$contrast[i])]] <- ct$estimate[i]
values[[sprintf("emm_p_adj[%s|%s]", fac, ct$contrast[i])]] <- ct$p_adj[i]
}
}
a <- predictors[1]
bb <- if (length(predictors) > 1) predictors[2] else NULL
if (interactions != "none" && !is.null(bb) && a %in% factors && bb %in% factors) {
# Two interacting factors: EMMs of the first within each level of the second, with simple-effect tests.
em <- cs_emmeans(fit0, df, a, factors, covariates, by = bb, conf = conf, vcov = V, df = dfree)
emm_chart <- cs_chart("emm", "emm-plot", sprintf("Estimated marginal means of %s: %s by %s", y, a, bb), list(
x = cs_col(a, em$level, levels = levels(df[[a]])), mean = cs_col(paste0(y, " (EMM)"), em$emm),
low = cs_col("low", em$ci_low), high = cs_col("high", em$ci_high), trace = cs_col(bb, em$by, levels = levels(df[[bb]]))))
jt <- cs_emm_joint_test(fit0, df, a, factors, covariates, by = bb, vcov = V, df = dfree)
for (i in seq_len(nrow(jt))) {
simple_rows[[length(simple_rows) + 1]] <- list(at = sprintf("%s = %s", bb, jt$by[i]), effect = a, f = jt$f[i], df1 = jt$df1[i], df2 = jt$df2[i], p = jt$p[i])
}
} else {
em <- cs_emmeans(fit0, df, factors[1], factors, covariates, conf = conf, vcov = V, df = dfree)
emm_chart <- cs_chart("emm", "emm-plot", sprintf("Estimated marginal means of %s by %s", y, factors[1]), list(
x = cs_col(factors[1], em$level, levels = levels(df[[factors[1]]])), mean = cs_col(paste0(y, " (EMM)"), em$emm),
low = cs_col("low", em$ci_low), high = cs_col("high", em$ci_high)))
}
}
# %% Result
alpha <- 1 - conf
pct <- sprintf("%.0f%%", conf * 100)
significant <- vapply(Filter(function(cf) cf$term != "(Intercept)" && cf$p < alpha, coefs), `[[`, "", "term")
se_label <- if (se_type == "classical") "classical" else if (se_type == "cluster") sprintf("cluster-robust (CR1, %d clusters)", n_clusters) else if (se_type == "HAC") sprintf("Newey–West HAC (lag %d, %s)", as.integer(hac_lag), order_note) else sprintf("robust (%s)", se_type)
summary <- paste0(
sprintf("The model explains %.0f%% of the variance in %s (adjusted R² = %.2f, F(%.0f, %.0f) = %.2f, %s; n = %d). ",
r2 * 100, y, adj_r2, df1, df2, f, cs_fmt_p(f_p), n),
if (length(significant)) sprintf("Significant terms: %s.", paste(significant, collapse = ", ")) else "No individual term is significant."
)
values <- c(values, list(r_squared = r2, adj_r_squared = adj_r2, f2 = f2, f = f, df1 = df1, df2 = df2, f_p = f_p, sigma = sigma, n = n, k = k,
log_lik = log_lik, aic = aic, bic = bic, bp = bp, bp_p = bp_p, max_vif = max_vif,
sw_p_resid = if (is.null(sw)) NULL else sw$p.value, reset_f = reset_f, reset_p = reset_p, reset_df1 = reset_df1, reset_df2 = reset_df2, dw = dw,
max_cooks = max_cooks, n_influential = n_influential, max_leverage = max_leverage, se_type = se_type,
n_params = k, max_interaction_order = if (interactions != "none" && length(predictors) >= 2) 2 else 1, missing_share = if (n_input > 0) n_dropped / n_input else 0))
if (se_type == "cluster") values$n_clusters <- n_clusters
if (se_type == "HAC") values$hac_lag <- hac_lag
diag_rows <- list()
if (!is.null(battery)) {
diag <- function(test, bt, key, p_key, df_text, reads) {
if (is.null(bt)) {
diag_rows[[length(diag_rows) + 1]] <<- list(test = test, reads = "Not defined for this design.")
return(invisible())
}
values[[key]] <<- bt$statistic
values[[p_key]] <<- bt$p
diag_rows[[length(diag_rows) + 1]] <<- c(list(test = test, statistic = bt$statistic), if (!is.null(df_text)) list(df = df_text(bt)), list(p = bt$p, reads = reads))
}
diag("Breusch–Pagan (original, assumes normal errors)", battery$bp_classic, "bp_classic", "bp_classic_p", function(b) sprintf("χ²(%d)", as.integer(b$df)), "Variance changes with the predictors.")
diag("White (squares and cross-products)", battery$white, "white", "white_p", function(b) sprintf("χ²(%d)", as.integer(b$df)), "Variance changes with the predictors, possibly non-linearly.")
if (!is.null(battery$white)) values$white_df <- battery$white$df
diag("Goldfeld–Quandt (second half vs first)", battery$gq, "gq_f", "gq_p", function(b) sprintf("F(%d, %d)", as.integer(b$df1), as.integer(b$df2)), sprintf("Variance grows along the order (%s).", order_note))
diag("Harrison–McCabe (exact)", battery$hmc, "hmc", "hmc_p", NULL, "Small shares: the first half has less spread than the second.")
diag("Durbin–Watson (exact, positive)", battery$dw, "dw", "dw_p", NULL, "Neighboring residuals move together (lag 1).")
diag("Breusch–Godfrey", battery$bg, "bg", "bg_p", function(b) sprintf("χ²(%d)", as.integer(b$df)), sprintf("Residuals correlate with their previous %d value(s).", lag_order))
diag("ARCH LM (Engle)", battery$arch, "arch_lm", "arch_p", function(b) sprintf("χ²(%d)", as.integer(b$df)), "Large residuals cluster in time (volatility clustering).")
diag("Harvey–Collier (recursive residuals)", battery$hc, "hc_t", "hc_p", function(b) sprintf("t(%d)", as.integer(b$df)), "The relationship bends along the order.")
diag("Rainbow (central half)", battery$rainbow, "rainbow_f", "rainbow_p", function(b) sprintf("F(%d, %d)", as.integer(b$df1), as.integer(b$df2)), "The model fits the middle better than the whole range.")
ot <- battery$outlier
values$outlier_t <- ot$statistic
values$outlier_p_bonf <- ot$p
values$outlier_row <- ot$row
diag_rows[[length(diag_rows) + 1]] <- list(test = sprintf("Bonferroni outlier (row %d)", as.integer(ot$row)), statistic = ot$statistic, df = sprintf("t(%d)", as.integer(n - k - 1)),
p = ot$p, reads = "The most extreme studentized residual, after a Bonferroni correction for n rows.")
}
standardized <- TRUE
for (cf in coefs) {
for (pair in list(c("coef", "estimate"), c("se", "se"), c("t", "t"), c("p", "p"), c("ci_low", "ci_low"), c("ci_high", "ci_high"))) {
values[[sprintf("%s[%s]", pair[1], cf$term)]] <- cf[[pair[2]]]
}
if (standardized && !is.null(cf$std_beta)) values[[sprintf("std_beta[%s]", cf$term)]] <- cf$std_beta
}
coef_columns <- list(list(key = "term", label = "Term", type = "string"), list(key = "estimate", label = "Estimate", type = "number"),
list(key = "se", label = if (se_type == "classical") "SE" else sprintf("SE (%s)", se_type), type = "number"),
list(key = "t", label = "t", type = "number"), list(key = "p", label = "p", type = "pvalue"),
list(key = "ci_low", label = paste(pct, "CI low"), type = "number"), list(key = "ci_high", label = paste(pct, "CI high"), type = "number"))
if (standardized) coef_columns[[length(coef_columns) + 1]] <- list(key = "std_beta", label = "β (std.)", type = "number")
coef_rows <- lapply(coefs, function(cf) if (standardized) cf else cf[names(cf) != "std_beta"])
tables <- list(list(key = "coefficients", title = "Coefficients", columns = coef_columns, rows = coef_rows,
note = sprintf("Standard errors: %s; t tests with %s df.", se_label, format(df2))))
if (!is.null(slopes)) {
note <- NULL
if (!is.null(jn)) {
mod <- slopes$moderator
note <- paste0(switch(jn$region,
outside = sprintf("Johnson–Neyman: the slope is significant (α = %s) when %s < %.3f or > %.3f.", format(alpha), mod, jn$low, jn$high),
inside = sprintf("Johnson–Neyman: the slope is significant (α = %s) when %.3f < %s < %.3f.", format(alpha), jn$low, mod, jn$high),
all = sprintf("Johnson–Neyman: the slope is significant at every value of %s.", mod),
none = sprintf("Johnson–Neyman: the slope is not significant at any value of %s.", mod)),
sprintf(" Observed %s: %s to %s.", mod, format(min(df[[mod]])), format(max(df[[mod]]))))
}
tables[[length(tables) + 1]] <- list(key = "simple_slopes", title = sprintf("Simple slopes of %s", slopes$focal), columns = list(
list(key = "at", label = "At", type = "string"), list(key = "slope", label = "Slope", type = "number"),
list(key = "se", label = "SE", type = "number"), list(key = "t", label = "t", type = "number"), list(key = "p", label = "p", type = "pvalue"),
list(key = "ci_low", label = paste(pct, "CI low"), type = "number"), list(key = "ci_high", label = paste(pct, "CI high"), type = "number")),
rows = lapply(slopes$rows, function(r) r[names(r) != "value"]), note = note)
}
if (length(emm_rows)) {
tables[[length(tables) + 1]] <- list(key = "emm", title = "Estimated marginal means", columns = list(
list(key = "factor", label = "Factor", type = "string"), list(key = "level", label = "Level", type = "string"),
list(key = "emm", label = "EMM", type = "number"), list(key = "se", label = "SE", type = "number"),
list(key = "ci_low", label = paste(pct, "CI low"), type = "number"), list(key = "ci_high", label = paste(pct, "CI high"), type = "number")),
rows = emm_rows, note = "Other factors averaged with equal weights; numeric predictors at their means.")
tables[[length(tables) + 1]] <- list(key = "posthoc", title = "Pairwise comparisons of marginal means", columns = list(
list(key = "factor", label = "Factor", type = "string"), list(key = "contrast", label = "Contrast", type = "string"),
list(key = "estimate", label = "Difference", type = "number"), list(key = "se", label = "SE", type = "number"),
list(key = "t", label = "t", type = "number"), list(key = "p_adj", label = "p (adj.)", type = "pvalue"),
list(key = "ci_low", label = "CI low", type = "number"), list(key = "ci_high", label = "CI high", type = "number")),
rows = pair_rows, note = sprintf("Adjustment: %s (within each factor).", adjust))
}
if (length(simple_rows)) {
tables[[length(tables) + 1]] <- list(key = "simple_effects", title = "Simple effects", columns = list(
list(key = "at", label = "At", type = "string"), list(key = "effect", label = "Effect of", type = "string"),
list(key = "f", label = "F", type = "number"), list(key = "df1", label = "df1", type = "number"),
list(key = "df2", label = "df2", type = "number"), list(key = "p", label = "p", type = "pvalue")), rows = simple_rows)
}
if (length(diag_rows)) {
tables[[length(tables) + 1]] <- list(key = "diagnostics", title = "Specification and residual tests", columns = list(
list(key = "test", label = "Test", type = "string"), list(key = "statistic", label = "Statistic", type = "number"),
list(key = "df", label = "Reference", type = "string"), list(key = "p", label = "p", type = "pvalue"),
list(key = "reads", label = "A small p suggests", type = "string")),
rows = diag_rows, note = sprintf("Order-dependent tests use %s. Exact p-values assume normal errors (Imhof's method).", order_note))
}
tables[[length(tables) + 1]] <- list(key = "influence", title = "Most influential rows (Cook's distance)", columns = list(
list(key = "row", label = "Row", type = "integer"), list(key = "fitted", label = "Fitted", type = "number"),
list(key = "residual", label = "Residual", type = "number"), list(key = "studentized", label = "Studentized", type = "number"),
list(key = "leverage", label = "Leverage", type = "number"), list(key = "cooks", label = "Cook's D", type = "number")),
rows = influence_rows, note = "Row numbers count the rows used in the analysis (after missing values were left out).")
chart_rows <- unique(round(seq(1, n, length.out = min(n, 5000))))
charts <- list(cs_chart("residuals", "residual-panel", "Residual diagnostics", list(
fitted = cs_col("Fitted", fitted_v[chart_rows]), residual = cs_col("Residual", e[chart_rows]),
stdResidual = cs_col("Standardized residual", std_resid[chart_rows]), leverage = cs_col("Leverage", lev[chart_rows]),
cooks = cs_col("Cook's distance", cooks[chart_rows]))))
if (!is.null(emm_chart)) charts[[length(charts) + 1]] <- emm_chart
# %% Partial-regression charts: what each term adds, whether a numeric term bends, and Cook's distance by row.
panel_cols <- head(which(terms != "(Intercept)"), 9)
panel_rows <- unique(round(seq(1, n, length.out = min(n, 2000))))
row_names <- sprintf("row %d", panel_rows)
resid_on <- function(Z, v) if (ncol(Z)) as.numeric(qr.resid(qr(Z), v)) else as.numeric(v)
if (length(panel_cols)) {
av <- lapply(panel_cols, function(j) {
Z <- X[, -j, drop = FALSE]
list(x = resid_on(Z, X[, j])[panel_rows], y = resid_on(Z, yv)[panel_rows])
})
charts[[length(charts) + 1]] <- cs_chart("added-variable", "added-variable", "Added-variable plots", list(
x_res = cs_col("Predictor given the others", unlist(lapply(av, `[[`, "x")), "numeric"),
y_res = cs_col(sprintf("%s given the others", y), unlist(lapply(av, `[[`, "y")), "numeric"),
term = cs_col("Term", rep(terms[panel_cols], each = length(panel_rows)), "categorical", levels = terms[panel_cols]),
label = cs_col("Row", rep(row_names, length(panel_cols)), "categorical")
), note = if (k - intercept > 9) "The first 9 terms." else NULL)
}
# Component + residual needs a term that is one numeric column with no interaction to share its effect.
cr_cols <- if (interactions == "none") panel_cols[terms[panel_cols] %in% predictors] else integer(0)
if (length(cr_cols)) {
charts[[length(charts) + 1]] <- cs_chart("component-residual", "component-residual", "Component + residual plots", list(
x = cs_col("Predictor", unlist(lapply(cr_cols, function(j) X[panel_rows, j]), use.names = FALSE), "numeric"),
partial = cs_col("Component + residual", unlist(lapply(cr_cols, function(j) e[panel_rows] + b[[j]] * X[panel_rows, j]), use.names = FALSE), "numeric"),
term = cs_col("Term", rep(terms[cr_cols], each = length(panel_rows)), "categorical", levels = terms[cr_cols]),
label = cs_col("Row", rep(row_names, length(cr_cols)), "categorical")
))
}
charts[[length(charts) + 1]] <- cs_chart("influence-index", "influence-index", "Cook's distance by row", list(
cooks = cs_col("Cook's distance", cooks[chart_rows], "numeric"), index = cs_col("Row", as.numeric(chart_rows), "numeric")
))
cs_publish(list(
method = "regression.linear",
methodVersion = "2.0.1",
title = "Linear regression (OLS)",
engine = cs_engine_info("stats", "nanoparquet"),
n = n,
summary = summary,
apa = sprintf("R² = %s, adjusted R² = %s, F(%.0f, %.0f) = %s, %s", cs_fmt_num(r2, leading_zero = FALSE), cs_fmt_num(adj_r2, leading_zero = FALSE),
df1, df2, cs_fmt_num(f), cs_fmt_p(f_p)),
statistics = list(
list(key = "r_squared", label = "R²", value = r2), list(key = "adj_r_squared", label = "Adjusted R²", value = adj_r2),
list(key = "f", label = "F", value = f), list(key = "f_p", label = "p (F test)", value = f_p, format = "p"),
list(key = "sigma", label = "Residual SE", value = sigma), list(key = "aic", label = "AIC", value = aic)
),
tables = tables,
effectSizes = list(list(key = "f2", label = "Cohen's f²", value = f2, method = "R² / (1 − R²)"),
list(key = "r_squared", label = "R²", value = r2, method = "1 − SSres / SStot")),
assumptions = assumptions,
warnings = warnings,
notes = list(paste0("Ordinary least squares; categorical predictors use treatment contrasts with the first stored level as reference; ", se_label, " standard errors.",
if (interactions != "none") " With interactions, main effects are conditional on the other predictor being 0 (or at its reference level)." else "")),
charts = charts,
values = values
))
R² = .84, adjusted R² = .81, F(4, 27) = 34.79, p < .001
- R²
- 0.8375
- Adjusted R²
- 0.8134
- F
- 34.792
- p (F test)
- < .001
- Residual SE
- 2.603
- AIC
- 158.61
Effect size
- Cohen's f² 5.154
- R² 0.8375
To keep this page light, the plots are shown once, under the R tab.
Assumptions
- Normality of residuals — Shapiro–Wilk W = 0.959, p = .260.
- Constant variance — Breusch–Pagan (Koenker) χ²(4) = 6.87, p = .143.
- Multicollinearity — Largest VIF 3.61 (weight (1000 lbs)).
- Linearity — RESET F(2, 25) = 2.94, p = .071.
- Independent residuals — Durbin–Watson = 1.80 (≈ 2 when residuals in row order are uncorrelated; only meaningful for ordered rows).
- Influential points — 3 row(s) with Cook's distance above 4/n = 0.125; largest 0.210.
Coefficients
| Term | Estimate | SE | t | p | 95% CI low | 95% CI high | β (std.) |
|---|---|---|---|---|---|---|---|
| (Intercept) | 33.754 | 2.813 | 11.997 | < .001 | 27.981 | 39.526 | — |
| weight (1000 lbs) | −3.150 | 0.9080 | −3.469 | .002 | −5.013 | −1.286 | −0.5113 |
| cyl_f: 6 | −4.257 | 1.411 | −3.017 | .006 | −7.153 | −1.362 | −0.2967 |
| cyl_f: 8 | −6.079 | 1.684 | −3.611 | .001 | −9.534 | −2.624 | −0.5084 |
| manual: true | 0.1501 | 1.300 | 0.1154 | .909 | −2.518 | 2.818 | 0.0124 |
Standard errors: classical; t tests with 27 df.
Estimated marginal means
| Factor | Level | EMM | SE | 95% CI low | 95% CI high |
|---|---|---|---|---|---|
| cyl_f | 4 | 23.696 | 1.073 | 21.494 | 25.898 |
| cyl_f | 6 | 19.438 | 0.9970 | 17.393 | 21.484 |
| cyl_f | 8 | 17.616 | 0.9228 | 15.723 | 19.510 |
| manual | false | 20.175 | 0.7119 | 18.714 | 21.636 |
| manual | true | 20.325 | 0.9158 | 18.446 | 22.204 |
Other factors averaged with equal weights; numeric predictors at their means.
Pairwise comparisons of marginal means
| Factor | Contrast | Difference | SE | t | p (adj.) | CI low | CI high |
|---|---|---|---|---|---|---|---|
| cyl_f | 4 - 6 | 4.257 | 1.411 | 3.017 | .015 | 0.7583 | 7.756 |
| cyl_f | 4 - 8 | 6.079 | 1.684 | 3.611 | .003 | 1.904 | 10.254 |
| cyl_f | 6 - 8 | 1.822 | 1.383 | 1.317 | .398 | −1.608 | 5.252 |
| manual | false - true | −0.1501 | 1.300 | −0.1154 | .909 | −2.818 | 2.518 |
Adjustment: tukey (within each factor).
Most influential rows (Cook's distance)
| Row | Fitted | Residual | Studentized | Leverage | Cook's D |
|---|---|---|---|---|---|
| 17 | 10.840 | 3.860 | 1.795 | 0.2611 | 0.2103 |
| 21 | 25.990 | −4.490 | −2.041 | 0.2025 | 0.1894 |
| 20 | 28.124 | 5.776 | 2.591 | 0.1113 | 0.1387 |
| 18 | 26.975 | 5.425 | 2.389 | 0.1060 | 0.1152 |
| 32 | 25.148 | −3.748 | −1.622 | 0.1643 | 0.0975 |
| 3 | 26.597 | −3.797 | −1.590 | 0.1113 | 0.0600 |
| 29 | 17.840 | −2.040 | −0.8758 | 0.2060 | 0.0402 |
| 25 | 15.564 | 3.636 | 1.492 | 0.0835 | 0.0388 |
| 4 | 19.370 | 2.030 | 0.8579 | 0.1820 | 0.0331 |
| 31 | 16.581 | −1.581 | −0.6756 | 0.2086 | 0.0246 |
Row numbers count the rows used in the analysis (after missing values were left out).
- Fewer than 10 rows per coefficient (32 rows, 4 slopes): estimates may be unstable.
- Ordinary least squares; categorical predictors use treatment contrasts with the first stored level as reference; classical standard errors.
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Linear regression (OLS)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method regression.linear 2.0.1 · spec fe7c9c92f10ad7e6
# Dataset: mtcars (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
import numpy as np
import pandas as pd
import statsmodels.api as sm
import statsmodels.formula.api as smf
from scipy import linalg, stats
from statsmodels.stats.diagnostic import het_breuschpagan
from statsmodels.stats.outliers_influence import OLSInfluence
from statsmodels.stats.stattools import durbin_watson
import codesplash as cs
from codesplash.errors import check_not_constant
from codesplash.stats import emm as csemm
from codesplash.stats import regdiag as rd
from codesplash.stats import regression as csreg
# %% Data
df = pd.read_parquet("tests/parity/fixtures/mtcars.parquet", columns=["mpg", "weight (1000 lbs)", "cyl_f", "manual"])
n_input = len(df)
df["cyl_f"] = pd.Categorical(df["cyl_f"], categories=["4", "6", "8"]) # stored level order
df["manual"] = pd.Categorical(df["manual"], categories=["false", "true"]) # stored level order
df = df.dropna(subset=["mpg", "weight (1000 lbs)", "cyl_f", "manual"]) # listwise deletion over the analysis columns
df["cyl_f"] = df["cyl_f"].cat.remove_unused_categories()
df["manual"] = df["manual"].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", "weight (1000 lbs)", "cyl_f", "manual"]) # infinite values stop the run (registry/errors.yaml)
# %% Design matrix
y = "mpg"
predictors = ["weight (1000 lbs)", "cyl_f", "manual"]
conf = 0.95
interactions = "none" # none | first-two | all-pairs
se_type = "classical" # classical | HC0–HC3 | cluster | HAC
diagnostics = "standard" # standard | full
cluster = None
if se_type == "cluster" and cluster is None:
raise ValueError("Cluster-robust standard errors need a cluster column (the Cluster role).")
# Treatment contrasts: the first stored level of each categorical predictor is the reference (R's default);
# interaction columns in R's model.matrix order.
intercept = True
if not intercept and any(isinstance(df[p].dtype, pd.CategoricalDtype) for p in predictors):
raise ValueError("A model without an intercept takes numeric predictors only (a categorical predictor would need every level as a column).")
X = csreg.design_matrix(df, predictors, interactions, intercept=intercept)
# Degenerate input stops with a catalog error; R runs the same checks in the same order.
cs.check_rows(len(df), X.shape[1] + 1, "Linear regression") # more rows than coefficients
check_not_constant(df[y], y)
if intercept:
for p in predictors:
check_not_constant(df[p], p) # one value (or one level with data) is no variation
if np.linalg.matrix_rank(X.to_numpy()) < X.shape[1]:
cs.cs_error("CS_E_COLLINEAR")
n, k = X.shape
yv = df[y].to_numpy(dtype=float)
terms = list(X.columns)
order_col = None
ord_idx = np.arange(n)
# %% Fit
model = sm.OLS(yv, X)
fit0 = model.fit(method="qr") # classical fit (QR, like R's lm): R², residuals, diagnostics
if se_type in ("classical", "HAC"):
fit = fit0
elif se_type == "cluster":
groups = pd.factorize(df[cluster].astype(str))[0]
fit = model.fit(method="qr", cov_type="cluster", cov_kwds={"groups": groups}, use_t=True) # CR1: G/(G−1)·(n−1)/(n−k)
else:
fit = model.fit(method="qr", cov_type=se_type, use_t=True)
if se_type == "classical":
# σ²·R⁻¹R⁻ᵀ from the QR factor (as R's chol2inv): inverting X'X would square its condition number
r_inv = linalg.solve_triangular(np.linalg.qr(X.to_numpy(), mode="r"), np.eye(k))
V = fit0.scale * (r_inv @ r_inv.T)
elif se_type == "HAC":
V, hac_lag = rd.hac_cov(X.to_numpy()[ord_idx], np.asarray(fit0.resid)[ord_idx], None)
else:
V = np.asarray(fit.cov_params())
b = fit0.params.to_numpy()
n_clusters = int(df[cluster].nunique()) if se_type == "cluster" else None
dfree = float(n_clusters - 1) if se_type == "cluster" else float(n - k) # cluster-robust: t with G − 1 df
se = np.sqrt(np.diag(V))
tval = b / se
pval = 2 * stats.t.sf(np.abs(tval), dfree)
crit = stats.t.ppf(1 - (1 - conf) / 2, dfree)
beta = csreg.std_beta(X, yv, b)
coefs = [
{"term": term, "estimate": float(b[j]), "se": float(se[j]), "t": float(tval[j]), "p": float(pval[j]),
"ci_low": float(b[j] - crit * se[j]), "ci_high": float(b[j] + crit * se[j]), "std_beta": beta.get(term)}
for j, term in enumerate(terms)
]
r2, adj_r2 = float(fit0.rsquared), float(fit0.rsquared_adj)
slope_idx = [j for j, term in enumerate(terms) if term != "(Intercept)"]
f, df1 = csreg.wald_f(b, V, slope_idx) # = the classical F with classical SEs (all coefficients when there is no intercept)
df1, df2 = float(df1), dfree
f_p = float(stats.f.sf(f, df1, df2))
f2 = r2 / (1 - r2) if r2 < 1 else float("inf") # an exact fit has R² = 1
sigma = float(np.sqrt(fit0.scale))
log_lik = float(fit0.llf)
aic = -2 * log_lik + 2 * (k + 1) # pinned: k coefficients + σ (R's AIC; statsmodels' .aic omits σ)
bic = -2 * log_lik + np.log(n) * (k + 1)
# %% Assumptions
assumptions = []
resid = np.asarray(fit0.resid)
fitted = np.asarray(fit0.fittedvalues)
sw = stats.shapiro(resid) if 3 <= n <= 5000 else None
if sw is not None:
status = "pass" if sw.pvalue >= 0.05 else ("info" if n >= 50 else "warn")
assumptions.append({"key": "normality", "label": "Normality of residuals", "status": status, "statistic": float(sw.statistic), "p": float(sw.pvalue),
"detail": f"Shapiro–Wilk W = {sw.statistic:.3f}, {cs.fmt_p(sw.pvalue)}" + (" (with large n, judge the Q–Q plot)." if status == "info" else ".")})
# Koenker's studentized Breusch–Pagan (n·R² of e² on X, with a constant even when the model has none)
bp_X = X.to_numpy() if intercept else np.column_stack([np.ones(n), X.to_numpy()])
bp, bp_p, _, _ = het_breuschpagan(resid, bp_X)
robust = se_type != "classical"
assumptions.append({"key": "homoscedasticity", "label": "Constant variance", "status": "info" if robust else ("warn" if bp_p < 0.05 else "pass"),
"statistic": float(bp), "p": float(bp_p),
"detail": f"Breusch–Pagan (Koenker) χ²({bp_X.shape[1] - 1}) = {bp:.2f}, {cs.fmt_p(bp_p)}"
+ ("; the robust standard errors do not assume it." if robust else ("; consider robust (HC3) standard errors." if bp_p < 0.05 else "."))})
main_cols = [c for c in terms if c != "(Intercept)" and csreg.TIMES not in c]
vifs = csreg.gvif(X, main_cols, df, predictors) # one generalized VIF per factor
max_vif = None
if vifs:
worst = max(vifs, key=vifs.get)
max_vif = vifs[worst]
status = "pass" if max_vif < 5 else ("warn" if max_vif < 10 else "fail")
assumptions.append({"key": "multicollinearity", "label": "Multicollinearity", "status": status, "statistic": max_vif,
"detail": f"Largest VIF {max_vif:.2f} ({worst})" + ("; interaction columns are left out (their correlation with main effects is structural)." if len(main_cols) < len(slope_idx) else ".")})
# Ramsey RESET (powers of ŷ, or of each numeric predictor) — not defined when they add nothing
# (e.g. a model that fits every cell mean).
reset_type = "fitted"
reset_power = int(3)
reset = rd.reset(X.to_numpy(), yv, fitted, reset_power, reset_type)
if reset is not None:
reset_f, reset_p, reset_df1, reset_df2 = reset["statistic"], reset["p"], reset["df1"], reset["df2"]
assumptions.append({"key": "linearity", "label": "Linearity", "status": "warn" if reset_p < 0.05 else "pass", "statistic": reset_f, "p": reset_p,
"detail": f"RESET F({reset_df1}, {reset_df2}) = {reset_f:.2f}, {cs.fmt_p(reset_p)}" + ("; look for curvature or missing interactions." if reset_p < 0.05 else ".")})
else:
reset_f = reset_p = reset_df1 = reset_df2 = None
assumptions.append({"key": "linearity", "label": "Linearity", "status": "info",
"detail": "RESET does not apply: the model already fits a separate mean for every combination of predictor values." if reset_type == "fitted"
else "RESET does not apply: no numeric predictor with more than two values to raise to powers."})
Xo, yo, eo = X.to_numpy()[ord_idx], yv[ord_idx], resid[ord_idx]
order_note = f"rows ordered by {order_col}" if order_col else "rows in stored order"
dw = float(durbin_watson(eo))
battery = {}
if diagnostics == "full":
lag_order = int(1)
battery = {"bp_classic": rd.bp_classic(X.to_numpy(), resid), "white": rd.white(X.to_numpy(), resid), "gq": rd.goldfeld_quandt(Xo, yo),
"hmc": rd.harrison_mccabe(Xo, eo), "dw": rd.durbin_watson_exact(Xo, eo), "bg": rd.breusch_godfrey(Xo, eo, lag_order),
"arch": rd.arch_lm(eo, lag_order), "hc": rd.harvey_collier(Xo, yo), "rainbow": rd.rainbow(Xo, yo)}
if battery:
bg, dwx = battery["bg"], battery["dw"]
assumptions.append({"key": "independence", "label": "Independent residuals", "status": "warn" if bg["p"] < 0.05 else "pass", "statistic": bg["statistic"], "p": bg["p"],
"detail": f"Breusch–Godfrey χ²({bg['df']}) = {bg['statistic']:.2f}, {cs.fmt_p(bg['p'])}; Durbin–Watson = {dw:.2f}"
+ (f" (exact {cs.fmt_p(dwx['p'])} for positive autocorrelation)" if dwx["p"] is not None else "") + f"; {order_note}."
+ (" Consider Newey–West standard errors or an AR(1) error model." if bg["p"] < 0.05 else "")})
else:
assumptions.append({"key": "independence", "label": "Independent residuals", "status": "warn" if dw < 1.5 or dw > 2.5 else "info", "statistic": dw,
"detail": f"Durbin–Watson = {dw:.2f} (≈ 2 when residuals in row order are uncorrelated; " + (f"{order_note})." if order_col else "only meaningful for ordered rows).")})
infl = OLSInfluence(fit0)
lev = np.asarray(infl.hat_matrix_diag)
cooks = np.asarray(infl.cooks_distance[0])
stud = np.asarray(infl.resid_studentized_external)
std_resid = np.asarray(infl.resid_studentized_internal)
n_influential = int(np.sum(cooks > 4 / n))
max_cooks, max_leverage = float(cooks.max()), float(lev.max())
assumptions.append({"key": "influence", "label": "Influential points", "status": "warn" if max_cooks >= 1 else ("info" if n_influential else "pass"), "statistic": max_cooks,
"detail": f"{n_influential} row(s) with Cook's distance above 4/n = {4 / n:.3f}; largest {max_cooks:.3f}"
+ (" (≥ 1: refit without it to see whether conclusions change)." if max_cooks >= 1 else ".")})
if n < 10 * len(slope_idx):
warnings.append(f"Fewer than 10 rows per coefficient ({n} rows, {len(slope_idx)} slopes): estimates may be unstable.")
if se_type == "cluster" and n_clusters < 30:
warnings.append(f"Only {n_clusters} clusters: cluster-robust standard errors can be too small with fewer than 30–50 clusters.")
if battery:
battery["outlier"] = rd.bonferroni_outlier(stud, n - k - 1)
top = np.argsort(-cooks, kind="stable")[: min(10, n)]
influence_rows = [{"row": int(i + 1), "fitted": float(fitted[i]), "residual": float(resid[i]), "studentized": float(stud[i]),
"leverage": float(lev[i]), "cooks": float(cooks[i])} for i in top]
# %% Simple slopes and Johnson–Neyman (first interacting pair with a numeric predictor)
values = {}
slopes = None
coef_s = pd.Series(b, index=terms)
cov_s = pd.DataFrame(V, index=terms, columns=terms)
if interactions != "none" and len(predictors) >= 2:
slopes = csreg.simple_slopes(df, predictors, coef_s, cov_s, dfree, conf)
if slopes is not None:
focal, moderator, slope_rows = slopes
for r in slope_rows:
values.update({f"slope[{r['at']}]": r["slope"], f"slope_se[{r['at']}]": r["se"], f"slope_p[{r['at']}]": r["p"],
f"slope_ci_low[{r['at']}]": r["ci_low"], f"slope_ci_high[{r['at']}]": r["ci_high"]})
if not isinstance(df[moderator].dtype, pd.CategoricalDtype):
inter = f"{focal}{csreg.TIMES}{moderator}" if predictors[0] == focal else f"{moderator}{csreg.TIMES}{focal}"
m = df[moderator].to_numpy(dtype=float)
jn = csreg.johnson_neyman(coef_s, cov_s, focal, inter, dfree, 1 - conf, float(m.min()), float(m.max()))
values.update({k2: v for k2, v in (("jn_low", jn["low"]), ("jn_high", jn["high"]), ("jn_region", jn["region"])) if v is not None})
# %% Estimated marginal means (categorical predictors)
factors = [p for p in predictors if isinstance(df[p].dtype, pd.CategoricalDtype)]
covariates = [p for p in predictors if p not in factors]
emm_rows, pair_rows, simple_rows = [], [], []
emm_chart = None
if True and factors:
# The same model through the formula API (EMMs need its design info); estimates are identical.
# Newey–West: refit on the rows in time order (statsmodels' HAC with the n/(n − k) factor = rd.hac_cov).
ffit = smf.ols(csreg.patsy_formula(y, predictors, interactions), data=df.iloc[ord_idx] if se_type == "HAC" else df)
ffit = ffit.fit() if se_type == "classical" else (
ffit.fit(cov_type="cluster", cov_kwds={"groups": pd.factorize(df[cluster].astype(str))[0]}, use_t=True) if se_type == "cluster"
else ffit.fit(cov_type="HAC", cov_kwds={"maxlags": hac_lag, "use_correction": True}, use_t=True) if se_type == "HAC"
else ffit.fit(cov_type=se_type, use_t=True))
adjust = "tukey"
for fac in factors:
em = csemm.emmeans(ffit, df, fac, factors, covariates, conf=conf, df=dfree)
ct = csemm.contrasts(ffit, df, fac, factors, covariates, adjust=adjust, conf=conf, df=dfree)
for _, r in em.iterrows():
emm_rows.append({"factor": fac, "level": str(r["level"]), "emm": float(r["emm"]), "se": float(r["se"]),
"ci_low": float(r["ci_low"]), "ci_high": float(r["ci_high"])})
values[f"emm[{fac}|{r['level']}]"] = float(r["emm"])
values[f"emm_se[{fac}|{r['level']}]"] = float(r["se"])
for _, r in ct.iterrows():
pair_rows.append({"factor": fac, "contrast": str(r["contrast"]), "estimate": float(r["estimate"]), "se": float(r["se"]),
"t": float(r["t"]), "p_adj": float(r["p_adj"]), "ci_low": float(r["ci_low"]), "ci_high": float(r["ci_high"])})
values[f"emm_diff[{fac}|{r['contrast']}]"] = float(r["estimate"])
values[f"emm_p_adj[{fac}|{r['contrast']}]"] = float(r["p_adj"])
# Two interacting factors: EMMs of the first within each level of the second, with simple-effect tests.
a, bb = predictors[0], predictors[1] if len(predictors) > 1 else None
if interactions != "none" and bb is not None and a in factors and bb in factors:
em = csemm.emmeans(ffit, df, a, factors, covariates, by=bb, conf=conf, df=dfree)
emm_chart = cs.chart("emm", "emm-plot", f"Estimated marginal means of {y}: {a} by {bb}", {
"x": cs.col(a, em["level"].astype(str).to_numpy(), levels=[str(x) for x in df[a].cat.categories]),
"mean": cs.col(f"{y} (EMM)", em["emm"].to_numpy()), "low": cs.col("low", em["ci_low"].to_numpy()),
"high": cs.col("high", em["ci_high"].to_numpy()),
"trace": cs.col(bb, em["by"].astype(str).to_numpy(), levels=[str(x) for x in df[bb].cat.categories])})
jt = csemm.joint_test(ffit, df, a, factors, covariates, by=bb, df=dfree)
for _, r in jt.iterrows():
simple_rows.append({"at": f"{bb} = {r['by']}", "effect": a, "f": float(r["f"]), "df1": float(r["df1"]), "df2": float(r["df2"]), "p": float(r["p"])})
elif factors:
em = csemm.emmeans(ffit, df, factors[0], factors, covariates, conf=conf, df=dfree)
emm_chart = cs.chart("emm", "emm-plot", f"Estimated marginal means of {y} by {factors[0]}", {
"x": cs.col(factors[0], em["level"].astype(str).to_numpy(), levels=[str(x) for x in df[factors[0]].cat.categories]),
"mean": cs.col(f"{y} (EMM)", em["emm"].to_numpy()), "low": cs.col("low", em["ci_low"].to_numpy()),
"high": cs.col("high", em["ci_high"].to_numpy())})
# %% Result
alpha = 1 - conf
significant = [c["term"] for c in coefs if c["term"] != "(Intercept)" and c["p"] < alpha]
se_label = {"classical": "classical", "cluster": f"cluster-robust (CR1, {n_clusters} clusters)",
"HAC": f"Newey–West HAC (lag {hac_lag if se_type == 'HAC' else 0}, {order_note})"}.get(se_type, f"robust ({se_type})")
summary = (
f"The model explains {r2:.0%} of the variance in {y} (adjusted R² = {adj_r2:.2f}, F({df1:.0f}, {df2:.0f}) = {f:.2f}, {cs.fmt_p(f_p)}; n = {n}). "
+ (f"Significant terms: {', '.join(significant)}." if significant else "No individual term is significant.")
)
values.update({"r_squared": r2, "adj_r_squared": adj_r2, "f2": f2, "f": f, "df1": df1, "df2": df2, "f_p": f_p, "sigma": sigma,
"n": n, "k": k, "log_lik": log_lik, "aic": aic, "bic": bic, "bp": float(bp), "bp_p": float(bp_p), "max_vif": max_vif,
"sw_p_resid": None if sw is None else float(sw.pvalue), "reset_f": reset_f, "reset_p": reset_p, "dw": dw,
"max_cooks": max_cooks, "n_influential": n_influential, "max_leverage": max_leverage, "se_type": se_type,
"n_params": k, "max_interaction_order": 2 if interactions != "none" and len(predictors) >= 2 else 1, "missing_share": n_dropped / n_input if n_input else 0.0})
if se_type == "cluster":
values["n_clusters"] = n_clusters
if se_type == "HAC":
values["hac_lag"] = hac_lag
values.update({"reset_df1": reset_df1, "reset_df2": reset_df2})
diag_rows = []
if battery:
bt = battery
def diag(test, b, stat_key, key, p_key, df_text, reads):
if b is None:
diag_rows.append({"test": test, "statistic": None, "df": None, "p": None, "reads": "Not defined for this design."})
return
values[key] = b["statistic"]
values[p_key] = b["p"]
diag_rows.append({"test": test, "statistic": b["statistic"], "df": df_text(b) if df_text else None, "p": b["p"], "reads": reads})
diag("Breusch–Pagan (original, assumes normal errors)", bt["bp_classic"], "statistic", "bp_classic", "bp_classic_p", lambda b: f"χ²({b['df']})", "Variance changes with the predictors.")
diag("White (squares and cross-products)", bt["white"], "statistic", "white", "white_p", lambda b: f"χ²({b['df']})", "Variance changes with the predictors, possibly non-linearly.")
if bt["white"] is not None:
values["white_df"] = bt["white"]["df"]
diag("Goldfeld–Quandt (second half vs first)", bt["gq"], "statistic", "gq_f", "gq_p", lambda b: f"F({b['df1']}, {b['df2']})", f"Variance grows along the order ({order_note}).")
diag("Harrison–McCabe (exact)", bt["hmc"], "statistic", "hmc", "hmc_p", None, "Small shares: the first half has less spread than the second.")
diag("Durbin–Watson (exact, positive)", bt["dw"], "statistic", "dw", "dw_p", None, "Neighboring residuals move together (lag 1).")
diag("Breusch–Godfrey", bt["bg"], "statistic", "bg", "bg_p", lambda b: f"χ²({b['df']})", f"Residuals correlate with their previous {lag_order} value(s).")
diag("ARCH LM (Engle)", bt["arch"], "statistic", "arch_lm", "arch_p", lambda b: f"χ²({b['df']})", "Large residuals cluster in time (volatility clustering).")
diag("Harvey–Collier (recursive residuals)", bt["hc"], "statistic", "hc_t", "hc_p", lambda b: f"t({b['df']})", "The relationship bends along the order.")
diag("Rainbow (central half)", bt["rainbow"], "statistic", "rainbow_f", "rainbow_p", lambda b: f"F({b['df1']}, {b['df2']})", "The model fits the middle better than the whole range.")
ot = bt["outlier"]
values.update({"outlier_t": ot["statistic"], "outlier_p_bonf": ot["p"], "outlier_row": ot["row"]})
diag_rows.append({"test": f"Bonferroni outlier (row {ot['row']})", "statistic": ot["statistic"], "df": f"t({n - k - 1})", "p": ot["p"],
"reads": "The most extreme studentized residual, after a Bonferroni correction for n rows."})
for c in coefs:
values.update({f"{key}[{c['term']}]": c[key2] for key, key2 in
(("coef", "estimate"), ("se", "se"), ("t", "t"), ("p", "p"), ("ci_low", "ci_low"), ("ci_high", "ci_high"))})
if True and c["std_beta"] is not None:
values[f"std_beta[{c['term']}]"] = c["std_beta"]
pct = f"{conf:.0%}"
coef_columns = [{"key": "term", "label": "Term", "type": "string"}, {"key": "estimate", "label": "Estimate", "type": "number"},
{"key": "se", "label": "SE" if se_type == "classical" else f"SE ({se_type})", "type": "number"},
{"key": "t", "label": "t", "type": "number"}, {"key": "p", "label": "p", "type": "pvalue"},
{"key": "ci_low", "label": f"{pct} CI low", "type": "number"}, {"key": "ci_high", "label": f"{pct} CI high", "type": "number"}]
if True:
coef_columns.append({"key": "std_beta", "label": "β (std.)", "type": "number"})
tables = [{"key": "coefficients", "title": "Coefficients", "columns": coef_columns,
"rows": [{k2: v for k2, v in c.items() if k2 != "std_beta" or True} for c in coefs],
"note": f"Standard errors: {se_label}; t tests with {df2:g} df."}]
if slopes is not None:
tables.append({"key": "simple_slopes", "title": f"Simple slopes of {slopes[0]}", "columns": [
{"key": "at", "label": "At", "type": "string"}, {"key": "slope", "label": "Slope", "type": "number"},
{"key": "se", "label": "SE", "type": "number"}, {"key": "t", "label": "t", "type": "number"}, {"key": "p", "label": "p", "type": "pvalue"},
{"key": "ci_low", "label": f"{pct} CI low", "type": "number"}, {"key": "ci_high", "label": f"{pct} CI high", "type": "number"}],
"rows": [{k2: v for k2, v in r.items() if k2 != "value"} for r in slopes[2]],
"note": None if values.get("jn_region") is None else (
{"outside": f"Johnson–Neyman: the slope is significant (α = {alpha:g}) when {slopes[1]} < {values['jn_low']:.3f} or > {values['jn_high']:.3f}.",
"inside": f"Johnson–Neyman: the slope is significant (α = {alpha:g}) when {values['jn_low']:.3f} < {slopes[1]} < {values['jn_high']:.3f}.",
"all": f"Johnson–Neyman: the slope is significant at every value of {slopes[1]}.",
"none": f"Johnson–Neyman: the slope is not significant at any value of {slopes[1]}."}[values["jn_region"]]
+ f" Observed {slopes[1]}: {float(df[slopes[1]].min()):g} to {float(df[slopes[1]].max()):g}.")})
if emm_rows:
tables.append({"key": "emm", "title": "Estimated marginal means", "columns": [
{"key": "factor", "label": "Factor", "type": "string"}, {"key": "level", "label": "Level", "type": "string"},
{"key": "emm", "label": "EMM", "type": "number"}, {"key": "se", "label": "SE", "type": "number"},
{"key": "ci_low", "label": f"{pct} CI low", "type": "number"}, {"key": "ci_high", "label": f"{pct} CI high", "type": "number"}],
"rows": emm_rows, "note": "Other factors averaged with equal weights; numeric predictors at their means."})
tables.append({"key": "posthoc", "title": "Pairwise comparisons of marginal means", "columns": [
{"key": "factor", "label": "Factor", "type": "string"}, {"key": "contrast", "label": "Contrast", "type": "string"},
{"key": "estimate", "label": "Difference", "type": "number"}, {"key": "se", "label": "SE", "type": "number"},
{"key": "t", "label": "t", "type": "number"}, {"key": "p_adj", "label": "p (adj.)", "type": "pvalue"},
{"key": "ci_low", "label": "CI low", "type": "number"}, {"key": "ci_high", "label": "CI high", "type": "number"}],
"rows": pair_rows, "note": f"Adjustment: {adjust} (within each factor)."})
if simple_rows:
tables.append({"key": "simple_effects", "title": "Simple effects", "columns": [
{"key": "at", "label": "At", "type": "string"}, {"key": "effect", "label": "Effect of", "type": "string"},
{"key": "f", "label": "F", "type": "number"}, {"key": "df1", "label": "df1", "type": "number"},
{"key": "df2", "label": "df2", "type": "number"}, {"key": "p", "label": "p", "type": "pvalue"}], "rows": simple_rows})
if diag_rows:
tables.append({"key": "diagnostics", "title": "Specification and residual tests", "columns": [
{"key": "test", "label": "Test", "type": "string"}, {"key": "statistic", "label": "Statistic", "type": "number"},
{"key": "df", "label": "Reference", "type": "string"}, {"key": "p", "label": "p", "type": "pvalue"},
{"key": "reads", "label": "A small p suggests", "type": "string"}],
"rows": diag_rows, "note": f"Order-dependent tests use {order_note}. Exact p-values assume normal errors (Imhof's method)."})
tables.append({"key": "influence", "title": "Most influential rows (Cook's distance)", "columns": [
{"key": "row", "label": "Row", "type": "integer"}, {"key": "fitted", "label": "Fitted", "type": "number"},
{"key": "residual", "label": "Residual", "type": "number"}, {"key": "studentized", "label": "Studentized", "type": "number"},
{"key": "leverage", "label": "Leverage", "type": "number"}, {"key": "cooks", "label": "Cook's D", "type": "number"}],
"rows": influence_rows, "note": "Row numbers count the rows used in the analysis (after missing values were left out)."})
chart_rows = np.unique(np.round(np.linspace(0, n - 1, min(n, 5000))).astype(int))
charts = [cs.chart("residuals", "residual-panel", "Residual diagnostics", {
"fitted": cs.col("Fitted", fitted[chart_rows]), "residual": cs.col("Residual", resid[chart_rows]),
"stdResidual": cs.col("Standardized residual", np.asarray(std_resid)[chart_rows]),
"leverage": cs.col("Leverage", np.asarray(lev)[chart_rows]), "cooks": cs.col("Cook's distance", np.asarray(cooks)[chart_rows])})]
if emm_chart is not None:
charts.append(emm_chart)
# %% Partial-regression charts: what each term adds, whether a numeric term bends, and Cook's distance by row.
Xm = X.to_numpy()
panel_cols = [j for j, t in enumerate(terms) if t != "(Intercept)"][:9]
panel_rows = np.unique(np.round(np.linspace(0, n - 1, min(n, 2000))).astype(int))
row_names = [f"row {i + 1}" for i in panel_rows]
def resid_on(Z, v):
return v - Z @ np.linalg.lstsq(Z, v, rcond=None)[0] if Z.shape[1] else v
av_x, av_y, av_term, av_label = [], [], [], []
for j in panel_cols:
Z = np.delete(Xm, j, axis=1)
av_x += resid_on(Z, Xm[:, j])[panel_rows].tolist()
av_y += resid_on(Z, yv)[panel_rows].tolist()
av_term += [terms[j]] * len(panel_rows)
av_label += row_names
if panel_cols:
charts.append(cs.chart("added-variable", "added-variable", "Added-variable plots", {
"x_res": cs.col("Predictor given the others", av_x, "numeric"), "y_res": cs.col(f"{y} given the others", av_y, "numeric"),
"term": cs.col("Term", av_term, "categorical", levels=[terms[j] for j in panel_cols]), "label": cs.col("Row", av_label, "categorical"),
}, note=None if k - intercept <= 9 else "The first 9 terms."))
# Component + residual needs a term that is one numeric column with no interaction to share its effect.
cr_cols = [j for j in panel_cols if terms[j] in predictors] if interactions == "none" else []
if cr_cols:
cr_x, cr_y, cr_term, cr_label = [], [], [], []
b_hat = np.asarray(fit0.params)
for j in cr_cols:
cr_x += Xm[panel_rows, j].tolist()
cr_y += (resid[panel_rows] + b_hat[j] * Xm[panel_rows, j]).tolist()
cr_term += [terms[j]] * len(panel_rows)
cr_label += row_names
charts.append(cs.chart("component-residual", "component-residual", "Component + residual plots", {
"x": cs.col("Predictor", cr_x, "numeric"), "partial": cs.col("Component + residual", cr_y, "numeric"),
"term": cs.col("Term", cr_term, "categorical", levels=[terms[j] for j in cr_cols]), "label": cs.col("Row", cr_label, "categorical"),
}))
charts.append(cs.chart("influence-index", "influence-index", "Cook's distance by row", {
"cooks": cs.col("Cook's distance", np.asarray(cooks)[chart_rows], "numeric"), "index": cs.col("Row", (chart_rows + 1).tolist(), "numeric"),
}))
cs.publish({
"method": "regression.linear",
"methodVersion": "2.0.1",
"title": "Linear regression (OLS)",
"engine": cs.engine_info("pandas", "numpy", "statsmodels", "scipy"),
"n": n,
"summary": summary,
"apa": f"R² = {cs.fmt_num(r2, leading_zero=False)}, adjusted R² = {cs.fmt_num(adj_r2, leading_zero=False)}, F({df1:.0f}, {df2:.0f}) = {cs.fmt_num(f)}, {cs.fmt_p(f_p)}",
"statistics": [
{"key": "r_squared", "label": "R²", "value": r2}, {"key": "adj_r_squared", "label": "Adjusted R²", "value": adj_r2},
{"key": "f", "label": "F", "value": f}, {"key": "f_p", "label": "p (F test)", "value": f_p, "format": "p"},
{"key": "sigma", "label": "Residual SE", "value": sigma}, {"key": "aic", "label": "AIC", "value": aic},
],
"tables": tables,
"effectSizes": [{"key": "f2", "label": "Cohen's f²", "value": f2, "method": "R² / (1 − R²)"},
{"key": "r_squared", "label": "R²", "value": r2, "method": "1 − SSres / SStot"}],
"assumptions": assumptions,
"warnings": warnings,
"notes": [f"Ordinary least squares; categorical predictors use treatment contrasts with the first stored level as reference; {se_label} standard errors."
+ (" With interactions, main effects are conditional on the other predictor being 0 (or at its reference level)." if interactions != "none" else "")],
"charts": charts,
"values": values,
})
Here, cylinder groups are compared at the same weight and transmission. Heavier cars tend to have more cylinders, so the raw means mix the two.
The contrasts between marginal means come adjusted for multiple comparisons. They're usually what you'd plot for a reader.
One car, or the average car?
PredictPredict first
From the model of mpg on weight and horsepower, you want an interval for two things at the same weight and horsepower: the average mpg of all such cars, and the mpg of one new car. How do they compare?
Reveal
The one car's is wider. It carries the uncertainty about the line, plus the car's own scatter around it:
Here = 2.59 mpg.
What more data can't shrink
ReflectCollect a million cars, and the confidence interval for the average nearly vanishes, since goes to zero. The prediction intervalPrediction intervalThe range a future single value is expected to fall in; wider than a confidence interval for the mean. stops shrinking at about , because individual cars still differ.
Think of a forecast or score you've reported. Was your reader asking about the average, or about one case? Which interval did you give them?
When the spread isn't constant
PredictA prediction interval uses one everywhere. If spending varies more among high earners, it's too wide for some rows and too narrow for others.
Predict first
In simulated household data, spending spreads out as income rises. Compare the income slope at the median with the slope at the 90th percentile. What do you expect?
Reveal
Steeper at the 90th percentile. Quantile regressionQuantile regressionModels a chosen percentile of the outcome given the predictors, rather than its mean. It makes no normality assumption. fits any percentile directly. Read the quantile process on the card below: the income slope climbs from 0.27 at the 10th percentile to 0.34 at the median and 0.41 at the 90th.
pseudo-R¹ = 0.520, Wald F(3, 297) = 218.66, p < .001
- Wald F
- 218.66
- p
- < .001
- Pseudo-R¹
- 0.5204
Plots
View data
| B | high | Term | low |
|---|---|---|---|
| 0.3386 | 0.3652 | income | 0.3120 |
| 0.5571 | 1.431 | area: suburban | −0.3163 |
| 2.440 | 3.505 | area: urban | 1.375 |
View data
| Term | τ | B |
|---|---|---|
| income | 0.1000 | 0.2694 |
| area: suburban | 0.1000 | 1.735 |
| area: urban | 0.1000 | 3.437 |
| income | 0.2500 | 0.2841 |
| area: suburban | 0.2500 | 1.528 |
| area: urban | 0.2500 | 2.934 |
| income | 0.5000 | 0.3386 |
| area: suburban | 0.5000 | 0.5571 |
| area: urban | 0.5000 | 2.440 |
| income | 0.7500 | 0.3877 |
| area: suburban | 0.7500 | 1.062 |
| area: urban | 0.7500 | 4.205 |
| income | 0.9000 | 0.4058 |
| area: suburban | 0.9000 | 1.387 |
| area: urban | 0.9000 | 3.884 |
Assumptions
- Unique solution — The optimal coefficients are unique.
- Local density estimates — All 301 local density estimates are positive (bandwidth h = 0.1450).
- Non-crossing quantiles — Fitted quantiles increase with τ for every row.
- Linear conditional quantile — No assumption about the error distribution; the τ-th quantile of the outcome is assumed linear in the predictors, with independent rows.
Coefficients for the 0.5 quantile
| Term | B | SE | t | p | 95% CI low | 95% CI high |
|---|---|---|---|---|---|---|
| (Intercept) | 4.288 | 0.4119 | 10.411 | < .001 | 3.478 | 5.099 |
| income | 0.3386 | 0.0135 | 25.064 | < .001 | 0.3120 | 0.3652 |
| area: suburban | 0.5571 | 0.4438 | 1.255 | .210 | −0.3163 | 1.431 |
| area: urban | 2.440 | 0.5410 | 4.510 | < .001 | 1.375 | 3.505 |
Each slope is the change in the 0.5 quantile of spending per unit of the predictor (or versus the reference level).
Quantile process
| τ | Term | B | SE | 95% CI low | 95% CI high |
|---|---|---|---|---|---|
| 0.1000 | (Intercept) | 1.912 | 0.6723 | 0.5891 | 3.235 |
| 0.1000 | income | 0.2694 | 0.0190 | 0.2319 | 0.3069 |
| 0.1000 | area: suburban | 1.735 | 0.7356 | 0.2876 | 3.183 |
| 0.1000 | area: urban | 3.437 | 0.7361 | 1.988 | 4.886 |
| 0.2500 | (Intercept) | 3.422 | 0.7086 | 2.027 | 4.816 |
| 0.2500 | income | 0.2841 | 0.0125 | 0.2596 | 0.3086 |
| 0.2500 | area: suburban | 1.528 | 0.6710 | 0.2071 | 2.848 |
| 0.2500 | area: urban | 2.934 | 0.7255 | 1.506 | 4.362 |
| 0.5000 | (Intercept) | 4.288 | 0.4119 | 3.478 | 5.099 |
| 0.5000 | income | 0.3386 | 0.0135 | 0.3120 | 0.3652 |
| 0.5000 | area: suburban | 0.5571 | 0.4438 | −0.3163 | 1.431 |
| 0.5000 | area: urban | 2.440 | 0.5410 | 1.375 | 3.505 |
| 0.7500 | (Intercept) | 4.117 | 0.5852 | 2.965 | 5.268 |
| 0.7500 | income | 0.3877 | 0.0154 | 0.3574 | 0.4179 |
| 0.7500 | area: suburban | 1.062 | 0.5917 | −0.1022 | 2.227 |
| 0.7500 | area: urban | 4.205 | 0.6380 | 2.950 | 5.461 |
| 0.9000 | (Intercept) | 5.336 | 0.8480 | 3.667 | 7.005 |
| 0.9000 | income | 0.4058 | 0.0166 | 0.3732 | 0.4385 |
| 0.9000 | area: suburban | 1.387 | 0.8519 | −0.2892 | 3.064 |
| 0.9000 | area: urban | 3.884 | 0.7886 | 2.332 | 5.436 |
Slopes that change with τ mean the predictor affects the spread or shape of the outcome, not only its location.
- Linear program solved exactly (quantreg Barrodale–Roberts, refit at the vertex); Hendricks–Koenker (nid) sandwich standard errors with t tests on n − k = 297 df.
- Pseudo-R¹ (Koenker–Machado) is 1 − check loss of the model / check loss of the intercept-only quantile.
The exact R script · R R version 4.5.1 (2025-06-13)
# Quantile regression
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method regression.quantile 1.0.1 · spec bf40b7cc4cd28401
# Dataset: c3_quantile (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
library(codesplashr)
# %% Data
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/c3_quantile.parquet", col_select = c("spending", "income", "area")))
n_input <- nrow(df)
df[["area"]] <- factor(df[["area"]], levels = c("rural", "suburban", "urban")) # stored level order
df <- df[stats::complete.cases(df[c("spending", "income", "area")]), , 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("spending", "income", "area")) # infinite values stop the run (registry/errors.yaml)
# %% Design matrix
outcome <- "spending"
predictors <- c("income", "area")
tau <- 0.5 # the conditional quantile modeled (0.5 = median)
se_type <- "nid" # nid (Hendricks-Koenker) | ker (Powell kernel)
interactions <- "none" # none | first-two | all-pairs
process <- TRUE
conf <- 0.95
if (!(tau > 0 && tau < 1)) stop("The quantile τ must lie strictly between 0 and 1.")
# Treatment contrasts: the first stored level of each categorical predictor is the reference.
terms <- cs_design_labels(df, predictors, interactions)
n <- nrow(df)
k <- length(terms)
# Degenerate input stops with a catalog error; Python runs the same checks in the same order.
cs_check_rows(n, k + 2, "Quantile regression") # at least two more rows than coefficients
for (col in c(outcome, predictors)) cs_check_not_constant(df[[col]], col) # one value (or one level with data) is no variation
X <- model.matrix(cs_model_formula(outcome, predictors, interactions), data = df)
stopifnot(length(terms) == ncol(X))
colnames(X) <- terms
if (qr(X)$rank < ncol(X)) cs_error("CS_E_COLLINEAR")
y <- as.numeric(df[[outcome]])
covariance <- function(t, b) if (se_type == "nid") cs_rq_cov_nid(X, y, t) else cs_rq_cov_ker(X, y, t, b)
# %% Fit: quantreg's simplex, refit exactly at its vertex (identical in Python)
fit <- cs_rq_fit(X, y, tau)
beta <- fit$beta
nonunique <- cs_rq_nonunique(X, y, tau, beta, fit$h)
cv <- covariance(tau, beta)
V <- cv$cov
se <- sqrt(diag(V))
dfree <- n - k
tval <- beta / se
pval <- 2 * pt(abs(tval), dfree, lower.tail = FALSE)
crit <- qt(1 - (1 - conf) / 2, dfree)
loss <- cs_rq_check_loss(y - drop(X %*% beta), tau)
loss0 <- cs_rq_null_loss(y, tau)
r1 <- if (loss0 > 0) 1 - loss / loss0 else NULL # Koenker-Machado pseudo-R1
slopes <- 2:k
wald_f <- sum(beta[slopes] * solve(V[slopes, slopes, drop = FALSE], beta[slopes])) / length(slopes)
wald_p <- pf(wald_f, length(slopes), dfree, lower.tail = FALSE)
# %% Quantile process
taus <- if (process) sort(unique(c(0.1, 0.25, 0.5, 0.75, 0.9, round(tau, 10)))) else tau
process_rows <- list()
fitted <- NULL
values <- list()
for (t in taus) {
b_t <- if (t == tau) beta else cs_rq_fit(X, y, t)$beta
fitted <- cbind(fitted, drop(X %*% b_t))
if (!process) next
se_t <- if (t == tau) se else sqrt(diag(covariance(t, b_t)$cov))
for (j in seq_along(terms)) {
row <- list(tau = t, term = terms[j], estimate = b_t[j], se = se_t[j], ci_low = b_t[j] - crit * se_t[j], ci_high = b_t[j] + crit * se_t[j])
process_rows[[length(process_rows) + 1]] <- row
key <- sprintf("%s|%s", sprintf("%g", t), terms[j])
values[[sprintf("qcoef[%s]", key)]] <- row$estimate
values[[sprintf("qse[%s]", key)]] <- row$se
values[[sprintf("qci_low[%s]", key)]] <- row$ci_low
values[[sprintf("qci_high[%s]", key)]] <- row$ci_high
}
}
n_crossing <- if (process) cs_rq_crossing(fitted) else NULL
# %% Assumptions
assumptions <- list(list(key = "uniqueness", label = "Unique solution", status = if (nonunique) "warn" else "pass",
detail = if (nonunique) "Other coefficient values fit equally well (the optimum is a face, typical with tied outcomes or a whole-number n·τ); the estimate shown is one of them." else "The optimal coefficients are unique."))
if (se_type == "nid") {
bad <- cv$n_nonpositive
assumptions[[length(assumptions) + 1]] <- list(key = "sparsity", label = "Local density estimates", status = if (bad > 0) "warn" else "pass", statistic = bad,
detail = if (bad > 0) sprintf("%d of %d local density estimates were not positive (the fits at τ ± h cross there) and were set to zero.", bad, n)
else sprintf("All %d local density estimates are positive (bandwidth h = %.4f).", n, cv$bandwidth))
}
if (process) {
assumptions[[length(assumptions) + 1]] <- list(key = "crossing", label = "Non-crossing quantiles", status = if (n_crossing > 0) "warn" else "pass", statistic = n_crossing,
detail = if (n_crossing > 0) sprintf("Fitted quantiles for increasing τ cross for %d of %d rows (%.1f%%); the linear model may not hold across the distribution.", n_crossing, n, 100 * n_crossing / n)
else "Fitted quantiles increase with τ for every row.")
}
assumptions[[length(assumptions) + 1]] <- list(key = "linearity", label = "Linear conditional quantile", status = "info",
detail = "No assumption about the error distribution; the τ-th quantile of the outcome is assumed linear in the predictors, with independent rows.")
# %% Result
coefs <- lapply(seq_along(terms), function(j) list(term = terms[j], estimate = unname(beta[j]), se = unname(se[j]), t = unname(tval[j]), p = unname(pval[j]),
ci_low = unname(beta[j] - crit * se[j]), ci_high = unname(beta[j] + crit * se[j])))
for (cf in coefs) {
for (key in c("coef", "se", "t", "p", "ci_low", "ci_high")) values[[sprintf("%s[%s]", key, cf$term)]] <- if (key == "coef") cf$estimate else cf[[key]]
}
values <- c(values, list(tau = tau, n = n, k = k, r1 = r1, loss = loss, loss_null = loss0, wald_f = wald_f, wald_df1 = length(slopes),
wald_df2 = dfree, wald_p = wald_p, nonunique = nonunique, n_nonpositive = cv$n_nonpositive, bandwidth = cv$bandwidth,
se_type = se_type, n_crossing = n_crossing, crossing_share = if (process) n_crossing / n else NULL, n_params = k,
max_interaction_order = if (interactions != "none" && length(predictors) >= 2) 2 else 1,
missing_share = if (n_input > 0) n_dropped / n_input else 0))
name <- if (tau == 0.5) "Median regression" else sprintf("Quantile regression (τ = %s)", sprintf("%g", tau))
significant <- vapply(Filter(function(cf) cf$p < 1 - conf, coefs[-1]), `[[`, "", "term")
summary <- paste0(sprintf("%s of %s (n = %d): Wald F(%d, %d) = %.2f, %s; pseudo-R¹ = %.3f. ", name, outcome, n, length(slopes), dfree, wald_f, cs_fmt_p(wald_p), r1),
if (length(significant)) sprintf("Significant terms: %s.", paste(significant, collapse = ", ")) else "No individual term is significant.")
pct <- sprintf("%.0f%%", conf * 100)
se_name <- c(nid = "Hendricks–Koenker (nid) sandwich", ker = "Powell kernel sandwich")[[se_type]]
tables <- list(list(key = "coefficients", title = sprintf("Coefficients for the %s quantile", sprintf("%g", tau)), columns = list(
list(key = "term", label = "Term", type = "string"), list(key = "estimate", label = "B", type = "number"),
list(key = "se", label = "SE", type = "number"), list(key = "t", label = "t", type = "number"),
list(key = "p", label = "p", type = "pvalue"), list(key = "ci_low", label = paste(pct, "CI low"), type = "number"),
list(key = "ci_high", label = paste(pct, "CI high"), type = "number")),
rows = coefs, note = sprintf("Each slope is the change in the %s quantile of %s per unit of the predictor (or versus the reference level).", sprintf("%g", tau), outcome)))
sl <- coefs[-1]
charts <- list(cs_chart("coefficients", "forest", sprintf("Slopes at τ = %s", sprintf("%g", tau)), list(
label = cs_col("Term", vapply(sl, `[[`, "", "term"), kind = "categorical"), estimate = cs_col("B", vapply(sl, `[[`, 0, "estimate")),
low = cs_col("low", vapply(sl, `[[`, 0, "ci_low")), high = cs_col("high", vapply(sl, `[[`, 0, "ci_high"))), controls = list(reference = 0)))
if (process) {
tables[[2]] <- list(key = "process", title = "Quantile process", columns = list(
list(key = "tau", label = "τ", type = "number"), list(key = "term", label = "Term", type = "string"),
list(key = "estimate", label = "B", type = "number"), list(key = "se", label = "SE", type = "number"),
list(key = "ci_low", label = paste(pct, "CI low"), type = "number"), list(key = "ci_high", label = paste(pct, "CI high"), type = "number")),
rows = process_rows, note = "Slopes that change with τ mean the predictor affects the spread or shape of the outcome, not only its location.")
sr <- Filter(function(r) r$term != "(Intercept)", process_rows)
charts[[2]] <- cs_chart("process", "line", "Slopes across quantiles", list(
x = cs_col("τ", vapply(sr, `[[`, 0, "tau")), y = cs_col("B", vapply(sr, `[[`, 0, "estimate")),
group = cs_col("Term", vapply(sr, `[[`, "", "term"), kind = "categorical", levels = terms[-1])))
}
cs_publish(list(
method = "regression.quantile",
methodVersion = "1.0.1",
title = name,
engine = cs_engine_info("stats", "quantreg", "nanoparquet"),
n = n,
summary = summary,
apa = sprintf("pseudo-R¹ = %s, Wald F(%d, %d) = %.2f, %s", cs_fmt_num(r1, 3), length(slopes), dfree, wald_f, cs_fmt_p(wald_p)),
statistics = list(list(key = "wald_f", label = "Wald F", value = wald_f), list(key = "wald_p", label = "p", value = wald_p, format = "p"),
list(key = "r1", label = "Pseudo-R¹", value = r1)),
tables = tables,
effectSizes = list(),
assumptions = assumptions,
warnings = warnings,
notes = list(sprintf("Linear program solved exactly (quantreg Barrodale–Roberts, refit at the vertex); %s standard errors with t tests on n − k = %d df.", se_name, dfree),
"Pseudo-R¹ (Koenker–Machado) is 1 − check loss of the model / check loss of the intercept-only quantile."),
charts = charts,
values = values
))
pseudo-R¹ = 0.520, Wald F(3, 297) = 218.66, p < .001
- Wald F
- 218.66
- p
- < .001
- Pseudo-R¹
- 0.5204
To keep this page light, the plots are shown once, under the R tab.
Assumptions
- Unique solution — The optimal coefficients are unique.
- Local density estimates — All 301 local density estimates are positive (bandwidth h = 0.1450).
- Non-crossing quantiles — Fitted quantiles increase with τ for every row.
- Linear conditional quantile — No assumption about the error distribution; the τ-th quantile of the outcome is assumed linear in the predictors, with independent rows.
Coefficients for the 0.5 quantile
| Term | B | SE | t | p | 95% CI low | 95% CI high |
|---|---|---|---|---|---|---|
| (Intercept) | 4.288 | 0.4119 | 10.411 | < .001 | 3.478 | 5.099 |
| income | 0.3386 | 0.0135 | 25.064 | < .001 | 0.3120 | 0.3652 |
| area: suburban | 0.5571 | 0.4438 | 1.255 | .210 | −0.3163 | 1.431 |
| area: urban | 2.440 | 0.5410 | 4.510 | < .001 | 1.375 | 3.505 |
Each slope is the change in the 0.5 quantile of spending per unit of the predictor (or versus the reference level).
Quantile process
| τ | Term | B | SE | 95% CI low | 95% CI high |
|---|---|---|---|---|---|
| 0.1000 | (Intercept) | 1.912 | 0.6723 | 0.5891 | 3.235 |
| 0.1000 | income | 0.2694 | 0.0190 | 0.2319 | 0.3069 |
| 0.1000 | area: suburban | 1.735 | 0.7356 | 0.2876 | 3.183 |
| 0.1000 | area: urban | 3.437 | 0.7361 | 1.988 | 4.886 |
| 0.2500 | (Intercept) | 3.422 | 0.7086 | 2.027 | 4.816 |
| 0.2500 | income | 0.2841 | 0.0125 | 0.2596 | 0.3086 |
| 0.2500 | area: suburban | 1.528 | 0.6710 | 0.2071 | 2.848 |
| 0.2500 | area: urban | 2.934 | 0.7255 | 1.506 | 4.362 |
| 0.5000 | (Intercept) | 4.288 | 0.4119 | 3.478 | 5.099 |
| 0.5000 | income | 0.3386 | 0.0135 | 0.3120 | 0.3652 |
| 0.5000 | area: suburban | 0.5571 | 0.4438 | −0.3163 | 1.431 |
| 0.5000 | area: urban | 2.440 | 0.5410 | 1.375 | 3.505 |
| 0.7500 | (Intercept) | 4.117 | 0.5852 | 2.965 | 5.268 |
| 0.7500 | income | 0.3877 | 0.0154 | 0.3574 | 0.4179 |
| 0.7500 | area: suburban | 1.062 | 0.5917 | −0.1022 | 2.227 |
| 0.7500 | area: urban | 4.205 | 0.6380 | 2.950 | 5.461 |
| 0.9000 | (Intercept) | 5.336 | 0.8480 | 3.667 | 7.005 |
| 0.9000 | income | 0.4058 | 0.0166 | 0.3732 | 0.4385 |
| 0.9000 | area: suburban | 1.387 | 0.8519 | −0.2892 | 3.064 |
| 0.9000 | area: urban | 3.884 | 0.7886 | 2.332 | 5.436 |
Slopes that change with τ mean the predictor affects the spread or shape of the outcome, not only its location.
- Linear program solved exactly (HiGHS dual simplex, refit at the vertex); Hendricks–Koenker (nid) sandwich standard errors with t tests on n − k = 297 df.
- Pseudo-R¹ (Koenker–Machado) is 1 − check loss of the model / check loss of the intercept-only quantile.
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Quantile regression
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method regression.quantile 1.0.1 · spec bf40b7cc4cd28401
# Dataset: c3_quantile (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
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 quantreg as csqr
from codesplash.stats import regression as csreg
# %% Data
df = pd.read_parquet("tests/parity/fixtures/c3_quantile.parquet", columns=["spending", "income", "area"])
n_input = len(df)
df["area"] = pd.Categorical(df["area"], categories=["rural", "suburban", "urban"]) # stored level order
df = df.dropna(subset=["spending", "income", "area"]) # listwise deletion over the analysis columns
df["area"] = df["area"].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, ["spending", "income", "area"]) # infinite values stop the run (registry/errors.yaml)
# %% Design matrix
outcome = "spending"
predictors = ["income", "area"]
tau = 0.5 # the conditional quantile modeled (0.5 = median)
se_type = "nid" # nid (Hendricks–Koenker) | ker (Powell kernel)
interactions = "none" # none | first-two | all-pairs
process = True
conf = 0.95
if not 0 < tau < 1:
raise ValueError("The quantile τ must lie strictly between 0 and 1.")
# Treatment contrasts: the first stored level of each categorical predictor is the reference.
X = csreg.design_matrix(df, predictors, interactions)
n, k = X.shape
# Degenerate input stops with a catalog error; R runs the same checks in the same order.
cs.check_rows(n, k + 2, "Quantile regression") # at least two more rows than coefficients
for col in [outcome] + predictors:
check_not_constant(df[col], col) # one value (or one level with data) is no variation
if np.linalg.matrix_rank(X.to_numpy()) < X.shape[1]:
cs.cs_error("CS_E_COLLINEAR")
terms = list(X.columns)
Xv = X.to_numpy(dtype=float)
y = df[outcome].to_numpy(dtype=float)
def covariance(t, b):
return csqr.cov_nid(Xv, y, t) if se_type == "nid" else csqr.cov_ker(Xv, y, t, b)
# %% Fit: the linear program, refit exactly at its vertex (identical in R)
beta, basis = csqr.rq_fit(Xv, y, tau)
nonunique = csqr.nonunique(Xv, y, tau, beta, basis)
cv = covariance(tau, beta)
V = cv["cov"]
se = np.sqrt(np.diag(V))
dfree = n - k
tval = beta / se
pval = 2 * stats.t.sf(np.abs(tval), dfree)
crit = stats.t.ppf(1 - (1 - conf) / 2, dfree)
loss = csqr.check_loss(y - Xv @ beta, tau)
loss0 = csqr.null_loss(y, tau)
r1 = 1 - loss / loss0 if loss0 > 0 else None # Koenker–Machado pseudo-R¹
slopes = list(range(1, k))
wald_f = float(beta[slopes] @ np.linalg.solve(V[np.ix_(slopes, slopes)], beta[slopes])) / len(slopes)
wald_p = float(stats.f.sf(wald_f, len(slopes), dfree))
# %% Quantile process
taus = sorted({0.1, 0.25, 0.5, 0.75, 0.9, round(tau, 10)}) if process else [tau]
process_rows, fitted = [], []
values = {}
for t in taus:
b_t = beta if t == tau else csqr.rq_fit(Xv, y, t)[0]
fitted.append(Xv @ b_t)
if not process:
continue
se_t = se if t == tau else np.sqrt(np.diag(covariance(t, b_t)["cov"]))
for j, term in enumerate(terms):
row = {"tau": float(t), "term": term, "estimate": float(b_t[j]), "se": float(se_t[j]),
"ci_low": float(b_t[j] - crit * se_t[j]), "ci_high": float(b_t[j] + crit * se_t[j])}
process_rows.append(row)
key = f"{t:g}|{term}"
values.update({f"qcoef[{key}]": row["estimate"], f"qse[{key}]": row["se"], f"qci_low[{key}]": row["ci_low"], f"qci_high[{key}]": row["ci_high"]})
n_crossing = csqr.crossing(np.column_stack(fitted)) if process else None
# %% Assumptions
assumptions = [
{"key": "uniqueness", "label": "Unique solution", "status": "warn" if nonunique else "pass",
"detail": "Other coefficient values fit equally well (the optimum is a face, typical with tied outcomes or a whole-number n·τ); the estimate shown is one of them." if nonunique
else "The optimal coefficients are unique."},
]
if se_type == "nid":
bad = cv["n_nonpositive"]
assumptions.append({"key": "sparsity", "label": "Local density estimates", "status": "warn" if bad else "pass", "statistic": bad,
"detail": (f"{bad} of {n} local density estimates were not positive (the fits at τ ± h cross there) and were set to zero." if bad
else f"All {n} local density estimates are positive (bandwidth h = {cv['bandwidth']:.4f}).")})
if process:
share = n_crossing / n
assumptions.append({"key": "crossing", "label": "Non-crossing quantiles", "status": "warn" if n_crossing else "pass", "statistic": n_crossing,
"detail": (f"Fitted quantiles for increasing τ cross for {n_crossing} of {n} rows ({share:.1%}); the linear model may not hold across the distribution." if n_crossing
else "Fitted quantiles increase with τ for every row.")})
assumptions.append({"key": "linearity", "label": "Linear conditional quantile", "status": "info",
"detail": "No assumption about the error distribution; the τ-th quantile of the outcome is assumed linear in the predictors, with independent rows."})
# %% Result
coefs = [{"term": t, "estimate": float(beta[j]), "se": float(se[j]), "t": float(tval[j]), "p": float(pval[j]),
"ci_low": float(beta[j] - crit * se[j]), "ci_high": float(beta[j] + crit * se[j])} for j, t in enumerate(terms)]
for c in coefs:
values.update({f"{key}[{c['term']}]": c[key] if key != "coef" else c["estimate"] for key in ("coef", "se", "t", "p", "ci_low", "ci_high")})
values.update({"tau": tau, "n": n, "k": k, "r1": r1, "loss": loss, "loss_null": loss0, "wald_f": wald_f, "wald_df1": float(len(slopes)),
"wald_df2": float(dfree), "wald_p": wald_p, "nonunique": nonunique, "n_nonpositive": cv["n_nonpositive"], "bandwidth": cv["bandwidth"],
"se_type": se_type, "n_crossing": n_crossing, "crossing_share": (n_crossing / n) if process else None, "n_params": k,
"max_interaction_order": 2 if interactions != "none" and len(predictors) >= 2 else 1,
"missing_share": n_dropped / n_input if n_input else 0.0})
name = "Median regression" if tau == 0.5 else f"Quantile regression (τ = {tau:g})"
significant = [c["term"] for c in coefs[1:] if c["p"] < 1 - conf]
summary = (f"{name} of {outcome} (n = {n}): Wald F({len(slopes)}, {dfree}) = {wald_f:.2f}, {cs.fmt_p(wald_p)}; pseudo-R¹ = {r1:.3f}. "
+ (f"Significant terms: {', '.join(significant)}." if significant else "No individual term is significant."))
pct = f"{conf:.0%}"
se_name = {"nid": "Hendricks–Koenker (nid) sandwich", "ker": "Powell kernel sandwich"}[se_type]
tables = [
{"key": "coefficients", "title": f"Coefficients for the {tau:g} quantile", "columns": [
{"key": "term", "label": "Term", "type": "string"}, {"key": "estimate", "label": "B", "type": "number"},
{"key": "se", "label": "SE", "type": "number"}, {"key": "t", "label": "t", "type": "number"},
{"key": "p", "label": "p", "type": "pvalue"}, {"key": "ci_low", "label": f"{pct} CI low", "type": "number"},
{"key": "ci_high", "label": f"{pct} CI high", "type": "number"}],
"rows": coefs, "note": f"Each slope is the change in the {tau:g} quantile of {outcome} per unit of the predictor (or versus the reference level)."},
]
charts = [cs.chart("coefficients", "forest", f"Slopes at τ = {tau:g}", {
"label": cs.col("Term", [c["term"] for c in coefs[1:]], kind="categorical"), "estimate": cs.col("B", [c["estimate"] for c in coefs[1:]]),
"low": cs.col("low", [c["ci_low"] for c in coefs[1:]]), "high": cs.col("high", [c["ci_high"] for c in coefs[1:]])}, controls={"reference": 0})]
if process:
tables.append({"key": "process", "title": "Quantile process", "columns": [
{"key": "tau", "label": "τ", "type": "number"}, {"key": "term", "label": "Term", "type": "string"},
{"key": "estimate", "label": "B", "type": "number"}, {"key": "se", "label": "SE", "type": "number"},
{"key": "ci_low", "label": f"{pct} CI low", "type": "number"}, {"key": "ci_high", "label": f"{pct} CI high", "type": "number"}],
"rows": process_rows, "note": "Slopes that change with τ mean the predictor affects the spread or shape of the outcome, not only its location."})
slope_rows = [r for r in process_rows if r["term"] != "(Intercept)"]
charts.append(cs.chart("process", "line", "Slopes across quantiles", {
"x": cs.col("τ", [r["tau"] for r in slope_rows]), "y": cs.col("B", [r["estimate"] for r in slope_rows]),
"group": cs.col("Term", [r["term"] for r in slope_rows], kind="categorical", levels=terms[1:])}))
cs.publish({
"method": "regression.quantile",
"methodVersion": "1.0.1",
"title": name,
"engine": cs.engine_info("pandas", "numpy", "scipy"),
"n": n,
"summary": summary,
"apa": f"pseudo-R¹ = {cs.fmt_num(r1, 3)}, Wald F({len(slopes)}, {dfree}) = {wald_f:.2f}, {cs.fmt_p(wald_p)}",
"statistics": [{"key": "wald_f", "label": "Wald F", "value": wald_f}, {"key": "wald_p", "label": "p", "value": wald_p, "format": "p"},
{"key": "r1", "label": "Pseudo-R¹", "value": r1}],
"tables": tables,
"effectSizes": [],
"assumptions": assumptions,
"warnings": warnings,
"notes": [f"Linear program solved exactly (HiGHS dual simplex, refit at the vertex); {se_name} standard errors with t tests on n − k = {dfree} df.",
"Pseudo-R¹ (Koenker–Machado) is 1 − check loss of the model / check loss of the intercept-only quantile."],
"charts": charts,
"values": values,
})
Check your understanding
CheckpointCheck yourself
An average marginal effect of age is −0.004 on the probability of an event. What does it say?
Show the answer
Answer: a
It's an average of different changes on the probability scale. It isn't an odds ratio, and no one row has to match it.
Check yourself
A customer asks how long their own delivery will take. Which interval answers them?
Show the answer
Answer: b
One delivery carries its own scatter around the mean. A confidence interval for the mean would be far too narrow for this.
Check yourself
With a very large sample and = 2.59, about how far on each side of the prediction does a 95% prediction interval reach? Use 1.96 and give two decimals.
Show the answer
Answer: 5.08
1.96 × 2.59 ≈ 5.08. A larger sample won't reduce this, because it comes from the cars themselves.
Check yourself
Why report estimated marginal means rather than raw group means?
Show the answer
Answer: b
Raw means mix a group's effect with how its other predictors differ. Marginal means hold those fixed, under the model you fitted.
Do it on your data
In the appTurn on Average marginal effects for a logistic model, or Estimated marginal means for factors for a linear one. For a percentile, set Quantile (τ), and keep Quantile process on to see how the slopes change.
The cards don't print a prediction interval for a new row, so use a script for that one.
import pandas as pd
import statsmodels.formula.api as smf
cars = pd.read_csv("mtcars.csv")
ols = smf.ols("mpg ~ wt + hp", data=cars).fit()
new = pd.DataFrame({"wt": [3.0], "hp": [150]})
print(ols.get_prediction(new).summary_frame(alpha=0.05)) # mean_ci_* and obs_ci_*
births = pd.read_csv("birthwt.csv").rename(columns={"mother weight (lb)": "lwt"})
births["low"] = births["low"].astype(int)
logit = smf.logit("low ~ age + lwt + race + smoke + ht", data=births).fit(disp=0)
print(logit.get_margeff().summary())
spend = pd.read_csv("c3_quantile.csv")
print(smf.quantreg("spending ~ income", data=spend).fit(q=0.9).summary())library(quantreg)
cars_df <- read.csv("mtcars.csv")
ols <- lm(mpg ~ wt + hp, data = cars_df)
new <- data.frame(wt = 3, hp = 150)
predict(ols, new, interval = "confidence")
predict(ols, new, interval = "prediction")
births <- read.csv("birthwt.csv", check.names = FALSE)
names(births)[names(births) == "mother weight (lb)"] <- "lwt"
births$low <- births$low == "true"
logit <- glm(low ~ age + lwt + race + smoke + ht, data = births, family = binomial)
mean(dlogis(predict(logit))) * coef(logit)[c("age", "lwt")] # average marginal effects
spend <- read.csv("c3_quantile.csv")
summary(rq(spending ~ income, tau = 0.9, data = spend), se = "ker")Recap
Recap- An odds ratio has no single change in probability. Average marginal effects give one honest summary.
- Marginal means compare factor levels at the same values of the other predictors.
- A confidence interval is about the average, and a prediction interval is about one new case.
- When the spread changes, fit the percentile you care about with quantile regression.
Concepts in this lesson