Logistic regression: modeling yes or no
A straight line can predict impossible probabilities. Logistic regression models the log-odds instead. Learn to read odds ratios and spot separation.
What runs in CodeSplash
- Logistic regression (binary outcome) Verified in Python and R
You will be able to
- Explain the logit link and why a binary outcome needs it
- Convert a coefficient to an odds ratio and interpret it
- Read the model tests, pseudo-R², AUC and events per variable on a card
- Recognize separation and what to do about it
Why a line won't do
ReadFit a straight line to a 0/1 outcome and it will predict probabilities below 0 and above 1. The errors can't be normal either, since each one can take only two values.
Logistic regressionLogistic regressionModels the log-odds of a yes-or-no outcome as a linear function of the predictors. solves this by modeling the log-oddsLogitThe log of the odds, log(p / (1 − p)); logistic regression models it as a straight line. of the event as a straight line:
Whatever the right side is, stays between 0 and 1.
See the link
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.
Move the slope and watch the S-shaped curve steepen. The same change in does more to the probability near and very little near the extremes. That's why a coefficient has no single effect on the probability scale.
Odds ratios
ReadExponentiate a coefficient and you get an odds ratioOdds ratioHow many times higher the odds of an event are in one group than another; 1 means no difference.: the factor by which the odds multiply per unit of the predictor.
Odds aren't probabilities. Odds of 3 mean a probability of 3/4. An odds ratio of 2 doesn't double the probability, unless the event is rare enough that odds and probability are nearly the same.
Make a prediction
PredictPredict first
In the birthwt data, 59 of 189 babies had low birth weight. Holding the mother's age, weight, race and blood pressure fixed, what do you expect for a mother who smokes?
Reveal
The odds go up. The card's odds ratio for smoke is 2.90 (95% CI 1.35 to 6.22), so its interval excludes 1. It's a multiplier on the odds, not the probability.
Fitted by likelihood
ExploreThere's no closed form; the fit climbs the likelihood hill.
DExplorable · Climbing the logistic likelihood
How does logistic regression find its coefficients, and what if the data separate perfectly?
Where will the likelihood peak? Estimate the slope (6 means 6 or more).
Stronger color is more likely. The line shows Newton's steps from (0, 0). Drag the red point toward the summit. Your log-likelihood: −50.52; the maximum: −22.02.
Commit your prediction above to see the result
Make your prediction to see the result.
The overall test compares the model to the intercept alone: (6) = 26.8, p < .001.
Read the card
Readχ²(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,
})
Pseudo-R² values, such as Nagelkerke's 0.186, aren't shares of variance; use them only to compare models on the same data. AUC = 0.717 says how often a random case gets a higher predicted risk than a random non-case.
Sensitivity is only 0.271, while specificity is 0.938, at the default threshold. When events are the minority, a 0.5 cut misses most of them. Choosing a threshold is a decision about costs, set with Classification threshold.
Two things to check
ReadEvents per variable. With a binary outcome, your information comes mainly from the rarer class. Here 9.8 events per variable sits near the common rule of thumb of 10. Far below that, estimates become unstable and biased.
SeparationSeparationA predictor perfectly splits the outcome in logistic regression, so its coefficient runs to infinity.. If a predictor perfectly splits the outcome, its estimate runs off to infinity. Warning signs are huge coefficients and enormous standard errors. The card checks for it and offers remedies, since this is a sign of too little data rather than a strong effect.
Check your understanding
CheckpointCheck yourself
The odds of an event are 3. What's its probability?
Show the answer
Answer: 0.75
p = odds / (1 + odds) = 3/4 = 0.75.
Check yourself
A predictor has an odds ratio of 2 per unit. By what factor do the odds multiply for a 2-unit increase?
Show the answer
Answer: 4
Effects are additive on the log-odds scale, so they multiply on the odds scale: 2 × 2 = 4.
Check yourself
The event rate is 40% and an odds ratio is 2. Does the risk double to 80%?
Show the answer
Answer: b
Only when events are rare does an odds ratio approximate a risk ratio. Report predicted probabilities for common outcomes.
Check yourself
A logistic model gives a coefficient of 28 with a standard error of 4,000. What's the likely cause?
Show the answer
Answer: b
Under separation, the likelihood keeps rising as the coefficient grows. Consider Firth's correction or a penalized fit, and more data.
Fit yours
In the appPick a yes/no Outcome and your Predictors. Set Event so the odds refer to the level you mean.
import numpy as np
import pandas as pd
import statsmodels.formula.api as smf
df = pd.read_csv("birthwt.csv").rename(columns={"mother weight (lb)": "lwt"})
df["low"] = df["low"].astype(int)
fit = smf.logit("low ~ age + lwt + C(race) + smoke + ht", data=df).fit()
print(fit.summary())
print(np.exp(fit.params)) # odds ratios
print(np.exp(fit.conf_int())) # their Wald intervalsdf <- read.csv("birthwt.csv", check.names = FALSE)
names(df)[names(df) == "mother weight (lb)"] <- "lwt"
df$low <- df$low == "true"
fit <- glm(low ~ age + lwt + factor(race) + smoke + ht, data = df, family = binomial)
summary(fit)
exp(coef(fit)) # odds ratios
exp(confint.default(fit)) # their Wald intervalsRecap
Recap- Logistic regression models log-odds, which keeps probabilities in range.
- Exponentiated coefficients are odds ratios: multipliers on odds, not on probabilities.
- Check events per variable and separation.
- AUC measures ranking; a threshold is a separate decision about costs.
Concepts in this lesson