Skip to content

DRegression models · regression.logistic

Logistic regression (binary outcome)

How do predictors change the odds of a yes/no outcome?

Binary logistic regression (maximum likelihood, logit link) with numeric and categorical predictors and optional interactions: odds ratios with Wald or profile-likelihood intervals, the likelihood-ratio test against the intercept-only model, pseudo-R² (McFadden, Nagelkerke, Tjur), discrimination (AUC), calibration (Hosmer–Lemeshow), a classification table, average marginal effects, and checks for separation, events per variable and multicollinearity.

Verified in Python and R Python and R agree to 6 decimals

A real result

Example “Birthwt”, recorded in both engines. In the app, “Try this example” loads it into Analyze.

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).
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).

Do it in CodeSplash Run it on your own data, in Python or R, with the code to prove it.

Worked examples in the app

  • Birthwtbirthwt · outcome: low · predictors: age, mother weight (lb), race, smoke, ht
  • Profile interactionbirthwt · outcome: low · predictors: smoke, mother weight (lb)
  • Categorical eventmtcars · outcome: am_f · predictors: hp, weight (1000 lbs)
  • Hl eight groupsbirthwt · outcome: low · predictors: age, mother weight (lb), smoke
  • Missing valuessurvey · outcome: Sex · predictors: Height, Wr.Hnd
  • Degenerate constantbirthwt · outcome: low · predictors: age, mother weight (lb), race, smoke, ht
  • Degenerate n3birthwt · outcome: low · predictors: age, mother weight (lb), race, smoke, ht
  • Degenerate single levelbirthwt · outcome: low · predictors: age, mother weight (lb), race, smoke, ht

In the guides

Tests from the statistics guide this method runs

Where it sits in the decision guides

  • Association with covariates: linear / logistic regression · Statistics Guide · C — Test association
  • Binary outcome: logistic regression (regularized) · Statistics Guide · D — Predict an outcome
  • Post-estimation: robust SEs, marginal effects, contrasts · Statistics Guide · D — Predict an outcome
  • Regression diagnostics · Statistics Guide · D — Predict an outcome
  • Multiple predictors: logistic / ML · Statistics Guide · H — Diagnostic accuracy
  • PR curves, calibration, decision curves · Statistics Guide · H — Diagnostic accuracy
  • Sample size / expected counts · Statistics Guide · Step 2 — Check assumptions
  • Model-specific checks (VIF, PH, PO, dispersion) · Statistics Guide · Step 2 — Check assumptions
  • Generalized models · Statistics Guide · Step 3 — If assumptions are violated
  • Regression (linear, logistic, Poisson) · DS & ML Decision Guide · Predict — forecast or classify outcomes
  • Regression (linear, GLM), ANOVA, t-tests, chi-square · DS & ML Decision Guide · Explain — why is it happening?

What you need

Outcome (yes/no)boolean / categorical · 1 column · 2–2 levels
Two levels; the event is the level chosen below (default "true", or the second stored level).
Predictorsnumeric / categorical / boolean · 1–20 columns · 2–30 levels
Numeric predictors enter as is; categorical ones as dummy variables against their first level.

Choices you make

hypothesis

Event (modeled level)default —

The outcome level whose probability is modeled; default: the second level (true for yes/no columns).

Confidence leveldefault 0.95

How sure the intervals should be: 0.95 gives 95% confidence intervals. Higher confidence means wider intervals.

statistics

Interactionsdefault none

Add interaction terms so the effect of one predictor can depend on the value of another.

  • None (main effects only)(default) — Fits main effects only; the usual starting point and the easiest to read.
  • First two predictors (A × B) — Adds the A × B term for the first two predictors; pick it when you expect one effect to depend on the other.
  • All pairs of predictors — Adds every two-way term; uses many coefficients, so pick it with plenty of rows and a reason to look.
Confidence intervalsdefault wald

Wald is estimate ± z·SE; profile likelihood intervals are more accurate in small samples.

  • Wald (estimate ± z·SE)(default) — Estimate ± z·SE; fast, and fine in large samples.
  • Profile likelihood (better in small samples) — Follows the likelihood curve; slower, but better for small samples and rare events.
Average marginal effectsdefault on

Average change in the predicted probability per unit of each numeric predictor (not part of an interaction).

Classification thresholddefault 0.5

Predicted probability above which a row is classified as an event, for the classification table.

Advanced

Hosmer–Lemeshow groupsdefault 10

Rows are split into this many groups of predicted risk (deciles by default); fewer groups for small samples, so each group expects at least a few events.

Checks and remedies

CodeSplash checks each testable assumption on every run and shows the result on the card; premises the data can’t test are marked. If a check fails, these are the ways forward.

  • No (quasi-)complete separation

    When a predictor splits events from non-events perfectly, estimates and standard errors blow up; Firth's penalized likelihood is the remedy.

  • Events per variable

    At least 10 events (of the rarer outcome) per estimated slope is the usual rule.

    • If violated → Profile-likelihood intervals — With few events per variable, Wald intervals for odds ratios are unreliable; profile-likelihood intervals keep closer to nominal coverage. Also consider fewer predictors.
  • Multicollinearity (VIF)

  • Calibration (Hosmer–Lemeshow)

    Observed against expected events within groups of predicted risk; χ² with groups − 2 df. A small p means the predicted probabilities are off somewhere along the range.

  • Linearity in the logit

    Numeric predictors are assumed to act linearly on the log odds.

What it reports

  • Tests: Model vs intercept only (likelihood-ratio test)
n
How many independent units the analysis used; it sets precision and power.
n_events
How many independent units the analysis used; it sets precision and power.
k
How many groups, studies or clusters the analysis used. Many methods are less reliable when k is small.
event_level
In time-to-event data, the outcome happening (death, failure, churn). Rows without it by the end of follow-up are censored.
log_lik
The logarithm of the likelihood; higher (less negative) means the model fits the data better.
null_log_lik
How well a model with no predictors fits. The likelihood-ratio test compares the fitted model with it.
deviance
Twice the gap in log-likelihood between a model and a perfect fit; GLMs' analog of the residual sum of squares.
lr_chi2
A sum of squared, scaled differences between observed and expected counts or estimates.
lr_df
Compares nested models by how much the log-likelihood improves when parameters are added.
lr_p
Compares nested models by how much the log-likelihood improves when parameters are added.
mcfadden_r2
An R²-like summary for models without a usual R². Versions differ, and none reads as variance explained.
cox_snell_r2
An R²-like summary for models without a usual R². Versions differ, and none reads as variance explained.
nagelkerke_r2
An R²-like summary for models without a usual R². Versions differ, and none reads as variance explained.
tjur_r2
An R²-like summary for models without a usual R². Versions differ, and none reads as variance explained.
aic
A model score balancing fit against complexity; lower is better, and only differences matter.
bic
Like AIC but with a stronger penalty for parameters as n grows; favors simpler models.
auc
The chance a random positive scores higher than a random negative; 0.5 is guessing, 1 is perfect ranking.
hl_chi2
A sum of squared, scaled differences between observed and expected counts or estimates.
hl_df
How much independent information is left to estimate variability after fitting the model.
hl_p
How surprising your data would be if the null hypothesis were true, as a probability.
accuracy
The share of predictions that are right; misleading when classes are imbalanced.
sensitivity
The share of real positives the test catches.
specificity
The share of real negatives the test correctly clears.
epv
Events (the rarer outcome) per estimated coefficient in logistic or Cox models.
max_vif
How much a coefficient's variance is inflated by correlation with the other predictors.
n_extreme
How many independent units the analysis used; it sets precision and power.
ci_method
A range of effect values compatible with your data at the chosen confidence level.
separation
A predictor perfectly splits the outcome in logistic regression, so its coefficient runs to infinity.
converged
Whether an iterative fit found a stable solution; warnings mean estimates may be unreliable.
n_params
How many values a model learns from the data: a regression's coefficients (intercept included) or a network's weights and biases.
max_interaction_order
The most factors combined in one term of the model: 1 means main effects only, 2 two-way interactions.
missing_share
Values that were not recorded; how they went missing decides which fixes are safe.

Per group, level or term: coef[<term>], se[…], z[…], p[…], ci_low[…], ci_high[…], or[…], or_ci_low[…], or_ci_high[…], ame[<term>], ame_se[…], ame_ci_low[…], ame_ci_high[…]

Python and R

Python and R agree to 6 decimals (relative tolerance 1e-7). Python uses pandas, numpy, statsmodels, scipy, codesplash; R uses stats, nanoparquet, codesplashr.

Default traps between the two languages

  • IRLS in both engines with a 1e-12 relative deviance tolerance (statsmodels GLM / R glm.fit): coefficients agree to ~1e-10.
  • Fitted probabilities are rounded to 12 decimals before AUC, Hosmer–Lemeshow grouping and classification, so near-ties are ties in both engines.
  • Profile-likelihood intervals use the codesplash twin (exact root of the profile deviance) in both engines; R's confint() would interpolate a spline over a grid (≈1e-4).
Python

The exact script CodeSplash ran for example “Birthwt” · 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,
})
R

The exact script CodeSplash ran for example “Birthwt” · 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
))

Sources

  • Hosmer, D. W., Lemeshow, S., & Sturdivant, R. X. (2013). Applied logistic regression (3rd ed.). Wiley.
  • Tjur, T. (2009). Coefficients of determination in logistic regression models. The American Statistician, 63, 366–372.
  • Peduzzi, P., et al. (1996). A simulation study of the number of events per variable in logistic regression analysis. Journal of Clinical Epidemiology, 49, 1373–1379.

From the CodeSplash method registry · regression.logistic v2.0.2.