Count outcomes: Poisson, overdispersion and negative binomial
Counts are whole numbers with a floor at zero. Model them on the log scale, read rate ratios, add exposure when units differ, and check whether the variance has outrun the mean.
What runs in CodeSplash
- Count regression (Poisson / negative binomial) Verified in Python and R
You will be able to
- Explain why counts use a log link and read a coefficient as a rate ratio
- Use an exposure offset to model a rate rather than a raw count
- Spot overdispersion from the dispersion ratio and its test
- Choose between Poisson, quasi-Poisson and negative binomial
Read first
A model for counts
ReadYarn breaks per loom, days absent from school, claims per policy: counts are whole numbers, they can't go below zero, and they spread out as they grow. A straight line handles none of that.
A Poisson regressionPoisson regressionModels the log of an expected count as a linear function of the predictors, with variance equal to the mean. models the log of the expected count:
The log keeps every prediction positive, and it makes effects multiply rather than add.
Make a prediction
PredictPredict first
A predictor has a coefficient of . One more unit of it multiplies the expected count by how much?
Make your guess between 0 and 6 times the count, then reveal.
Reveal
By , at any starting count: from 3 to 6, or from 30 to 60. That exponentiated coefficient is the rate ratioRate ratioThe factor that multiplies an expected count or rate per unit of a predictor. It's an exponentiated count coefficient., shown as IRR on the card. An IRR below 1 means fewer events.
Read the card
In the appχ²(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.
The exact R script · R 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
))
χ²(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.
The exact Python script · Python 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,
})
These are warp breaks on a loom, by wool type and tension, in 54 rows. The test against an intercept-only model gives (3) = 87.0, p < .001.
Now find the IRR column. High tension has an IRR of 0.60 (95% CI 0.53 to 0.67): fewer breaks than at low tension, the reference level. Report each IRR with its interval.
Is the variance too big?
PredictA Poisson model has one parameter, so it forces the variance to equal the mean. The dispersion ratio is Pearson divided by its degrees of freedom, and it sits near 1 when that holds.
Predict first
These are breaks on real looms, with only wool and tension in the model. Where do you expect the ratio to land?
Reveal
It's 4.26, and the Cameron–Trivedi test gives p < .001. That's overdispersionOverdispersionCounts that vary more than a Poisson model allows; standard errors come out too small.: the counts vary more than the model allows.
See what it does to a test
ExploreDExplorable · Overdispersed counts
What happens to a Poisson test when counts vary more than the Poisson allows?
With no real difference, how often does the plain Poisson comparison reject?
Commit your prediction above to see the result
Make your prediction to see the result.
There's no true difference between the groups here. Lower the negative binomial size and watch the Poisson comparison reject far more than 5% of the time, while the quasi-Poisson comparison stays close to it.
Two remedies
ReadQuasi-Poisson keeps the Poisson coefficients and multiplies each standard error by the square root of the dispersion. No likelihood sits behind it, so there's no AIC.
The negative binomialNegative binomial regressionA count model with an extra parameter θ, so the variance is μ + μ²/θ. A smaller θ means more extra spread. adds a parameter , so the variance becomes . It has a likelihood, so AIC works, and a smaller means more extra spread.
On days absent from school, quasi-Poisson estimates a dispersion of 14.9. A negative binomial on the same 146 pupils, with more predictors, gives = 1.27.
χ²(6, N = 146) = 25.12, p < .001
- LR χ²
- 25.116
- p
- < .001
- Pearson dispersion
- 13.167
- θ
- 1.275
- AIC
- 1109.15
Plots
View data
| Count | Expected | Observed |
|---|---|---|
| 0 | 6.214 | 9 |
| 1 | 7.148 | 4 |
| 2 | 7.346 | 6 |
| 3 | 7.256 | 6 |
| 4 | 7.026 | 1 |
| 5 | 6.724 | 19 |
| 6 | 6.389 | 8 |
| 7 | 6.039 | 6 |
| 8 | 5.689 | 4 |
| 9 | 5.346 | 2 |
| 10 | 5.015 | 4 |
| 11 | 4.698 | 7 |
| 12 | 4.397 | 2 |
| 13 | 4.113 | 3 |
| 14 | 3.846 | 8 |
| 15 | 3.595 | 3 |
| 16 | 3.360 | 3 |
| 17 | 3.141 | 4 |
| 18 | 2.936 | 1 |
| 19 | 2.744 | 1 |
| 20 | 2.566 | 3 |
| 21 | 2.400 | 1 |
| 22 | 2.245 | 4 |
| 23 | 2.101 | 3 |
| 24 | 1.967 | 1 |
| 25 | 1.842 | 2 |
| 26 | 1.726 | 0 |
| 27 | 1.617 | 2 |
| 28 | 1.516 | 2 |
| 29 | 1.422 | 0 |
| 30 | 1.334 | 2 |
| 31 | 1.252 | 0 |
| 32 | 1.175 | 2 |
| 33 | 1.104 | 1 |
| 34 | 1.037 | 1 |
| 35 | 0.9745 | 0 |
| 36 | 0.9162 | 3 |
| 37 | 0.8618 | 1 |
| 38 | 0.8109 | 1 |
| 39 | 0.7632 | 0 |
| 40 | 0.7186 | 2 |
| 41 | 0.6769 | 1 |
| 42 | 0.6377 | 0 |
| 43 | 0.6011 | 1 |
| 44 | 0.5667 | 0 |
| 45 | 0.5345 | 1 |
| 46 | 0.5042 | 1 |
| 47 | 0.4759 | 1 |
| 48 | 0.4492 | 1 |
| 49 | 0.4242 | 0 |
| 50 | 0.4007 | 0 |
View data
| Rate ratio | high | Term | low |
|---|---|---|---|
| 0.5659 | 0.7643 | Eth: N | 0.4190 |
| 1.086 | 1.485 | Sex: M | 0.7937 |
| 0.6386 | 1.022 | Age: F1 | 0.3992 |
| 1.092 | 1.735 | Age: F2 | 0.6874 |
| 1.429 | 2.325 | Age: F3 | 0.8783 |
| 1.339 | 1.930 | Lrn: SL | 0.9293 |
View data
| Scaled residual |
|---|
| 0.0609 |
| 0.2907 |
| 0.4415 |
| 0.1907 |
| 0.2127 |
| 0.4610 |
| 0.6178 |
| 0.6278 |
| 0.2796 |
| 0.2480 |
| 0.5600 |
| 0.4097 |
| 0.6320 |
| 0.1326 |
| 0.6420 |
| 0.8685 |
| 0.8779 |
| 0.4340 |
| 0.5303 |
| 0.5130 |
| 0.5206 |
| 0.8440 |
| 0.8640 |
| 0.8840 |
| 0.1660 |
| 0.5197 |
| 0.5222 |
| 0.6047 |
| 0.6804 |
| 0.6965 |
| 0.7234 |
| 0.1195 |
| 0.2056 |
| 0.4104 |
| 0.7773 |
| 0.9600 |
| 0.2312 |
| 0.2942 |
| 0.3338 |
| 0.4085 |
| 0.5494 |
| 0.7145 |
| 0.8067 |
| 0.8779 |
| 0.9720 |
| 0.9760 |
| 0.3544 |
| 0.3013 |
| 0.6171 |
| 0.7698 |
| 0.8040 |
| 0.2321 |
| 0.2936 |
| 0.4266 |
| 0.5016 |
| 0.8060 |
| 0.8614 |
| 0.9080 |
| 0.9343 |
| 0.1071 |
First 60 of 146 rows.
View data
| Predicted value (rank, 0–1) | Scaled residual |
|---|---|
| 0.8630 | 0.0609 |
| 0.8630 | 0.2907 |
| 0.8630 | 0.4415 |
| 0.7123 | 0.1907 |
| 0.7123 | 0.2127 |
| 0.7123 | 0.4610 |
| 0.7123 | 0.6178 |
| 0.7123 | 0.6278 |
| 0.6575 | 0.2796 |
| 0.6575 | 0.2480 |
| 0.6575 | 0.5600 |
| 0.3459 | 0.4097 |
| 0.3459 | 0.6320 |
| 0.9897 | 0.1326 |
| 0.9897 | 0.6420 |
| 0.9897 | 0.8685 |
| 0.9897 | 0.8779 |
| 0.7603 | 0.4340 |
| 0.7603 | 0.5303 |
| 0.7603 | 0.5130 |
| 0.7603 | 0.5206 |
| 0.7603 | 0.8440 |
| 0.7603 | 0.8640 |
| 0.7603 | 0.8840 |
| 0.9521 | 0.1660 |
| 0.9521 | 0.5197 |
| 0.9521 | 0.5222 |
| 0.9521 | 0.6047 |
| 0.9521 | 0.6804 |
| 0.9521 | 0.6965 |
| 0.9521 | 0.7234 |
| 0.7877 | 0.1195 |
| 0.6815 | 0.2056 |
| 0.6815 | 0.4104 |
| 0.6815 | 0.7773 |
| 0.6815 | 0.9600 |
| 0.5445 | 0.2312 |
| 0.5445 | 0.2942 |
| 0.5445 | 0.3338 |
| 0.5445 | 0.4085 |
| 0.5445 | 0.5494 |
| 0.5445 | 0.7145 |
| 0.5445 | 0.8067 |
| 0.5445 | 0.8779 |
| 0.5445 | 0.9720 |
| 0.5445 | 0.9760 |
| 0.2740 | 0.3544 |
| 0.2740 | 0.3013 |
| 0.2740 | 0.6171 |
| 0.2740 | 0.7698 |
| 0.2740 | 0.8040 |
| 0.9007 | 0.2321 |
| 0.9007 | 0.2936 |
| 0.9007 | 0.4266 |
| 0.9007 | 0.5016 |
| 0.9007 | 0.8060 |
| 0.9007 | 0.8614 |
| 0.9007 | 0.9080 |
| 0.9007 | 0.9343 |
| 0.7329 | 0.1071 |
First 60 of 146 rows.
Assumptions
- Overdispersion — Pearson dispersion of the Poisson fit 13.17 (Cameron–Trivedi z = 5.33, p < .001); the negative binomial model allows for it.
- Excess zeros — 9 zeros observed, 6.2 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.059, p = .686 over 250 simulations.
- Residual spread matches the model (simulation) — Observed / simulated spread = 0.85, p = .472.
- No more outliers than expected (simulation) — 3 of 146 rows sit at the edge of their 250 simulations (within 1/251 of either end; binomial test, p = .112).
Coefficients (log scale) and rate ratios
| Term | B | SE | z | p | Rate ratio | 95% CI low | 95% CI high |
|---|---|---|---|---|---|---|---|
| (Intercept) | 2.895 | 0.2284 | 12.672 | < .001 | 18.076 | 11.552 | 28.284 |
| Eth: N | −0.5694 | 0.1533 | −3.713 | < .001 | 0.5659 | 0.4190 | 0.7643 |
| Sex: M | 0.0823 | 0.1599 | 0.5148 | .607 | 1.086 | 0.7937 | 1.485 |
| Age: F1 | −0.4484 | 0.2397 | −1.870 | .061 | 0.6386 | 0.3992 | 1.022 |
| Age: F2 | 0.0881 | 0.2362 | 0.3729 | .709 | 1.092 | 0.6874 | 1.735 |
| Age: F3 | 0.3569 | 0.2483 | 1.437 | .151 | 1.429 | 0.8783 | 2.325 |
| Lrn: SL | 0.2921 | 0.1865 | 1.566 | .117 | 1.339 | 0.9293 | 1.930 |
Rate ratio = exp(B): the multiplicative change in the expected count.
Observed and expected count frequencies
| Count | Observed | Expected |
|---|---|---|
| 0 | 9 | 6.214 |
| 1 | 4 | 7.148 |
| 2 | 6 | 7.346 |
| 3 | 6 | 7.256 |
| 4 | 1 | 7.026 |
| 5 | 19 | 6.724 |
| 6 | 8 | 6.389 |
| 7 | 6 | 6.039 |
| 8 | 4 | 5.689 |
| 9 | 2 | 5.346 |
| 10 | 4 | 5.015 |
| 11 | 7 | 4.698 |
| 12 | 2 | 4.397 |
| 13 | 3 | 4.113 |
| 14 | 8 | 3.846 |
| 15 | 3 | 3.595 |
| 16 | 3 | 3.360 |
| 17 | 4 | 3.141 |
| 18 | 1 | 2.936 |
| 19 | 1 | 2.744 |
| 20 | 3 | 2.566 |
Simulated residual checks (DHARMa)
| Check | Statistic | p |
|---|---|---|
| Uniformity (Kolmogorov–Smirnov D) | 0.0592 | .686 |
| Spread (observed / simulated) | 0.8460 | .472 |
| Zeros (observed / simulated) | 1.460 | .272 |
| Outliers (rows at the edge of their simulations) | 3 | .112 |
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.
- Negative binomial GLM, log link; θ by maximum likelihood (MASS::glm.nb); Wald z tests conditional on θ.
The exact R script · R 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 ad9763a5a66f1991
# Dataset: quine (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/quine.parquet", col_select = c("Days", "Eth", "Sex", "Age", "Lrn")))
n_input <- nrow(df)
df[["Eth"]] <- factor(df[["Eth"]], levels = c("A", "N")) # stored level order
df[["Sex"]] <- factor(df[["Sex"]], levels = c("F", "M")) # stored level order
df[["Age"]] <- factor(df[["Age"]], levels = c("F0", "F1", "F2", "F3")) # stored level order
df[["Lrn"]] <- factor(df[["Lrn"]], levels = c("AL", "SL")) # stored level order
df <- df[stats::complete.cases(df[c("Days", "Eth", "Sex", "Age", "Lrn")]), , 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("Days", "Eth", "Sex", "Age", "Lrn")) # infinite values stop the run (registry/errors.yaml)
# %% Outcome, exposure and model
outcome <- "Days"
predictors <- c("Eth", "Sex", "Age", "Lrn")
family <- "negbin" # 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
))
χ²(6, N = 146) = 25.12, p < .001
- LR χ²
- 25.116
- p
- < .001
- Pearson dispersion
- 13.167
- θ
- 1.275
- AIC
- 1109.15
To keep this page light, the plots are shown once, under the R tab.
Assumptions
- Overdispersion — Pearson dispersion of the Poisson fit 13.17 (Cameron–Trivedi z = 5.33, p < .001); the negative binomial model allows for it.
- Excess zeros — 9 zeros observed, 6.2 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.059, p = .686 over 250 simulations.
- Residual spread matches the model (simulation) — Observed / simulated spread = 0.85, p = .472.
- No more outliers than expected (simulation) — 3 of 146 rows sit at the edge of their 250 simulations (within 1/251 of either end; binomial test, p = .112).
Coefficients (log scale) and rate ratios
| Term | B | SE | z | p | Rate ratio | 95% CI low | 95% CI high |
|---|---|---|---|---|---|---|---|
| (Intercept) | 2.895 | 0.2284 | 12.672 | < .001 | 18.076 | 11.552 | 28.284 |
| Eth: N | −0.5694 | 0.1533 | −3.713 | < .001 | 0.5659 | 0.4190 | 0.7643 |
| Sex: M | 0.0823 | 0.1599 | 0.5148 | .607 | 1.086 | 0.7937 | 1.485 |
| Age: F1 | −0.4484 | 0.2397 | −1.870 | .061 | 0.6386 | 0.3992 | 1.022 |
| Age: F2 | 0.0881 | 0.2362 | 0.3729 | .709 | 1.092 | 0.6874 | 1.735 |
| Age: F3 | 0.3569 | 0.2483 | 1.437 | .151 | 1.429 | 0.8783 | 2.325 |
| Lrn: SL | 0.2921 | 0.1865 | 1.566 | .117 | 1.339 | 0.9293 | 1.930 |
Rate ratio = exp(B): the multiplicative change in the expected count.
Observed and expected count frequencies
| Count | Observed | Expected |
|---|---|---|
| 0 | 9 | 6.214 |
| 1 | 4 | 7.148 |
| 2 | 6 | 7.346 |
| 3 | 6 | 7.256 |
| 4 | 1 | 7.026 |
| 5 | 19 | 6.724 |
| 6 | 8 | 6.389 |
| 7 | 6 | 6.039 |
| 8 | 4 | 5.689 |
| 9 | 2 | 5.346 |
| 10 | 4 | 5.015 |
| 11 | 7 | 4.698 |
| 12 | 2 | 4.397 |
| 13 | 3 | 4.113 |
| 14 | 8 | 3.846 |
| 15 | 3 | 3.595 |
| 16 | 3 | 3.360 |
| 17 | 4 | 3.141 |
| 18 | 1 | 2.936 |
| 19 | 1 | 2.744 |
| 20 | 3 | 2.566 |
Simulated residual checks (DHARMa)
| Check | Statistic | p |
|---|---|---|
| Uniformity (Kolmogorov–Smirnov D) | 0.0592 | .686 |
| Spread (observed / simulated) | 0.8460 | .472 |
| Zeros (observed / simulated) | 1.460 | .272 |
| Outliers (rows at the edge of their simulations) | 3 | .112 |
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.
- Negative binomial GLM, log link; θ by maximum likelihood (MASS::glm.nb); Wald z tests conditional on θ.
The exact Python script · Python 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 ad9763a5a66f1991
# Dataset: quine (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/quine.parquet", columns=["Days", "Eth", "Sex", "Age", "Lrn"])
n_input = len(df)
df["Eth"] = pd.Categorical(df["Eth"], categories=["A", "N"]) # stored level order
df["Sex"] = pd.Categorical(df["Sex"], categories=["F", "M"]) # stored level order
df["Age"] = pd.Categorical(df["Age"], categories=["F0", "F1", "F2", "F3"]) # stored level order
df["Lrn"] = pd.Categorical(df["Lrn"], categories=["AL", "SL"]) # stored level order
df = df.dropna(subset=["Days", "Eth", "Sex", "Age", "Lrn"]) # listwise deletion over the analysis columns
df["Eth"] = df["Eth"].cat.remove_unused_categories()
df["Sex"] = df["Sex"].cat.remove_unused_categories()
df["Age"] = df["Age"].cat.remove_unused_categories()
df["Lrn"] = df["Lrn"].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, ["Days", "Eth", "Sex", "Age", "Lrn"]) # infinite values stop the run (registry/errors.yaml)
# %% Outcome, exposure and design matrix
outcome = "Days"
predictors = ["Eth", "Sex", "Age", "Lrn"]
family = "negbin" # 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,
})
Count the zeros
ReflectThe rootogram on the card compares how often each count occurred with how often the model expects it. Zeros are a quick check.
9 pupils had no absences. The Poisson mean structure expects 0.000468 of them. The negative binomial expects 6.2.
Before you reach for a special model for zeros, ask which of those two you'd compare against. Is a data set "zero-inflated" if the problem was the wrong count model all along?
Not every unit had the same chance
ReadA group with ten times the policyholders will have about ten times the claims. Counts only compare fairly per unit of exposureExposureHow much opportunity each row had to produce the count (policy-years, hours, area), so the model learns a rate.: policyholders, person-years, hours observed.
Add with its coefficient fixed at 1, and you've got a model of the rate:
χ²(9, N = 64) = 184.84, p < .001
- LR χ²
- 184.84
- p
- < .001
- Pearson dispersion
- 0.9005
- AIC
- 388.74
Plots
View data
| Count | Expected | Observed |
|---|---|---|
| 0 | 0.5860 | 1 |
| 1 | 1.054 | 0 |
| 2 | 1.334 | 2 |
| 3 | 1.597 | 1 |
| 4 | 1.856 | 3 |
| 5 | 2.032 | 3 |
| 6 | 2.070 | 1 |
| 7 | 1.985 | 2 |
| 8 | 1.832 | 3 |
| 9 | 1.668 | 0 |
| 10 | 1.529 | 3 |
| 11 | 1.427 | 1 |
| 12 | 1.360 | 1 |
| 13 | 1.317 | 0 |
| 14 | 1.286 | 1 |
| 15 | 1.255 | 1 |
| 16 | 1.217 | 1 |
| 17 | 1.168 | 0 |
| 18 | 1.106 | 1 |
| 19 | 1.036 | 4 |
| 20 | 0.9626 | 1 |
| 21 | 0.8900 | 0 |
| 22 | 0.8234 | 3 |
| 23 | 0.7661 | 0 |
| 24 | 0.7199 | 2 |
| 25 | 0.6851 | 1 |
| 26 | 0.6610 | 0 |
| 27 | 0.6456 | 0 |
| 28 | 0.6368 | 0 |
| 29 | 0.6319 | 0 |
| 30 | 0.6285 | 0 |
| 31 | 0.6242 | 0 |
| 32 | 0.6171 | 0 |
| 33 | 0.6060 | 1 |
| 34 | 0.5902 | 0 |
| 35 | 0.5695 | 1 |
| 36 | 0.5444 | 1 |
| 37 | 0.5157 | 2 |
| 38 | 0.4847 | 1 |
| 39 | 0.4529 | 1 |
| 40 | 0.4217 | 0 |
| 41 | 0.3926 | 0 |
| 42 | 0.3670 | 0 |
| 43 | 0.3457 | 0 |
| 44 | 0.3296 | 0 |
| 45 | 0.3189 | 0 |
| 46 | 0.3136 | 1 |
| 47 | 0.3133 | 0 |
| 48 | 0.3174 | 0 |
| 49 | 0.3250 | 1 |
| 50 | 0.3350 | 0 |
View data
| Rate ratio | high | Term | low |
|---|---|---|---|
| 1.026 | 1.116 | District: 2 | 0.9432 |
| 1.039 | 1.147 | District: 3 | 0.9413 |
| 1.264 | 1.426 | District: 4 | 1.120 |
| 1.175 | 1.297 | Group: 1-1.5l | 1.064 |
| 1.481 | 1.650 | Group: 1.5-2l | 1.330 |
| 1.757 | 2.024 | Group: >2l | 1.525 |
| 0.8261 | 0.9718 | Age: 25-29 | 0.7023 |
| 0.7083 | 0.8307 | Age: 30-35 | 0.6038 |
| 0.5847 | 0.6706 | Age: >35 | 0.5098 |
View data
| Scaled residual |
|---|
| 0.8677 |
| 0.4595 |
| 0.0579 |
| 0.3926 |
| 0.8627 |
| 0.4847 |
| 0.3218 |
| 0.5485 |
| 0.0040 |
| 0.2577 |
| 0.9674 |
| 0.6001 |
| 0.1144 |
| 0.6973 |
| 0.4292 |
| 0.6486 |
| 0.9781 |
| 0.5271 |
| 0.8448 |
| 0.3474 |
| 0.2674 |
| 0.5195 |
| 0.1388 |
| 0.7200 |
| 0.3245 |
| 0.9452 |
| 0.5434 |
| 0.1180 |
| 0.8082 |
| 0.8989 |
| 0.2259 |
| 0.3857 |
| 0.3579 |
| 0.6509 |
| 0.4397 |
| 0.6715 |
| 0.4857 |
| 0.4556 |
| 0.7521 |
| 0.4113 |
| 0.8561 |
| 0.8305 |
| 0.7183 |
| 0.5059 |
| 0.8065 |
| 0.0188 |
| 0.3940 |
| 0.2063 |
| 0.1235 |
| 0.4193 |
| 0.2412 |
| 0.3992 |
| 0.5227 |
| 0.0680 |
| 0.6104 |
| 0.5284 |
| 0.3945 |
| 0.2661 |
| 0.6413 |
| 0.5972 |
First 60 of 64 rows.
View data
| Predicted value (rank, 0–1) | Scaled residual |
|---|---|
| 0.5938 | 0.8677 |
| 0.6250 | 0.4595 |
| 0.5469 | 0.0579 |
| 0.9219 | 0.3926 |
| 0.7188 | 0.8627 |
| 0.8438 | 0.4847 |
| 0.8750 | 0.3218 |
| 1 | 0.5485 |
| 0.5781 | 0.0040 |
| 0.7500 | 0.2577 |
| 0.7813 | 0.9674 |
| 0.9688 | 0.6001 |
| 0.1875 | 0.1144 |
| 0.4219 | 0.6973 |
| 0.4688 | 0.4292 |
| 0.8281 | 0.6486 |
| 0.3281 | 0.9781 |
| 0.4531 | 0.5271 |
| 0.4375 | 0.8448 |
| 0.8594 | 0.3474 |
| 0.5625 | 0.2674 |
| 0.7031 | 0.5195 |
| 0.7656 | 0.1388 |
| 0.9844 | 0.7200 |
| 0.4063 | 0.3245 |
| 0.6406 | 0.9452 |
| 0.6719 | 0.5434 |
| 0.9375 | 0.1180 |
| 0.0469 | 0.8082 |
| 0.3125 | 0.8989 |
| 0.3594 | 0.2259 |
| 0.7344 | 0.3857 |
| 0.1406 | 0.3579 |
| 0.2656 | 0.6509 |
| 0.2969 | 0.4397 |
| 0.8125 | 0.6715 |
| 0.2813 | 0.4857 |
| 0.5313 | 0.4556 |
| 0.6094 | 0.7521 |
| 0.9531 | 0.4113 |
| 0.1563 | 0.8561 |
| 0.3750 | 0.8305 |
| 0.5000 | 0.7183 |
| 0.8906 | 0.5059 |
| 0.0313 | 0.8065 |
| 0.2031 | 0.0188 |
| 0.2344 | 0.3940 |
| 0.6875 | 0.2063 |
| 0.0625 | 0.1235 |
| 0.1094 | 0.4193 |
| 0.1250 | 0.2412 |
| 0.6563 | 0.3992 |
| 0.2188 | 0.5227 |
| 0.3906 | 0.0680 |
| 0.4844 | 0.6104 |
| 0.9063 | 0.5284 |
| 0.0938 | 0.3945 |
| 0.2500 | 0.2661 |
| 0.3438 | 0.6413 |
| 0.7969 | 0.5972 |
First 60 of 64 rows.
Assumptions
- Overdispersion — Pearson dispersion 0.90 (1 for Poisson); Cameron–Trivedi z = -1.90, p = .971.
- Excess zeros — 1 zeros observed, 0.6 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.089, p = .660 over 250 simulations.
- Residual spread matches the model (simulation) — Observed / simulated spread = 0.52, p = .048; underdispersion: standard errors are conservative.
- No more outliers than expected (simulation) — 0 of 64 rows sit at the edge of their 250 simulations (within 1/251 of either end; binomial test, p = 1.000).
Coefficients (log scale) and rate ratios
| Term | B | SE | z | p | Rate ratio | 95% CI low | 95% CI high |
|---|---|---|---|---|---|---|---|
| (Intercept) | −1.822 | 0.0768 | −23.724 | < .001 | 0.1617 | 0.1391 | 0.1880 |
| District: 2 | 0.0259 | 0.0430 | 0.6014 | .548 | 1.026 | 0.9432 | 1.116 |
| District: 3 | 0.0385 | 0.0505 | 0.7627 | .446 | 1.039 | 0.9413 | 1.147 |
| District: 4 | 0.2342 | 0.0617 | 3.798 | < .001 | 1.264 | 1.120 | 1.426 |
| Group: 1-1.5l | 0.1613 | 0.0505 | 3.193 | .001 | 1.175 | 1.064 | 1.297 |
| Group: 1.5-2l | 0.3928 | 0.0550 | 7.142 | < .001 | 1.481 | 1.330 | 1.650 |
| Group: >2l | 0.5634 | 0.0723 | 7.791 | < .001 | 1.757 | 1.525 | 2.024 |
| Age: 25-29 | −0.1910 | 0.0829 | −2.305 | .021 | 0.8261 | 0.7023 | 0.9718 |
| Age: 30-35 | −0.3450 | 0.0814 | −4.239 | < .001 | 0.7083 | 0.6038 | 0.8307 |
| Age: >35 | −0.5367 | 0.0700 | −7.672 | < .001 | 0.5847 | 0.5098 | 0.6706 |
Rate ratio = exp(B): the multiplicative change in the expected count per unit of Holders.
Observed and expected count frequencies
| Count | Observed | Expected |
|---|---|---|
| 0 | 1 | 0.5860 |
| 1 | 0 | 1.054 |
| 2 | 2 | 1.334 |
| 3 | 1 | 1.597 |
| 4 | 3 | 1.856 |
| 5 | 3 | 2.032 |
| 6 | 1 | 2.070 |
| 7 | 2 | 1.985 |
| 8 | 3 | 1.832 |
| 9 | 0 | 1.668 |
| 10 | 3 | 1.529 |
| 11 | 1 | 1.427 |
| 12 | 1 | 1.360 |
| 13 | 0 | 1.317 |
| 14 | 1 | 1.286 |
| 15 | 1 | 1.255 |
| 16 | 1 | 1.217 |
| 17 | 0 | 1.168 |
| 18 | 1 | 1.106 |
| 19 | 4 | 1.036 |
| 20 | 1 | 0.9626 |
Simulated residual checks (DHARMa)
| Check | Statistic | p |
|---|---|---|
| Uniformity (Kolmogorov–Smirnov D) | 0.0889 | .660 |
| Spread (observed / simulated) | 0.5236 | .048 |
| Zeros (observed / simulated) | 1.667 | 1.000 |
| Outliers (rows at the edge of their simulations) | 0 | 1.000 |
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, offset log(Holders); Wald z tests.
The exact R script · R 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 f37c464835cdd9e4
# Dataset: insurance (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/insurance.parquet", col_select = c("Claims", "District", "Group", "Age", "Holders")))
n_input <- nrow(df)
df[["District"]] <- factor(df[["District"]], levels = c("1", "2", "3", "4")) # stored level order
df[["Group"]] <- factor(df[["Group"]], levels = c("<1l", "1-1.5l", "1.5-2l", ">2l")) # stored level order
df[["Age"]] <- factor(df[["Age"]], levels = c("<25", "25-29", "30-35", ">35")) # stored level order
df <- df[stats::complete.cases(df[c("Claims", "District", "Group", "Age", "Holders")]), , 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("Claims", "District", "Group", "Age", "Holders")) # infinite values stop the run (registry/errors.yaml)
# %% Outcome, exposure and model
outcome <- "Claims"
predictors <- c("District", "Group", "Age")
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 <- "Holders"
if (any(df[[exposure]] <= 0)) stop(sprintf("%s must be positive (its log is the offset).", exposure))
offset <- log(df[[exposure]]) # log exposure: effects are rate ratios
# 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
))
χ²(9, N = 64) = 184.84, p < .001
- LR χ²
- 184.84
- p
- < .001
- Pearson dispersion
- 0.9005
- AIC
- 388.74
To keep this page light, the plots are shown once, under the R tab.
Assumptions
- Overdispersion — Pearson dispersion 0.90 (1 for Poisson); Cameron–Trivedi z = -1.90, p = .971.
- Excess zeros — 1 zeros observed, 0.6 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.089, p = .660 over 250 simulations.
- Residual spread matches the model (simulation) — Observed / simulated spread = 0.52, p = .048; underdispersion: standard errors are conservative.
- No more outliers than expected (simulation) — 0 of 64 rows sit at the edge of their 250 simulations (within 1/251 of either end; binomial test, p = 1.000).
Coefficients (log scale) and rate ratios
| Term | B | SE | z | p | Rate ratio | 95% CI low | 95% CI high |
|---|---|---|---|---|---|---|---|
| (Intercept) | −1.822 | 0.0768 | −23.724 | < .001 | 0.1617 | 0.1391 | 0.1880 |
| District: 2 | 0.0259 | 0.0430 | 0.6014 | .548 | 1.026 | 0.9432 | 1.116 |
| District: 3 | 0.0385 | 0.0505 | 0.7627 | .446 | 1.039 | 0.9413 | 1.147 |
| District: 4 | 0.2342 | 0.0617 | 3.798 | < .001 | 1.264 | 1.120 | 1.426 |
| Group: 1-1.5l | 0.1613 | 0.0505 | 3.193 | .001 | 1.175 | 1.064 | 1.297 |
| Group: 1.5-2l | 0.3928 | 0.0550 | 7.142 | < .001 | 1.481 | 1.330 | 1.650 |
| Group: >2l | 0.5634 | 0.0723 | 7.791 | < .001 | 1.757 | 1.525 | 2.024 |
| Age: 25-29 | −0.1910 | 0.0829 | −2.305 | .021 | 0.8261 | 0.7023 | 0.9718 |
| Age: 30-35 | −0.3450 | 0.0814 | −4.239 | < .001 | 0.7083 | 0.6038 | 0.8307 |
| Age: >35 | −0.5367 | 0.0700 | −7.672 | < .001 | 0.5847 | 0.5098 | 0.6706 |
Rate ratio = exp(B): the multiplicative change in the expected count per unit of Holders.
Observed and expected count frequencies
| Count | Observed | Expected |
|---|---|---|
| 0 | 1 | 0.5860 |
| 1 | 0 | 1.054 |
| 2 | 2 | 1.334 |
| 3 | 1 | 1.597 |
| 4 | 3 | 1.856 |
| 5 | 3 | 2.032 |
| 6 | 1 | 2.070 |
| 7 | 2 | 1.985 |
| 8 | 3 | 1.832 |
| 9 | 0 | 1.668 |
| 10 | 3 | 1.529 |
| 11 | 1 | 1.427 |
| 12 | 1 | 1.360 |
| 13 | 0 | 1.317 |
| 14 | 1 | 1.286 |
| 15 | 1 | 1.255 |
| 16 | 1 | 1.217 |
| 17 | 0 | 1.168 |
| 18 | 1 | 1.106 |
| 19 | 4 | 1.036 |
| 20 | 1 | 0.9626 |
Simulated residual checks (DHARMa)
| Check | Statistic | p |
|---|---|---|
| Uniformity (Kolmogorov–Smirnov D) | 0.0889 | .660 |
| Spread (observed / simulated) | 0.5236 | .048 |
| Zeros (observed / simulated) | 1.667 | 1.000 |
| Outliers (rows at the edge of their simulations) | 0 | 1.000 |
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, offset log(Holders); Wald z tests.
The exact Python script · Python 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 f37c464835cdd9e4
# Dataset: insurance (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/insurance.parquet", columns=["Claims", "District", "Group", "Age", "Holders"])
n_input = len(df)
df["District"] = pd.Categorical(df["District"], categories=["1", "2", "3", "4"]) # stored level order
df["Group"] = pd.Categorical(df["Group"], categories=["<1l", "1-1.5l", "1.5-2l", ">2l"]) # stored level order
df["Age"] = pd.Categorical(df["Age"], categories=["<25", "25-29", "30-35", ">35"]) # stored level order
df = df.dropna(subset=["Claims", "District", "Group", "Age", "Holders"]) # listwise deletion over the analysis columns
df["District"] = df["District"].cat.remove_unused_categories()
df["Group"] = df["Group"].cat.remove_unused_categories()
df["Age"] = df["Age"].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, ["Claims", "District", "Group", "Age", "Holders"]) # infinite values stop the run (registry/errors.yaml)
# %% Outcome, exposure and design matrix
outcome = "Claims"
predictors = ["District", "Group", "Age"]
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 = "Holders"
if (df[exposure] <= 0).any():
raise ValueError(f"{exposure} must be positive (its log is the offset).")
offset = np.log(df[exposure].to_numpy(dtype=float)) # log exposure: effects are rate ratios
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,
})
Across these 64 groups, dispersion is 0.901 and the test gives p = .971. This Poisson model shows no overdispersion, so you needn't fix anything.
Check your understanding
CheckpointCheck yourself
Compared with low tension, high tension has an IRR of 0.6. What does it say?
Show the answer
Answer: a
An IRR multiplies the expected count: 0.6 means 40% fewer, whatever the baseline.
Check yourself
A Poisson fit reports a dispersion of 4.26. By what factor would quasi-Poisson multiply each standard error? Give two decimals.
Show the answer
Answer: 2.06
The square root of the dispersion: about 2.06, so every interval doubles in width.
Check yourself
You model infections per hospital. Hospitals differ a lot in patient-days. What should you do?
Show the answer
Answer: b
The exposure enters as a log offset with its coefficient fixed at 1, which makes the model one of rates.
Check yourself
Your counts are overdispersed, and you want to compare several models by AIC. Which fits?
Show the answer
Answer: c
Quasi-Poisson has no likelihood, so it has no AIC. Plain Poisson would understate every standard error.
Fit yours
In the appPick a Count outcome and your Predictors, add an Exposure if units differ in opportunity, and set Model to Poisson, quasi-Poisson or negative binomial. If the check flags overdispersion, the card offers both remedies.
import numpy as np
import pandas as pd
import statsmodels.api as sm
import statsmodels.formula.api as smf
df = pd.read_csv("warpbreaks.csv")
fit = smf.glm("breaks ~ wool + tension", data=df, family=sm.families.Poisson()).fit()
print(np.exp(fit.params))
print("dispersion:", fit.pearson_chi2 / fit.df_resid)
quine = pd.read_csv("quine.csv")
nb = smf.negativebinomial("Days ~ Eth + Sex + Age + Lrn", data=quine).fit(disp=0)
print("theta:", 1 / nb.params["alpha"])
claims = pd.read_csv("insurance.csv")
rate = smf.glm("Claims ~ C(District) + Group + Age", data=claims,
offset=np.log(claims["Holders"]), family=sm.families.Poisson()).fit()
print(rate.summary())library(MASS)
df <- read.csv("warpbreaks.csv")
fit <- glm(breaks ~ wool + tension, data = df, family = poisson)
exp(coef(fit))
sum(residuals(fit, "pearson")^2) / df.residual(fit)
quine_df <- read.csv("quine.csv")
nb <- glm.nb(Days ~ Eth + Sex + Age + Lrn, data = quine_df)
nb$theta
claims <- read.csv("insurance.csv")
rate <- glm(Claims ~ factor(District) + Group + Age + offset(log(Holders)),
data = claims, family = poisson)
summary(rate)The reference levels in these scripts follow each language's alphabetical order, so they can differ from the card.
Recap
Recap- Counts use a log link, so effects are rate ratios that multiply.
- Use an exposure offset when units had different opportunity.
- Poisson forces the variance to equal the mean. Check the dispersion ratio and its test.
- Quasi-Poisson rescales the standard errors; negative binomial models the spread and has an AIC.
Concepts in this lesson