Skip to content

Calibration and the Hosmer–Lemeshow test

Does a predicted 30% risk mean 30% of such cases have the event? Calibration asks that. Learn to read a calibration plot, and why Hosmer–Lemeshow is only a partial answer.

Applied ~9 min9 steps

What runs in CodeSplash

You will be able to

  • Distinguish calibration from discrimination
  • Read a calibration plot by risk group
  • Compute and read the Hosmer–Lemeshow statistic and its limits

Read first

01

Two different promises

Read

A model of risk makes two separate promises:

  • Discrimination: cases get higher predicted risks than non-cases. AUC measures this.
  • CalibrationCalibrationWhether predicted probabilities match observed frequencies — of cases given 30%, about 30% should be positive.: when the model says 30%, about 30% of such people have the event.

A model can rank perfectly and be badly calibrated: multiply every risk by a half, and AUC doesn't change at all. If people act on the probabilities themselves, calibration is what matters.

02

See it

Explore

HExplorable · Calibration and reliability

When a model says 80%, does the event happen 80% of the time?

If you make the model more overconfident, what happens to its AUC?

How sure?
2.00

Above 1 the model is too extreme; below 1 it hedges. At 1 it is perfectly calibrated.

2000
10
BrierECECalibration slopeAUC
0.1750.0870.500.835

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.

Bend the predicted probabilities away from the truth: too extreme, or too timid. Watch how the curve leaves the diagonal, and what happens to the summary numbers.

03

The Hosmer–Lemeshow test

Read

The Hosmer–LemeshowHosmer–Lemeshow testGroups rows by predicted risk and compares observed with expected events. It's a coarse check of calibration. test sorts rows by predicted risk into gg groups, usually ten, then compares observed and expected events:

C^=∑j=1g(Oj−Ej)2Ej (1−Ej/nj)  ∼  χg−22\hat C = \sum_{j=1}^{g} \frac{(O_j - E_j)^2}{E_j\,(1 - E_j/n_j)} \;\sim\; \chi^2_{g-2}

A small p-value suggests poor calibration. For the birthwt model, C^\hat C = 12.8 on 8 degrees of freedom, p = .118.

04

Make a prediction

Predict

Predict first

You rerun a similar model with 8 risk groups instead of 10. What happens to the p-value?

It stays the sameIt changesIt can't be computed with other group counts
Reveal

It changes, sometimes a lot. A simpler birthwt model with 6 degrees of freedom gives p = .646. The grouping is arbitrary, and results can depend on it. That's a good reason not to lean on this test alone.

05

Limits of the test

Read
  • It depends on the grouping. Different choices of gg can change your conclusion.
  • It has low power in small samples: a large p-value is weak evidence of good calibration.
  • It rejects trivia in large samples: with a million rows, tiny departures become significant.

So look at the plot first. The p-value is a supplement.

06

Read the plot

In the app
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,
})

Each point is a risk group: predicted risk across the bottom and observed rate up the side. Points on the diagonal are well calibrated. Note the Hosmer–Lemeshow risk groups table below it, and how few events each group has. A single group is noisy.

Calibration measured on the data used for fitting is optimistic. In Model, the same check runs on held-out data.

07

Check your understanding

Checkpoint

Check yourself

You divide every predicted risk by 2. What happens?

Show the answer

Answer: a

AUC depends only on the ordering of predictions, and dividing by 2 keeps the order. The probabilities themselves become wrong.

Check yourself

Hosmer–Lemeshow with 10 risk groups has how many degrees of freedom?

Show the answer

Answer: 8

g − 2 = 10 − 2 = 8.

Check yourself

Hosmer–Lemeshow gives p = .60 on 80 rows. What's a fair reading?

Show the answer

Answer: b

A large p-value isn't evidence of good fit, especially when the test can't see much. Look at the plot and its intervals.

Check yourself

Hosmer–Lemeshow's p-value moves when you change the number of risk groups. What should you report?

Show the answer

Answer: a

Trying group counts until one passes is a search. The test is one partial check, and the plot shows where predictions drift.

08

Check your model's calibration

In the app

Logistic regression cards include the plot and the test. Set Hosmer–Lemeshow groups to see how much the choice matters. To check a saved set of predicted probabilities, use the calibration method.

Python
import pandas as pd
import statsmodels.formula.api as smf
from scipy import stats

df = pd.read_csv("birthwt.csv").rename(columns={"mother weight (lb)": "lwt"})
df["low"] = df["low"].astype(int)
fit = smf.logit("low ~ age + lwt + smoke", data=df).fit(disp=0)
df["p"] = fit.predict(df)
df["g"] = pd.qcut(df["p"], 10, labels=False, duplicates="drop")
t = df.groupby("g").agg(O=("low", "sum"), E=("p", "sum"), n=("low", "size"))
c = ((t.O - t.E) ** 2 / (t.E * (1 - t.E / t.n))).sum()
print(c, stats.chi2.sf(c, len(t) - 2))
R
df <- read.csv("birthwt.csv", check.names = FALSE)
names(df)[names(df) == "mother weight (lb)"] <- "lwt"
df$low <- as.integer(df$low == "true")
fit <- glm(low ~ age + lwt + smoke, data = df, family = binomial)
df$p <- fitted(fit)
df$g <- cut(df$p, unique(quantile(df$p, 0:10 / 10)), include.lowest = TRUE)
t <- aggregate(cbind(O = low, E = p, n = 1) ~ g, data = df, FUN = sum)
c2 <- sum((t$O - t$E)^2 / (t$E * (1 - t$E / t$n)))
c(C = c2, p = pchisq(c2, nrow(t) - 2, lower.tail = FALSE))

These simple versions cut groups with default quantile rules, so their numbers can differ slightly from the app's.

09

Recap

Recap
  • Discrimination is ranking; calibration is whether the probabilities mean what they say.
  • Hosmer–Lemeshow compares observed and expected events across risk groups.
  • It depends on the grouping and on sample size, so read the plot first.
  • Check calibration on data the model didn't see.

Concepts in this lesson