DRegression models · regression.count
Count regression (Poisson / negative binomial)
How do predictors change the expected count (or rate) of events?
Poisson, quasi-Poisson or negative binomial (NB2) regression with a log link and an optional exposure (log offset, so effects are on rates): incidence-rate ratios with intervals, the test against the intercept-only model, an overdispersion test (Cameron–Trivedi), observed vs expected zeros and a rootogram of observed and fitted count frequencies.
A real result
Example “Poisson warpbreaks”, recorded in both engines. In the app, “Try this example” loads it into Analyze.
χ²(3, N = 54) = 86.98, p < .001
- LR χ²
- 86.980
- p
- < .001
- Pearson dispersion
- 4.262
- AIC
- 493.06
Plots
View data
| Count | Expected | Observed |
|---|---|---|
| 0 | 3.323e-8 | 0 |
| 1 | 6.497e-7 | 0 |
| 2 | 6.360e-6 | 0 |
| 3 | 4.157e-5 | 0 |
| 4 | 0.0002 | 0 |
| 5 | 0.0008 | 0 |
| 6 | 0.0026 | 0 |
| 7 | 0.0075 | 0 |
| 8 | 0.0186 | 0 |
| 9 | 0.0412 | 0 |
| 10 | 0.0826 | 1 |
| 11 | 0.1516 | 0 |
| 12 | 0.2568 | 1 |
| 13 | 0.4047 | 1 |
| 14 | 0.5976 | 1 |
| 15 | 0.8322 | 3 |
| 16 | 1.099 | 2 |
| 17 | 1.384 | 2 |
| 18 | 1.668 | 3 |
| 19 | 1.934 | 2 |
| 20 | 2.165 | 2 |
| 21 | 2.350 | 4 |
| 22 | 2.481 | 0 |
| 23 | 2.557 | 0 |
| 24 | 2.580 | 2 |
| 25 | 2.558 | 1 |
| 26 | 2.499 | 4 |
| 27 | 2.413 | 1 |
| 28 | 2.307 | 3 |
| 29 | 2.189 | 4 |
| 30 | 2.065 | 2 |
| 31 | 1.940 | 1 |
| 32 | 1.815 | 0 |
| 33 | 1.692 | 0 |
| 34 | 1.573 | 0 |
| 35 | 1.458 | 1 |
| 36 | 1.346 | 2 |
| 37 | 1.238 | 0 |
| 38 | 1.133 | 0 |
| 39 | 1.031 | 2 |
| 40 | 0.9316 | 0 |
| 41 | 0.8347 | 1 |
| 42 | 0.7406 | 1 |
| 43 | 0.6499 | 1 |
| 44 | 0.5633 | 1 |
| 45 | 0.4817 | 0 |
| 46 | 0.4061 | 0 |
| 47 | 0.3371 | 0 |
| 48 | 0.2755 | 0 |
| 49 | 0.2215 | 0 |
| 50 | 0.1751 | 0 |
View data
| Rate ratio | high | Term | low |
|---|---|---|---|
| 0.8138 | 0.9004 | wool: B | 0.7356 |
| 0.7252 | 0.8161 | tension: M | 0.6444 |
| 0.5954 | 0.6749 | tension: H | 0.5253 |
View data
| Scaled residual |
|---|
| 0.0247 |
| 0.0524 |
| 0.9760 |
| 0.0199 |
| 1 |
| 0.9746 |
| 0.9566 |
| 0.0042 |
| 1 |
| 0.0120 |
| 0.0711 |
| 0.4979 |
| 0.0064 |
| 0 |
| 0.0132 |
| 0.8534 |
| 0.6296 |
| 0.8802 |
| 0.9828 |
| 0.2053 |
| 0.4975 |
| 0.0926 |
| 0 |
| 1 |
| 0.7656 |
| 0.0313 |
| 0.7272 |
| 0.1863 |
| 0 |
| 0.2758 |
| 0.0017 |
| 0.2583 |
| 0.4143 |
| 0.9306 |
| 0.0108 |
| 0.9633 |
| 1 |
| 0.7419 |
| 0.1398 |
| 0.0481 |
| 1 |
| 0.8219 |
| 0.2886 |
| 1 |
| 0.8840 |
| 0.5331 |
| 0.7088 |
| 0.9120 |
| 0.2680 |
| 0.0536 |
| 0.1825 |
| 0.1809 |
| 0.2428 |
| 0.9685 |
View data
| Predicted value (rank, 0–1) | Scaled residual |
|---|---|
| 0.9259 | 0.0247 |
| 0.9259 | 0.0524 |
| 0.9259 | 0.9760 |
| 0.9259 | 0.0199 |
| 0.9259 | 1 |
| 0.9259 | 0.9746 |
| 0.9259 | 0.9566 |
| 0.9259 | 0.0042 |
| 0.9259 | 1 |
| 0.5926 | 0.0120 |
| 0.5926 | 0.0711 |
| 0.5926 | 0.4979 |
| 0.5926 | 0.0064 |
| 0.5926 | 0 |
| 0.5926 | 0.0132 |
| 0.5926 | 0.8534 |
| 0.5926 | 0.6296 |
| 0.5926 | 0.8802 |
| 0.4259 | 0.9828 |
| 0.4259 | 0.2053 |
| 0.4259 | 0.4975 |
| 0.4259 | 0.0926 |
| 0.4259 | 0 |
| 0.4259 | 1 |
| 0.4259 | 0.7656 |
| 0.4259 | 0.0313 |
| 0.4259 | 0.7272 |
| 0.7593 | 0.1863 |
| 0.7593 | 0 |
| 0.7593 | 0.2758 |
| 0.7593 | 0.0017 |
| 0.7593 | 0.2583 |
| 0.7593 | 0.4143 |
| 0.7593 | 0.9306 |
| 0.7593 | 0.0108 |
| 0.7593 | 0.9633 |
| 0.2593 | 1 |
| 0.2593 | 0.7419 |
| 0.2593 | 0.1398 |
| 0.2593 | 0.0481 |
| 0.2593 | 1 |
| 0.2593 | 0.8219 |
| 0.2593 | 0.2886 |
| 0.2593 | 1 |
| 0.2593 | 0.8840 |
| 0.0926 | 0.5331 |
| 0.0926 | 0.7088 |
| 0.0926 | 0.9120 |
| 0.0926 | 0.2680 |
| 0.0926 | 0.0536 |
| 0.0926 | 0.1825 |
| 0.0926 | 0.1809 |
| 0.0926 | 0.2428 |
| 0.0926 | 0.9685 |
Assumptions
- Overdispersion — Pearson dispersion 4.26 (1 for Poisson); Cameron–Trivedi z = 5.24, p < .001; standard errors are too small — use a negative binomial model.
- Excess zeros — 0 zeros observed, 0.0 expected by the model.
- Log-linear effects — Numeric predictors act multiplicatively (linearly on the log of the expected count).
- Simulated residuals look uniform — Kolmogorov–Smirnov D = 0.225, p = .007 over 250 simulations; the counts' distribution doesn't match the model (check the residual plots).
- Residual spread matches the model (simulation) — Observed / simulated spread = 4.33, p < .001; overdispersion: standard errors are too small — use a negative binomial model.
- No more outliers than expected (simulation) — 10 of 54 rows sit at the edge of their 250 simulations (within 1/251 of either end; binomial test, p < .001).
Coefficients (log scale) and rate ratios
| Term | B | SE | z | p | Rate ratio | 95% CI low | 95% CI high |
|---|---|---|---|---|---|---|---|
| (Intercept) | 3.692 | 0.0454 | 81.301 | < .001 | 40.124 | 36.707 | 43.858 |
| wool: B | −0.2060 | 0.0516 | −3.994 | < .001 | 0.8138 | 0.7356 | 0.9004 |
| tension: M | −0.3213 | 0.0603 | −5.332 | < .001 | 0.7252 | 0.6444 | 0.8161 |
| tension: H | −0.5185 | 0.0640 | −8.107 | < .001 | 0.5954 | 0.5253 | 0.6749 |
Rate ratio = exp(B): the multiplicative change in the expected count.
Observed and expected count frequencies
| Count | Observed | Expected |
|---|---|---|
| 0 | 0 | 3.323e-8 |
| 1 | 0 | 6.497e-7 |
| 2 | 0 | 6.360e-6 |
| 3 | 0 | 4.157e-5 |
| 4 | 0 | 0.0002 |
| 5 | 0 | 0.0008 |
| 6 | 0 | 0.0026 |
| 7 | 0 | 0.0075 |
| 8 | 0 | 0.0186 |
| 9 | 0 | 0.0412 |
| 10 | 1 | 0.0826 |
| 11 | 0 | 0.1516 |
| 12 | 1 | 0.2568 |
| 13 | 1 | 0.4047 |
| 14 | 1 | 0.5976 |
| 15 | 3 | 0.8322 |
| 16 | 2 | 1.099 |
| 17 | 2 | 1.384 |
| 18 | 3 | 1.668 |
| 19 | 2 | 1.934 |
| 20 | 2 | 2.165 |
Simulated residual checks (DHARMa)
| Check | Statistic | p |
|---|---|---|
| Uniformity (Kolmogorov–Smirnov D) | 0.2252 | .007 |
| Spread (observed / simulated) | 4.334 | < .001 |
| Zeros (observed / simulated) | — | 1.000 |
| Outliers (rows at the edge of their simulations) | 10 | < .001 |
250 simulations from the fitted model, portable seed 1. Each residual is where the observed count falls among its simulations (randomized for whole numbers); uniform residuals mean the model fits. Two-sided simulation p-values.
- Poisson GLM, log link; Wald z tests.
χ²(3, N = 54) = 86.98, p < .001
- LR χ²
- 86.980
- p
- < .001
- Pearson dispersion
- 4.262
- AIC
- 493.06
To keep this page light, the plots are shown once, under the R tab.
Assumptions
- Overdispersion — Pearson dispersion 4.26 (1 for Poisson); Cameron–Trivedi z = 5.24, p < .001; standard errors are too small — use a negative binomial model.
- Excess zeros — 0 zeros observed, 0.0 expected by the model.
- Log-linear effects — Numeric predictors act multiplicatively (linearly on the log of the expected count).
- Simulated residuals look uniform — Kolmogorov–Smirnov D = 0.225, p = .007 over 250 simulations; the counts' distribution doesn't match the model (check the residual plots).
- Residual spread matches the model (simulation) — Observed / simulated spread = 4.33, p < .001; overdispersion: standard errors are too small — use a negative binomial model.
- No more outliers than expected (simulation) — 10 of 54 rows sit at the edge of their 250 simulations (within 1/251 of either end; binomial test, p < .001).
Coefficients (log scale) and rate ratios
| Term | B | SE | z | p | Rate ratio | 95% CI low | 95% CI high |
|---|---|---|---|---|---|---|---|
| (Intercept) | 3.692 | 0.0454 | 81.301 | < .001 | 40.124 | 36.707 | 43.858 |
| wool: B | −0.2060 | 0.0516 | −3.994 | < .001 | 0.8138 | 0.7356 | 0.9004 |
| tension: M | −0.3213 | 0.0603 | −5.332 | < .001 | 0.7252 | 0.6444 | 0.8161 |
| tension: H | −0.5185 | 0.0640 | −8.107 | < .001 | 0.5954 | 0.5253 | 0.6749 |
Rate ratio = exp(B): the multiplicative change in the expected count.
Observed and expected count frequencies
| Count | Observed | Expected |
|---|---|---|
| 0 | 0 | 3.323e-8 |
| 1 | 0 | 6.497e-7 |
| 2 | 0 | 6.360e-6 |
| 3 | 0 | 4.157e-5 |
| 4 | 0 | 0.0002 |
| 5 | 0 | 0.0008 |
| 6 | 0 | 0.0026 |
| 7 | 0 | 0.0075 |
| 8 | 0 | 0.0186 |
| 9 | 0 | 0.0412 |
| 10 | 1 | 0.0826 |
| 11 | 0 | 0.1516 |
| 12 | 1 | 0.2568 |
| 13 | 1 | 0.4047 |
| 14 | 1 | 0.5976 |
| 15 | 3 | 0.8322 |
| 16 | 2 | 1.099 |
| 17 | 2 | 1.384 |
| 18 | 3 | 1.668 |
| 19 | 2 | 1.934 |
| 20 | 2 | 2.165 |
Simulated residual checks (DHARMa)
| Check | Statistic | p |
|---|---|---|
| Uniformity (Kolmogorov–Smirnov D) | 0.2252 | .007 |
| Spread (observed / simulated) | 4.334 | < .001 |
| Zeros (observed / simulated) | — | 1.000 |
| Outliers (rows at the edge of their simulations) | 10 | < .001 |
250 simulations from the fitted model, portable seed 1. Each residual is where the observed count falls among its simulations (randomized for whole numbers); uniform residuals mean the model fits. Two-sided simulation p-values.
- Poisson GLM, log link; Wald z tests.
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
- Poisson warpbreakswarpbreaks · outcome: breaks · predictors: wool, tension
- Negbin quinequine · outcome: Days · predictors: Eth, Sex, Age, Lrn
- Exposure offsetinsurance · exposure: Holders · outcome: Claims · predictors: District, Group, Age
- Quasipoissonquine · outcome: Days · predictors: Eth, Lrn
- Negbin interactionquine · outcome: Days · predictors: Eth, Sex, Lrn
- Degenerate constantwarpbreaks · outcome: breaks · predictors: wool, tension
- Degenerate n1warpbreaks · outcome: breaks · predictors: wool, tension
- Degenerate single levelwarpbreaks · outcome: breaks · predictors: wool, tension
In the guides
Tests from the statistics guide this method runs
Where it sits in the decision guides
- Count outcome: Poisson / negative binomial / zero-inflated · Statistics Guide · D — Predict an outcome
- More than two groups: χ² independence · Statistics Guide · E — Compare proportions / frequencies
- 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
What you need
- Count outcomenumeric · 1 column
- Non-negative whole numbers (events per row).
- Predictorsnumeric / categorical / boolean · 1–20 columns · 2–30 levels
- Columns used to explain or predict the outcome.
- Exposurenumeric · 0–1 column
- Time at risk, population or size per row (> 0). Its log is an offset: effects become rate ratios.
Choices you make
statistics
- Modeldefault poisson
Poisson assumes variance equals the mean; negative binomial and quasi-Poisson allow overdispersed counts.
- Poisson (variance = mean)(default) — Assumes the variance equals the mean; start here and move on if overdispersion shows up.
- Negative binomial (NB2, overdispersed counts) — Adds a dispersion parameter (NB2); pick it when counts vary more than their mean.
- Quasi-Poisson (scaled variance) — Keeps Poisson's estimates and scales the standard errors by the dispersion; a quick fix for overdispersion, with no AIC.
- 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.
hypothesis
- Confidence leveldefault 0.95
How sure the intervals should be: 0.95 gives 95% confidence intervals. Higher confidence means wider intervals.
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 overdispersion (Poisson)
Poisson assumes variance = mean; Cameron–Trivedi's test and the Pearson dispersion ratio check it.
- If violated → Negative binomial regression — Adds a dispersion parameter (variance = μ + μ²/θ) so standard errors are not too small when counts vary more than a Poisson model allows.
- If violated → Quasi-Poisson regression — Keeps the Poisson estimates and scales the standard errors by the estimated dispersion.
No excess zeros
Compares the observed number of zeros with the number the model expects.
- If violated → Zero-inflated negative binomial — Adds a separate process for the excess zeros (with the same predictors) on top of an overdispersed count model. Changes the question: The count coefficients describe the non-structural-zero part; the zero model's coefficients describe the excess zeros. Exposure offsets are not carried over.
Log-linear effects
Simulated residuals look uniform
Poisson and negative binomial (DHARMa): each row's residual is where its count falls among 250 simulations from the fitted model; a Kolmogorov–Smirnov test checks they are uniform.
Residual spread matches the model (simulation)
The spread of observed minus fitted counts against the same spread in each simulation (two-sided simulation test). Above 1 is overdispersion.
No more outliers than expected (simulation)
Rows whose residual is within 1 / (simulations + 1) of 0 or 1, against the expected 2 / (simulations + 1) share (DHARMa's binomial test; approximate for counts, where it can flag too often).
What it reports
- Tests: Model vs intercept only
- n
- 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.
- family
- The exact variant that ran (for example Welch vs classic F), shown so the result can be reported and reproduced.
- deviance
- Twice the gap in log-likelihood between a model and a perfect fit; GLMs' analog of the residual sum of squares.
- log_lik
- The logarithm of the likelihood; higher (less negative) means the model fits the data better.
- aic
- A model score balancing fit against complexity; lower is better, and only differences matter.
- model_stat
- A single number that summarizes how far your data are from what H₀ predicts.
- model_df
- How much independent information is left to estimate variability after fitting the model.
- model_p
- How surprising your data would be if the null hypothesis were true, as a probability.
- dispersion
- Counts that vary more than a Poisson model allows; standard errors come out too small.
- od_z
- An estimate in standard-error units, compared with the standard normal distribution.
- od_p
- How surprising your data would be if the null hypothesis were true, as a probability.
- zeros_observed
- More zeros than a Poisson or negative-binomial count model expects.
- zeros_expected
- More zeros than a Poisson or negative-binomial count model expects.
- has_exposure
- How much opportunity each row had to produce the count (policy-years, hours, area), so the model learns a rate.
- 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[…], irr[…], irr_ci_low[…], irr_ci_high[…], theta, theta_se, model_df2, dharma_n_sim, dharma_ks, dharma_ks_p, dharma_disp_ratio, dharma_disp_p, dharma_zero_ratio, dharma_zero_p, dharma_outliers, dharma_outlier_p
Python and R
Python and R agree to 6 decimals (relative tolerance 1e-6). Python uses pandas, numpy, statsmodels, scipy, codesplash; R uses stats, MASS, nanoparquet, codesplashr.
Default traps between the two languages
- IRLS in both engines with tight deviance tolerances; the negative binomial θ is the ML root found by the same Newton iteration, alternating with IRLS, the same alternation as MASS::glm.nb. Both engines converge further than a default glm.nb, so estimates can differ from one by about 1e-6 relative, and θ's standard error differs from MASS's SE.theta by about 3e-6.
- Overdispersion: Cameron & Trivedi's auxiliary regression (AER::dispersiontest, trafo = 2), z with a normal one-sided p.
- Simulated residuals (DHARMa): both engines simulate from the same portable random stream (codesplash.stats.dharma ↔ codesplashr cs_dharma_*), so the simulations are identical; only a draw that lands within ~1e-6 of a count's cumulative-probability boundary can differ, through the ~1e-6 difference in fitted means.
The exact script CodeSplash ran for example “Poisson warpbreaks” · Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Count regression (Poisson / negative binomial)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method regression.count 1.2.0 · spec 1db6852df6125f74
# Dataset: warpbreaks (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 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
from codesplash.stats import dharma # simulated residuals, twin of codesplashr::cs_dharma_*
# %% Data
df = pd.read_parquet("tests/parity/fixtures/warpbreaks.parquet", columns=["breaks", "wool", "tension"])
n_input = len(df)
df["wool"] = pd.Categorical(df["wool"], categories=["A", "B"]) # stored level order
df["tension"] = pd.Categorical(df["tension"], categories=["L", "M", "H"]) # stored level order
df = df.dropna(subset=["breaks", "wool", "tension"]) # listwise deletion over the analysis columns
df["wool"] = df["wool"].cat.remove_unused_categories()
df["tension"] = df["tension"].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, ["breaks", "wool", "tension"]) # infinite values stop the run (registry/errors.yaml)
# %% Outcome, exposure and design matrix
outcome = "breaks"
predictors = ["wool", "tension"]
family = "poisson" # poisson | negbin | quasipoisson
interactions = "none"
conf = 0.95
y = df[outcome].to_numpy(dtype=float)
if (y < 0).any() or (np.abs(y - np.round(y)) > 1e-9).any():
raise ValueError(f"{outcome} must hold counts: non-negative whole numbers.")
exposure = None
offset = np.zeros(len(df))
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, "Count regression") # more rows than coefficients
for col in [outcome] + predictors:
check_not_constant(df[col], col) # one value (or one level with data) is no variation
if np.linalg.matrix_rank(X.to_numpy()) < X.shape[1]:
cs.cs_error("CS_E_COLLINEAR")
n, k = X.shape
terms = list(X.columns)
# %% Fit
pois = sm.GLM(y, X, family=sm.families.Poisson(), offset=offset).fit(method="IRLS", tol=1e-10, maxiter=200)
# polish: one more IRLS pass from the converged coefficients, so the covariance uses their weights
pois = sm.GLM(y, X, family=sm.families.Poisson(), offset=offset).fit(method="IRLS", tol=1e-10, maxiter=200, start_params=np.asarray(pois.params))
mu_p = np.asarray(pois.mu)
dispersion = float(np.sum((y - mu_p) ** 2 / mu_p) / (n - k)) # Pearson χ² / residual df
# null (intercept-only) Poisson model, closed form with the offset
mu0 = np.exp(offset) * y.sum() / np.exp(offset).sum()
values = {}
if family == "negbin":
fit, theta, theta_se = csglm.nb_fit(y, X, offset) # NB2 as MASS::glm.nb: ML θ alternating with IRLS
mu = np.asarray(fit.mu)
V = np.asarray(fit.cov_params()) # conditional on θ, as glm.nb reports
log_lik = csglm.nb_loglik(y, mu, theta)
null_fit, theta0, _ = csglm.nb_fit(y, np.ones((n, 1)), offset)
log_lik0 = csglm.nb_loglik(y, np.asarray(null_fit.mu), theta0)
model_stat, model_df, model_p = 2 * (log_lik - log_lik0), k - 1, None
model_p = float(stats.chi2.sf(model_stat, model_df))
aic = -2 * log_lik + 2 * (k + 1) # θ counts as a parameter
deviance = float(fit.deviance)
values.update({"theta": float(theta), "theta_se": float(theta_se)})
else:
fit, mu = pois, mu_p
V = np.asarray(pois.cov_params())
deviance = float(pois.deviance)
if family == "quasipoisson":
V = V * dispersion # quasi-likelihood: variance = φ·μ
dev0 = 2 * float(np.sum(np.where(y > 0, y * np.log(np.where(y > 0, y, 1) / mu0), 0.0) - (y - mu0)))
model_df, model_df2 = k - 1, n - k
model_stat = ((dev0 - deviance) / model_df) / dispersion # F test (R: anova(..., test = "F"))
model_p = float(stats.f.sf(model_stat, model_df, model_df2))
log_lik = aic = None
values["model_df2"] = float(model_df2)
else:
log_lik = float(pois.llf)
log_lik0 = float(np.sum(stats.poisson.logpmf(y, mu0)))
model_stat, model_df = 2 * (log_lik - log_lik0), k - 1
model_p = float(stats.chi2.sf(model_stat, model_df))
aic = -2 * log_lik + 2 * k
b = np.asarray(fit.params, dtype=float)
se = np.sqrt(np.diag(V))
zval = b / se
if family == "quasipoisson":
pval = 2 * stats.t.sf(np.abs(zval), n - k)
crit = stats.t.ppf(1 - (1 - conf) / 2, n - k)
else:
pval = 2 * stats.norm.sf(np.abs(zval))
crit = stats.norm.ppf(1 - (1 - conf) / 2)
# %% Assumptions
assumptions = []
aux = ((y - mu_p) ** 2 - y) / mu_p # Cameron & Trivedi (1990): Var = μ + α·μ² against α = 0
od = sm.OLS(aux, mu_p).fit()
od_z = float(od.tvalues[0])
od_p = float(stats.norm.sf(od_z))
if family == "poisson":
status = "warn" if od_p < 0.05 else "pass"
detail = f"Pearson dispersion {dispersion:.2f} (1 for Poisson); Cameron–Trivedi z = {od_z:.2f}, {cs.fmt_p(od_p)}" + ("; standard errors are too small — use a negative binomial model." if od_p < 0.05 else ".")
else:
status = "info"
detail = f"Pearson dispersion of the Poisson fit {dispersion:.2f} (Cameron–Trivedi z = {od_z:.2f}, {cs.fmt_p(od_p)}); the {'negative binomial' if family == 'negbin' else 'quasi-Poisson'} model allows for it."
assumptions.append({"key": "overdispersion", "label": "Overdispersion", "status": status, "statistic": dispersion, "p": od_p, "detail": detail})
counts = np.arange(0, int(min(y.max(), 50)) + 1)
expected = csglm.nb_probs(mu, values["theta"], counts) if family == "negbin" else csglm.poisson_probs(mu, counts)
observed = np.array([int(np.sum(y == c)) for c in counts])
zeros_obs, zeros_exp = int(observed[0]), float(expected[0])
excess = zeros_obs >= 5 and zeros_obs > 1.5 * zeros_exp
assumptions.append({"key": "zero_inflation", "label": "Excess zeros", "status": "warn" if excess else "pass", "statistic": zeros_obs,
"detail": f"{zeros_obs} zeros observed, {zeros_exp:.1f} expected by the model" + ("; consider a zero-inflated or hurdle model." if excess else ".")})
assumptions.append({"key": "linearity", "label": "Log-linear effects", "status": "info",
"detail": "Numeric predictors act multiplicatively (linearly on the log of the expected count)."})
# %% Simulated residuals (DHARMa: 250 simulations from the fitted model, portable seed 1; quasi-Poisson has no model to simulate from)
dh_tables, dh_charts = [], []
if family != "quasipoisson":
rng = dharma.Rng(dharma.SEED)
sims = dharma.simulate(np.log(mu), [], family, None, dharma.N_SIM, rng, theta=values.get("theta"))
dh = dharma.residuals(y, mu, sims, family, rng, zeros=True)
values.update({"dharma_n_sim": dh["n_sim"], "dharma_ks": dh["ks"], "dharma_ks_p": dh["ks_p"], "dharma_disp_ratio": dh["disp_ratio"],
"dharma_disp_p": dh["disp_p"], "dharma_zero_ratio": dh["zero_ratio"], "dharma_zero_p": dh["zero_p"],
"dharma_outliers": dh["outliers"], "dharma_outlier_p": dh["outlier_p"]})
uni_bad, disp_bad, out_bad = dh["ks_p"] < 0.05, dh["disp_p"] < 0.05, dh["outlier_p"] < 0.05
assumptions.append({"key": "uniformity", "label": "Simulated residuals look uniform", "status": "warn" if uni_bad else "pass",
"statistic": dh["ks"], "p": dh["ks_p"],
"detail": f"Kolmogorov–Smirnov D = {dh['ks']:.3f}, {cs.fmt_p(dh['ks_p'])} over {dh['n_sim']} simulations"
+ ("; the counts' distribution doesn't match the model (check the residual plots)." if uni_bad else ".")})
assumptions.append({"key": "dispersion", "label": "Residual spread matches the model (simulation)", "status": "warn" if disp_bad else "pass",
"statistic": dh["disp_ratio"], "p": dh["disp_p"],
"detail": f"Observed / simulated spread = {dh['disp_ratio']:.2f}, {cs.fmt_p(dh['disp_p'])}"
+ (("; overdispersion: standard errors are too small" + (" — use a negative binomial model." if family == "poisson" else ".") if dh["disp_ratio"] > 1 else "; underdispersion: standard errors are conservative.") if disp_bad else ".")})
assumptions.append({"key": "outliers", "label": "No more outliers than expected (simulation)", "status": "warn" if out_bad else "pass",
"statistic": float(dh["outliers"]), "p": dh["outlier_p"],
"detail": f"{dh['outliers']} of {n} rows sit at the edge of their {dh['n_sim']} simulations (within 1/{dh['n_sim'] + 1} of either end; binomial test, {cs.fmt_p(dh['outlier_p'])})."})
dh_tables.append({"key": "dharma", "title": "Simulated residual checks (DHARMa)", "columns": [
{"key": "check", "label": "Check", "type": "string"}, {"key": "statistic", "label": "Statistic", "type": "number"}, {"key": "p", "label": "p", "type": "pvalue"}],
"rows": [{"check": "Uniformity (Kolmogorov–Smirnov D)", "statistic": dh["ks"], "p": dh["ks_p"]},
{"check": "Spread (observed / simulated)", "statistic": dh["disp_ratio"], "p": dh["disp_p"]},
{"check": "Zeros (observed / simulated)", "statistic": dh["zero_ratio"], "p": dh["zero_p"]},
{"check": "Outliers (rows at the edge of their simulations)", "statistic": float(dh["outliers"]), "p": dh["outlier_p"]}],
"note": f"{dh['n_sim']} simulations from the fitted model, portable seed {dharma.SEED}. Each residual is where the observed count falls among "
"its simulations (randomized for whole numbers); uniform residuals mean the model fits. Two-sided simulation p-values."})
m_show = min(n, 5000) # evenly spaced rows for the residual charts
show = [(i * (n - 1)) // (m_show - 1) if m_show > 1 else 0 for i in range(m_show)]
res_show = [float(dh["residuals"][i]) for i in show]
rank_fit = dharma.rank01(mu)
dh_charts += [cs.chart("dharma_qq", "qq", "Simulated residuals against the uniform distribution", {"x": cs.col("Scaled residual", res_show)},
controls={"reference": "uniform"}),
cs.chart("dharma_resid", "scatter", "Simulated residuals against the predicted value (rank)", {
"x": cs.col("Predicted value (rank, 0–1)", [float(rank_fit[i]) for i in show]), "y": cs.col("Scaled residual", res_show)},
controls={"fit": "loess"})]
# %% Result
alpha = 1 - conf
coefs = [{"term": t, "estimate": float(b[j]), "se": float(se[j]), "z": float(zval[j]), "p": float(pval[j]),
"ci_low": float(b[j] - crit * se[j]), "ci_high": float(b[j] + crit * se[j]), "irr": float(np.exp(b[j])),
"irr_ci_low": float(np.exp(b[j] - crit * se[j])), "irr_ci_high": float(np.exp(b[j] + crit * se[j]))} for j, t in enumerate(terms)]
for c in coefs:
values.update({f"{key}[{c['term']}]": c[key] if key != "coef" else c["estimate"]
for key in ("coef", "se", "z", "p", "ci_low", "ci_high", "irr", "irr_ci_low", "irr_ci_high")})
values.update({"n": n, "k": k, "family": family, "deviance": deviance, "log_lik": log_lik, "aic": aic,
"model_stat": float(model_stat), "model_df": float(model_df), "model_p": model_p, "dispersion": dispersion,
"od_z": od_z, "od_p": od_p, "zeros_observed": zeros_obs, "zeros_expected": zeros_exp, "has_exposure": exposure is not None,
"converged": bool(fit.converged), "n_params": k + (1 if family == "negbin" else 0), "max_interaction_order": 2 if interactions != "none" and len(predictors) >= 2 else 1,
"missing_share": n_dropped / n_input if n_input else 0.0})
name = {"poisson": "Poisson", "negbin": "Negative binomial", "quasipoisson": "Quasi-Poisson"}[family]
stat_text = f"F({model_df}, {n - k}) = {model_stat:.2f}" if family == "quasipoisson" else f"χ²({model_df}) = {model_stat:.2f}"
significant = [c["term"] for c in coefs[1:] if c["p"] < alpha]
summary = (f"{name} regression of {outcome}" + (f" per {exposure}" if exposure else "") + f" (n = {n}): {stat_text}, {cs.fmt_p(model_p)}. "
+ (f"Significant terms: {', '.join(significant)}." if significant else "No individual term is significant."))
pct = f"{conf:.0%}"
slopes = coefs[1:]
cs.publish({
"method": "regression.count",
"methodVersion": "1.2.0",
"title": f"{name} regression",
"engine": cs.engine_info("pandas", "numpy", "statsmodels", "scipy"),
"n": n,
"summary": summary,
"apa": stat_text.replace(f"χ²({model_df})", f"χ²({model_df}, N = {n})") + f", {cs.fmt_p(model_p)}",
"statistics": [{"key": "model_stat", "label": "F" if family == "quasipoisson" else "LR χ²", "value": float(model_stat)},
{"key": "model_p", "label": "p", "value": model_p, "format": "p"},
{"key": "dispersion", "label": "Pearson dispersion", "value": dispersion}]
+ ([{"key": "theta", "label": "θ", "value": values["theta"]}] if family == "negbin" else [])
+ ([{"key": "aic", "label": "AIC", "value": aic}] if aic is not None else []),
"tables": [
{"key": "coefficients", "title": "Coefficients (log scale) and rate ratios", "columns": [
{"key": "term", "label": "Term", "type": "string"}, {"key": "estimate", "label": "B", "type": "number"},
{"key": "se", "label": "SE", "type": "number"}, {"key": "z", "label": "t" if family == "quasipoisson" else "z", "type": "number"},
{"key": "p", "label": "p", "type": "pvalue"}, {"key": "irr", "label": "Rate ratio", "type": "number"},
{"key": "irr_ci_low", "label": f"{pct} CI low", "type": "number"}, {"key": "irr_ci_high", "label": f"{pct} CI high", "type": "number"}],
"rows": coefs, "note": "Rate ratio = exp(B): the multiplicative change in the expected count" + (f" per unit of {exposure}" if exposure else "") + "."},
{"key": "frequencies", "title": "Observed and expected count frequencies", "columns": [
{"key": "count", "label": "Count", "type": "integer"}, {"key": "observed", "label": "Observed", "type": "integer"},
{"key": "expected", "label": "Expected", "type": "number"}],
"rows": [{"count": int(c), "observed": int(o), "expected": float(e)} for c, o, e in zip(counts, observed, expected)][:21]},
] + dh_tables,
"effectSizes": [],
"assumptions": assumptions,
"warnings": warnings,
"notes": [f"{name} GLM, log link" + (f", offset log({exposure})" if exposure else "") + "; "
+ {"poisson": "Wald z tests.", "negbin": "θ by maximum likelihood (MASS::glm.nb); Wald z tests conditional on θ.",
"quasipoisson": "standard errors scaled by the Pearson dispersion; t tests."}[family]],
"charts": [
cs.chart("rootogram", "rootogram", "Hanging rootogram", {"count": cs.col("Count", counts.astype(float)),
"observed": cs.col("Observed", observed.astype(float)), "expected": cs.col("Expected", expected)}),
cs.chart("irr", "forest", "Rate ratios", {"label": cs.col("Term", [c["term"] for c in slopes], kind="categorical"),
"estimate": cs.col("Rate ratio", [c["irr"] for c in slopes]), "low": cs.col("low", [c["irr_ci_low"] for c in slopes]),
"high": cs.col("high", [c["irr_ci_high"] for c in slopes])}, controls={"reference": 1, "log": True}),
] + dh_charts,
"values": values,
})
The exact script CodeSplash ran for example “Poisson warpbreaks” · R version 4.5.1 (2025-06-13)
# Count regression (Poisson / negative binomial)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method regression.count 1.2.0 · spec 1db6852df6125f74
# Dataset: warpbreaks (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/warpbreaks.parquet", col_select = c("breaks", "wool", "tension")))
n_input <- nrow(df)
df[["wool"]] <- factor(df[["wool"]], levels = c("A", "B")) # stored level order
df[["tension"]] <- factor(df[["tension"]], levels = c("L", "M", "H")) # stored level order
df <- df[stats::complete.cases(df[c("breaks", "wool", "tension")]), , 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("breaks", "wool", "tension")) # infinite values stop the run (registry/errors.yaml)
# %% Outcome, exposure and model
outcome <- "breaks"
predictors <- c("wool", "tension")
family <- "poisson" # poisson | negbin | quasipoisson
interactions <- "none"
conf <- 0.95
y <- df[[outcome]]
if (any(y < 0) || any(abs(y - round(y)) > 1e-9)) stop(sprintf("%s must hold counts: non-negative whole numbers.", outcome))
exposure <- NULL
offset <- rep(0, nrow(df))
# 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, "Count regression") # more rows than coefficients
for (col in c(outcome, predictors)) cs_check_not_constant(df[[col]], col) # one value (or one level with data) is no variation
data <- df
data$.cs_offset <- offset
fml <- cs_model_formula(outcome, predictors, interactions)
ctrl <- glm.control(epsilon = 1e-12, maxit = 200)
# %% Fit
pois <- glm(fml, family = poisson(), data = data, offset = .cs_offset, control = ctrl)
if (anyNA(coef(pois))) cs_error("CS_E_COLLINEAR")
# polish: one more IRLS pass from the converged coefficients, so vcov uses their working weights
pois <- glm(fml, family = poisson(), data = data, offset = .cs_offset, control = ctrl, start = coef(pois))
if (anyNA(coef(pois))) cs_error("CS_E_COLLINEAR")
X <- model.matrix(pois)
terms <- cs_design_labels(df, predictors, interactions)
stopifnot(length(terms) == ncol(X))
n <- nrow(X)
k <- ncol(X)
mu_p <- unname(fitted(pois))
dispersion <- sum((y - mu_p)^2 / mu_p) / (n - k) # Pearson chi^2 / residual df
mu0 <- exp(offset) * sum(y) / sum(exp(offset)) # null (intercept-only) Poisson model, closed form
values <- list()
model_df <- k - 1
if (family == "negbin") {
nb <- cs_glm_nb(fml, data, offset) # NB2 as MASS::glm.nb: ML theta alternating with IRLS
fit <- nb$fit
theta <- nb$theta
mu <- unname(fitted(fit))
V <- summary(fit, dispersion = 1)$cov.scaled # conditional on theta with dispersion 1, as glm.nb reports
log_lik <- cs_nb_loglik(y, mu, theta)
data0 <- data.frame(.y = y)
nb0 <- cs_glm_nb(.y ~ 1, data0, offset)
log_lik0 <- cs_nb_loglik(y, unname(fitted(nb0$fit)), nb0$theta)
model_stat <- 2 * (log_lik - log_lik0)
model_p <- pchisq(model_stat, model_df, lower.tail = FALSE)
aic <- -2 * log_lik + 2 * (k + 1) # theta counts as a parameter
dev <- deviance(fit)
values$theta <- theta
values$theta_se <- nb$theta_se
} else {
fit <- pois
mu <- mu_p
V <- vcov(pois)
dev <- deviance(pois)
if (family == "quasipoisson") {
V <- V * dispersion # quasi-likelihood: variance = phi * mu (as summary(glm(family = quasipoisson)))
dev0 <- 2 * sum(ifelse(y > 0, y * log(ifelse(y > 0, y, 1) / mu0), 0) - (y - mu0))
model_df2 <- n - k
model_stat <- ((dev0 - dev) / model_df) / dispersion # F test (anova(..., test = "F"))
model_p <- pf(model_stat, model_df, model_df2, lower.tail = FALSE)
log_lik <- NULL
aic <- NULL
values$model_df2 <- model_df2
} else {
log_lik <- as.numeric(logLik(pois))
log_lik0 <- sum(dpois(y, mu0, log = TRUE))
model_stat <- 2 * (log_lik - log_lik0)
model_p <- pchisq(model_stat, model_df, lower.tail = FALSE)
aic <- -2 * log_lik + 2 * k
}
}
b <- unname(coef(fit))
se <- sqrt(diag(V))
zval <- b / se
if (family == "quasipoisson") {
pval <- 2 * pt(abs(zval), n - k, lower.tail = FALSE)
crit <- qt(1 - (1 - conf) / 2, n - k)
} else {
pval <- 2 * pnorm(abs(zval), lower.tail = FALSE)
crit <- qnorm(1 - (1 - conf) / 2)
}
# %% Assumptions
assumptions <- list()
aux <- ((y - mu_p)^2 - y) / mu_p # Cameron & Trivedi (1990), AER::dispersiontest(trafo = 2)
od <- summary(lm(aux ~ 0 + mu_p))
od_z <- od$coefficients[1, 3]
od_p <- pnorm(od_z, lower.tail = FALSE)
if (family == "poisson") {
status <- if (od_p < 0.05) "warn" else "pass"
detail <- paste0(sprintf("Pearson dispersion %.2f (1 for Poisson); Cameron–Trivedi z = %.2f, %s", dispersion, od_z, cs_fmt_p(od_p)),
if (od_p < 0.05) "; standard errors are too small — use a negative binomial model." else ".")
} else {
status <- "info"
detail <- sprintf("Pearson dispersion of the Poisson fit %.2f (Cameron–Trivedi z = %.2f, %s); the %s model allows for it.",
dispersion, od_z, cs_fmt_p(od_p), if (family == "negbin") "negative binomial" else "quasi-Poisson")
}
assumptions[[1]] <- list(key = "overdispersion", label = "Overdispersion", status = status, statistic = dispersion, p = od_p, detail = detail)
counts <- 0:as.integer(min(max(y), 50))
expected <- if (family == "negbin") cs_nb_probs(mu, values$theta, counts) else cs_poisson_probs(mu, counts)
observed <- vapply(counts, function(cc) sum(y == cc), 0)
zeros_obs <- observed[1]
zeros_exp <- expected[1]
excess <- zeros_obs >= 5 && zeros_obs > 1.5 * zeros_exp
assumptions[[2]] <- list(key = "zero_inflation", label = "Excess zeros", status = if (excess) "warn" else "pass", statistic = zeros_obs,
detail = paste0(sprintf("%d zeros observed, %.1f expected by the model", zeros_obs, zeros_exp),
if (excess) "; consider a zero-inflated or hurdle model." else "."))
assumptions[[3]] <- list(key = "linearity", label = "Log-linear effects", status = "info",
detail = "Numeric predictors act multiplicatively (linearly on the log of the expected count).")
# %% Simulated residuals (DHARMa: 250 simulations from the fitted model, portable seed 1; quasi-Poisson has no model to simulate from)
dh_tables <- list()
dh_charts <- list()
if (family != "quasipoisson") {
rng <- cs_rng(1)
sims <- cs_dharma_simulate(log(mu), list(), family, NULL, 250, rng, theta = values$theta)
dh <- cs_dharma_residuals(y, mu, sims, family, rng, zeros = TRUE)
values$dharma_n_sim <- dh$n_sim; values$dharma_ks <- dh$ks; values$dharma_ks_p <- dh$ks_p
values$dharma_disp_ratio <- dh$disp_ratio; values$dharma_disp_p <- dh$disp_p
values$dharma_zero_ratio <- dh$zero_ratio; values$dharma_zero_p <- dh$zero_p
values$dharma_outliers <- dh$outliers; values$dharma_outlier_p <- dh$outlier_p
uni_bad <- dh$ks_p < 0.05; disp_bad <- dh$disp_p < 0.05; out_bad <- dh$outlier_p < 0.05
assumptions[[length(assumptions) + 1]] <- list(key = "uniformity", label = "Simulated residuals look uniform", status = if (uni_bad) "warn" else "pass",
statistic = dh$ks, p = dh$ks_p,
detail = paste0(sprintf("Kolmogorov–Smirnov D = %.3f, %s over %d simulations", dh$ks, cs_fmt_p(dh$ks_p), as.integer(dh$n_sim)),
if (uni_bad) "; the counts' distribution doesn't match the model (check the residual plots)." else "."))
assumptions[[length(assumptions) + 1]] <- list(key = "dispersion", label = "Residual spread matches the model (simulation)", status = if (disp_bad) "warn" else "pass",
statistic = dh$disp_ratio, p = dh$disp_p,
detail = paste0(sprintf("Observed / simulated spread = %.2f, %s", dh$disp_ratio, cs_fmt_p(dh$disp_p)),
if (!disp_bad) "." else if (dh$disp_ratio > 1) paste0("; overdispersion: standard errors are too small", if (family == "poisson") " — use a negative binomial model." else ".")
else "; underdispersion: standard errors are conservative."))
assumptions[[length(assumptions) + 1]] <- list(key = "outliers", label = "No more outliers than expected (simulation)", status = if (out_bad) "warn" else "pass",
statistic = as.numeric(dh$outliers), p = dh$outlier_p,
detail = sprintf("%d of %d rows sit at the edge of their %d simulations (within 1/%d of either end; binomial test, %s).", as.integer(dh$outliers), as.integer(n),
as.integer(dh$n_sim), as.integer(dh$n_sim) + 1L, cs_fmt_p(dh$outlier_p)))
dh_tables <- list(list(key = "dharma", title = "Simulated residual checks (DHARMa)", columns = list(
list(key = "check", label = "Check", type = "string"), list(key = "statistic", label = "Statistic", type = "number"), list(key = "p", label = "p", type = "pvalue")),
rows = list(list(check = "Uniformity (Kolmogorov–Smirnov D)", statistic = dh$ks, p = dh$ks_p),
list(check = "Spread (observed / simulated)", statistic = dh$disp_ratio, p = dh$disp_p),
list(check = "Zeros (observed / simulated)", statistic = dh$zero_ratio, p = dh$zero_p),
list(check = "Outliers (rows at the edge of their simulations)", statistic = as.numeric(dh$outliers), p = dh$outlier_p)),
note = paste0(sprintf("%d simulations from the fitted model, portable seed 1. ", as.integer(dh$n_sim)),
"Each residual is where the observed count falls among its simulations (randomized for whole numbers); uniform residuals mean the model fits. Two-sided simulation p-values.")))
m_show <- min(n, 5000) # evenly spaced rows for the residual charts
show <- if (m_show > 1) ((seq_len(m_show) - 1) * (n - 1)) %/% (m_show - 1) + 1 else 1
res_show <- dh$residuals[show]
rank_fit <- cs_dharma_rank01(mu)
dh_charts <- list(cs_chart("dharma_qq", "qq", "Simulated residuals against the uniform distribution", list(x = cs_col("Scaled residual", res_show)),
controls = list(reference = "uniform")),
cs_chart("dharma_resid", "scatter", "Simulated residuals against the predicted value (rank)", list(
x = cs_col("Predicted value (rank, 0–1)", rank_fit[show]), y = cs_col("Scaled residual", res_show)), controls = list(fit = "loess")))
}
# %% Result
alpha <- 1 - conf
coefs <- lapply(seq_along(terms), function(j) list(term = terms[j], estimate = b[j], se = se[j], z = zval[j], p = pval[j],
ci_low = b[j] - crit * se[j], ci_high = b[j] + crit * se[j], irr = exp(b[j]),
irr_ci_low = exp(b[j] - crit * se[j]), irr_ci_high = exp(b[j] + crit * se[j])))
for (cf in coefs) {
for (key in c("coef", "se", "z", "p", "ci_low", "ci_high", "irr", "irr_ci_low", "irr_ci_high")) {
values[[sprintf("%s[%s]", key, cf$term)]] <- if (key == "coef") cf$estimate else cf[[key]]
}
}
values <- c(values, list(n = n, k = k, family = family, deviance = dev, log_lik = log_lik, aic = aic, model_stat = model_stat,
model_df = model_df, model_p = model_p, dispersion = dispersion, od_z = od_z, od_p = od_p,
zeros_observed = zeros_obs, zeros_expected = zeros_exp, has_exposure = !is.null(exposure),
converged = isTRUE(fit$converged), n_params = k + if (family == "negbin") 1 else 0, max_interaction_order = if (interactions != "none" && length(predictors) >= 2) 2 else 1,
missing_share = if (n_input > 0) n_dropped / n_input else 0))
name <- c(poisson = "Poisson", negbin = "Negative binomial", quasipoisson = "Quasi-Poisson")[[family]]
stat_text <- if (family == "quasipoisson") sprintf("F(%d, %d) = %.2f", model_df, n - k, model_stat) else sprintf("χ²(%d) = %.2f", model_df, model_stat)
significant <- vapply(Filter(function(cf) cf$p < alpha, coefs[-1]), `[[`, "", "term")
summary <- paste0(sprintf("%s regression of %s%s (n = %d): %s, %s. ", name, outcome, if (!is.null(exposure)) paste0(" per ", exposure) else "", n, stat_text, cs_fmt_p(model_p)),
if (length(significant)) sprintf("Significant terms: %s.", paste(significant, collapse = ", ")) else "No individual term is significant.")
pct <- sprintf("%.0f%%", conf * 100)
slopes <- coefs[-1]
stats_list <- list(list(key = "model_stat", label = if (family == "quasipoisson") "F" else "LR χ²", value = model_stat),
list(key = "model_p", label = "p", value = model_p, format = "p"), list(key = "dispersion", label = "Pearson dispersion", value = dispersion))
if (family == "negbin") stats_list[[length(stats_list) + 1]] <- list(key = "theta", label = "θ", value = values$theta)
if (!is.null(aic)) stats_list[[length(stats_list) + 1]] <- list(key = "aic", label = "AIC", value = aic)
freq_rows <- lapply(seq_along(counts), function(i) list(count = counts[i], observed = observed[i], expected = expected[i]))
cs_publish(list(
method = "regression.count",
methodVersion = "1.2.0",
title = paste(name, "regression"),
engine = cs_engine_info("stats", "MASS", "nanoparquet"),
n = n,
summary = summary,
apa = paste0(if (family == "quasipoisson") stat_text else sprintf("χ²(%d, N = %d) = %.2f", model_df, n, model_stat), ", ", cs_fmt_p(model_p)),
statistics = stats_list,
tables = c(list(
list(key = "coefficients", title = "Coefficients (log scale) and rate 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 = if (family == "quasipoisson") "t" else "z", type = "number"),
list(key = "p", label = "p", type = "pvalue"), list(key = "irr", label = "Rate ratio", type = "number"),
list(key = "irr_ci_low", label = paste(pct, "CI low"), type = "number"), list(key = "irr_ci_high", label = paste(pct, "CI high"), type = "number")),
rows = coefs, note = paste0("Rate ratio = exp(B): the multiplicative change in the expected count", if (!is.null(exposure)) paste0(" per unit of ", exposure) else "", ".")),
list(key = "frequencies", title = "Observed and expected count frequencies", columns = list(
list(key = "count", label = "Count", type = "integer"), list(key = "observed", label = "Observed", type = "integer"),
list(key = "expected", label = "Expected", type = "number")), rows = head(freq_rows, 21))
), dh_tables),
effectSizes = list(),
assumptions = assumptions,
warnings = warnings,
notes = list(paste0(name, " GLM, log link", if (!is.null(exposure)) sprintf(", offset log(%s)", exposure) else "", "; ",
c(poisson = "Wald z tests.", negbin = "θ by maximum likelihood (MASS::glm.nb); Wald z tests conditional on θ.",
quasipoisson = "standard errors scaled by the Pearson dispersion; t tests.")[[family]])),
charts = c(list(
cs_chart("rootogram", "rootogram", "Hanging rootogram", list(count = cs_col("Count", as.numeric(counts)), observed = cs_col("Observed", observed),
expected = cs_col("Expected", expected))),
cs_chart("irr", "forest", "Rate ratios", list(label = cs_col("Term", vapply(slopes, `[[`, "", "term"), kind = "categorical"),
estimate = cs_col("Rate ratio", vapply(slopes, `[[`, 0, "irr")),
low = cs_col("low", vapply(slopes, `[[`, 0, "irr_ci_low")), high = cs_col("high", vapply(slopes, `[[`, 0, "irr_ci_high"))),
controls = list(reference = 1, log = TRUE))
), dh_charts),
values = values
))
Sources
- Cameron, A. C., & Trivedi, P. K. (1990). Regression-based tests for overdispersion in the Poisson model. Journal of Econometrics, 46, 347–364.
- Venables, W. N., & Ripley, B. D. (2002). Modern Applied Statistics with S (4th ed.), §7.4. Springer.
- Kleiber, C., & Zeileis, A. (2016). Visualizing count data regressions using rootograms. The American Statistician, 70, 296–303.
- Hartig, F. (2022). DHARMa: Residual diagnostics for hierarchical (multi-level/mixed) regression models. R package version 0.4.6.
- Dunn, P. K., & Smyth, G. K. (1996). Randomized quantile residuals. Journal of Computational and Graphical Statistics, 5(3), 236–244.
From the CodeSplash method registry · regression.count v1.2.0.