Skip to content

Statistics or machine learning?

The question decides. Explanations need estimates you can defend, and predictions need scores you can trust on new data. See both on one dataset, and why the same model can serve either.

Applied ~11 min8 steps

What runs in CodeSplash

You will be able to

  • Decide whether a question calls for explaining or predicting
  • Compare a glass-box model with a boosted model honestly on held-out data
  • Explain why a p-value doesn't validate a predictor, and a score doesn't validate a cause

Read first

01

Two goals

Read

Explain: how does each input relate to the outcome, and how sure are you? You want coefficients, intervals and assumptions that hold.

Predict: for a new case, what will the outcome be? You want a score on data the model has never seen.

These pull in different directions. A model that predicts well can have useless coefficients, because correlated inputs trade off. A model with clean coefficients may predict poorly, because the question it answers wasn't about prediction.

02

One logistic model, two readings

Read

A logistic regression for low birth weight can be read either way.

  • Explaining: read the odds ratios and intervals. Ask whether the assumptions hold, and which variables to adjust for.
  • Predicting: read the discrimination: an AUC of 0.717 on the same rows it was fitted to, which flatters it. A prediction claim needs held-out data.
Logistic regressionRecorded · Python and R agreeRecorded 2026-11-25 · 103 values compared
R

χ²(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

ROC curve (AUC = 0.717)How well does a score separate positives from negatives at every cutoff?
View data
False-positive rateTrue-positive rate
00
0.00770
0.00770.0169
0.00770.0339
0.00770.0508
0.00770.0678
0.00770.0847
0.01540.0847
0.01540.1017
0.01540.1186
0.01540.1356
0.01540.1525
0.01540.1695
0.01540.1864
0.02310.1864
0.02310.2034
0.03080.2034
0.03850.2034
0.04620.2034
0.04620.2203
0.05380.2203
0.05380.2373
0.05380.2542
0.05380.2712
0.06150.2712
0.06920.2712
0.07690.2712
0.08460.2712
0.10000.2712
0.10000.2881
0.10770.2881
0.11540.2881
0.13080.2881
0.13080.3051
0.13850.3051
0.15380.3051
0.15380.3220
0.15380.3390
0.16150.3390
0.16920.3390
0.16920.3559
0.17690.3559
0.18460.3559
0.18460.3729
0.19230.3729
0.19230.3898
0.19230.4068
0.20000.4068
0.20770.4068
0.20770.4237
0.21540.4237
0.21540.4407
0.22310.4407
0.22310.4576
0.23080.4576
0.23080.4746
0.23850.4746
0.23850.4915
0.23850.5085
0.24620.5085

First 60 of 181 rows.

Calibration by risk groupDo predicted probabilities match observed frequencies?
View data
nObserved proportionPredicted probability
1900.0688
190.21050.1189
190.21050.1715
190.15790.2488
190.31580.2948
180.22220.3233
190.57890.3568
190.47370.3979
190.26320.4748
190.68420.6668
Odds ratiosHow large are several estimates, how precise, and which exclude the null?
View data
Odds ratiohighTermlow
0.97911.048age0.9142
0.98290.9962mother weight (lb)0.9697
3.4519.681race: black1.230
2.5075.791race: other1.085
2.9006.218smoke: true1.352
5.65721.787ht: true1.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

TermBSEzpOdds ratio95% CI low95% CI high
(Intercept)0.77731.1600.6699.5032.1760.223821.147
age−0.02120.0350−0.6054.5450.97910.91421.048
mother weight (lb)−0.01730.0069−2.519.0120.98290.96970.9962
race: black1.2390.52632.354.0193.4511.2309.681
race: other0.91910.42722.151.0312.5071.0855.791
smoke: true1.0650.38922.736.0062.9001.3526.218
ht: true1.7330.68792.519.0125.6571.46921.787

Modeled event: low = true; Wald intervals; Wald z tests.

Average marginal effects (probability scale)

PredictorAMESEp95% CI low95% CI high
age−0.00390.0065.544−0.01660.0088
mother weight (lb)−0.00320.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

ObservedPredicted truePredicted other
true1643
false8122

Accuracy 73.0%, sensitivity 27.1%, specificity 93.8%.

Hosmer–Lemeshow risk groups

GroupnObserved eventsExpected events
11901.307
21942.259
31943.259
41934.726
51965.601
61845.819
719116.779
81997.560
91959.021
10191312.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
))
Python

χ²(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

TermBSEzpOdds ratio95% CI low95% CI high
(Intercept)0.77731.1600.6699.5032.1760.223821.147
age−0.02120.0350−0.6054.5450.97910.91421.048
mother weight (lb)−0.01730.0069−2.519.0120.98290.96970.9962
race: black1.2390.52632.354.0193.4511.2309.681
race: other0.91910.42722.151.0312.5071.0855.791
smoke: true1.0650.38922.736.0062.9001.3526.218
ht: true1.7330.68792.519.0125.6571.46921.787

Modeled event: low = true; Wald intervals; Wald z tests.

Average marginal effects (probability scale)

PredictorAMESEp95% CI low95% CI high
age−0.00390.0065.544−0.01660.0088
mother weight (lb)−0.00320.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

ObservedPredicted truePredicted other
true1643
false8122

Accuracy 73.0%, sensitivity 27.1%, specificity 93.8%.

Hosmer–Lemeshow risk groups

GroupnObserved eventsExpected events
11901.307
21942.259
31943.259
41934.726
51965.601
61845.819
719116.779
81997.560
91959.021
10191312.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,
})
03

Will boosting win?

Predict

Predict first

Predicting diabetes from seven clinical measurements, with 426 training rows. You compare a plain logistic model with gradient boosting. What happens to the cross-validated AUC?

Boosting wins clearlyAbout the sameLinear wins clearly
Reveal

About the same: 0.857 for the logistic model and 0.843 for boosting. On 106 held-out rows they get 0.810 and 0.801. The gap is well within fold-to-fold noise. Small tabular data with mostly smooth effects often looks like this, and you would not know without the baseline.

04

See the trade-off

Explore

Raise the polynomial degree and watch the training error fall. Find the degree where the test error turns back up. Flexibility helps until it starts fitting noise.

DExplorable · The bias–variance trade-off

Why does a more flexible model eventually predict worse?

Which polynomial degree will predict new data best?

5
How sure?
3
25
0.30
Simulating…

Commit your prediction above to see the result

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

Make your prediction to see the result.

This is why machine learning's discipline is held-out evaluation: it is what tells you when flexibility stops paying.

05

Which validates which?

Read
StatisticsMachine learning
Trust comes fromDesign and assumptionsPerformance on new data
ReportsEstimates, intervals, p-valuesScores, calibration
Main dangerWrong model of the worldLeakage, drifting data

A high AUC doesn't show that a feature causes the outcome. A small p-value doesn't show a model will predict well. Each answers its own question.

06

Check your understanding

Checkpoint

Check yourself

A hospital wants to flag which patients are likely to be readmitted, so nurses can call them. What should drive the method choice?

Show the answer

Answer: a

The goal is to rank new patients. Coefficients are secondary; calibration and held-out performance matter.

Check yourself

A policy team asks whether a benefit change reduced poverty. What should drive the method choice?

Show the answer

Answer: b

"Did it reduce" is a causal question. Feature importance tells you what a model used, not what would happen if you intervened.

Check yourself

You select 5 of 200 features using a model's importances, then fit a logistic model on those 5 and report their p-values. What is wrong?

Show the answer

Answer: b

Selecting on the same data and then testing is double-dipping. Hold out a separate sample for the test, or use a method designed for inference after selection.

Check yourself

Why fit a simple baseline before a complex model?

Show the answer

Answer: b

The baseline sets the bar. A boosted model far above a plain one on small data is often worth a check for leakage.

07

Try both

In the app

For a classical fit, use Analyze. For held-out comparison, use Predict: start an experiment, add a linear learner and a boosted one, and read them on the leaderboard.

08

Recap

Recap
  • Explaining and predicting are different goals that need different evidence.
  • Compare any flexible model with a simple baseline on held-out data.
  • A score doesn't validate a cause, and a p-value doesn't validate a predictor.

Concepts in this lesson