Skip to content

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.

Applied ~13 min11 steps

What runs in CodeSplash

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

01

A model for counts

Read

Yarn 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:

ln⁡E[Y]=β0+β1x1+…\ln E[Y] = \beta_0 + \beta_1 x_1 + \dots

The log keeps every prediction positive, and it makes effects multiply rather than add.

02

Make a prediction

Predict

Predict first

A predictor has a coefficient of ln⁡2\ln 2. 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 eln⁡2=2e^{\ln 2} = 2, 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.

03

Read the card

In the app
Poisson regressionRecorded · Python and R agreeRecorded 2026-11-17 · 64 values compared
R

χ²(3, N = 54) = 86.98, p < .001

LR χ²
86.980
p
< .001
Pearson dispersion
4.262
AIC
493.06

Plots

Hanging rootogramDoes a count model fit the distribution of counts — zeros, overdispersion, the tail?
View data
CountExpectedObserved
03.323e-80
16.497e-70
26.360e-60
34.157e-50
40.00020
50.00080
60.00260
70.00750
80.01860
90.04120
100.08261
110.15160
120.25681
130.40471
140.59761
150.83223
161.0992
171.3842
181.6683
191.9342
202.1652
212.3504
222.4810
232.5570
242.5802
252.5581
262.4994
272.4131
282.3073
292.1894
302.0652
311.9401
321.8150
331.6920
341.5730
351.4581
361.3462
371.2380
381.1330
391.0312
400.93160
410.83471
420.74061
430.64991
440.56331
450.48170
460.40610
470.33710
480.27550
490.22150
500.17510
Rate ratiosHow large are several estimates, how precise, and which exclude the null?
View data
Rate ratiohighTermlow
0.81380.9004wool: B0.7356
0.72520.8161tension: M0.6444
0.59540.6749tension: H0.5253
Simulated residuals against the uniform distributionIs a variable (or a set of residuals) approximately normal, and where does it depart?
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
Simulated residuals against the predicted value (rank)How do two numeric variables move together?
View data
Predicted value (rank, 0–1)Scaled residual
0.92590.0247
0.92590.0524
0.92590.9760
0.92590.0199
0.92591
0.92590.9746
0.92590.9566
0.92590.0042
0.92591
0.59260.0120
0.59260.0711
0.59260.4979
0.59260.0064
0.59260
0.59260.0132
0.59260.8534
0.59260.6296
0.59260.8802
0.42590.9828
0.42590.2053
0.42590.4975
0.42590.0926
0.42590
0.42591
0.42590.7656
0.42590.0313
0.42590.7272
0.75930.1863
0.75930
0.75930.2758
0.75930.0017
0.75930.2583
0.75930.4143
0.75930.9306
0.75930.0108
0.75930.9633
0.25931
0.25930.7419
0.25930.1398
0.25930.0481
0.25931
0.25930.8219
0.25930.2886
0.25931
0.25930.8840
0.09260.5331
0.09260.7088
0.09260.9120
0.09260.2680
0.09260.0536
0.09260.1825
0.09260.1809
0.09260.2428
0.09260.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

TermBSEzpRate ratio95% CI low95% CI high
(Intercept)3.6920.045481.301< .00140.12436.70743.858
wool: B−0.20600.0516−3.994< .0010.81380.73560.9004
tension: M−0.32130.0603−5.332< .0010.72520.64440.8161
tension: H−0.51850.0640−8.107< .0010.59540.52530.6749

Rate ratio = exp(B): the multiplicative change in the expected count.

Observed and expected count frequencies

CountObservedExpected
003.323e-8
106.497e-7
206.360e-6
304.157e-5
400.0002
500.0008
600.0026
700.0075
800.0186
900.0412
1010.0826
1100.1516
1210.2568
1310.4047
1410.5976
1530.8322
1621.099
1721.384
1831.668
1921.934
2022.165

Simulated residual checks (DHARMa)

CheckStatisticp
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
))
Python

χ²(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

TermBSEzpRate ratio95% CI low95% CI high
(Intercept)3.6920.045481.301< .00140.12436.70743.858
wool: B−0.20600.0516−3.994< .0010.81380.73560.9004
tension: M−0.32130.0603−5.332< .0010.72520.64440.8161
tension: H−0.51850.0640−8.107< .0010.59540.52530.6749

Rate ratio = exp(B): the multiplicative change in the expected count.

Observed and expected count frequencies

CountObservedExpected
003.323e-8
106.497e-7
206.360e-6
304.157e-5
400.0002
500.0008
600.0026
700.0075
800.0186
900.0412
1010.0826
1100.1516
1210.2568
1310.4047
1410.5976
1530.8322
1621.099
1721.384
1831.668
1921.934
2022.165

Simulated residual checks (DHARMa)

CheckStatisticp
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 χ2\chi^2(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.

04

Is the variance too big?

Predict

A Poisson model has one parameter, so it forces the variance to equal the mean. The dispersion ratio is Pearson χ2\chi^2 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?

Close to 1About 2Well above 2
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.

05

See what it does to a test

Explore

DExplorable · 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?

0.50
How sure?
5.0
1.5
30
Simulating…

Commit your prediction above to see the result

Make your prediction first; the figure appears when you commit.

Make your prediction to see the result.

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.

06

Two remedies

Read

Quasi-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 θ\theta, so the variance becomes μ+μ2/θ\mu + \mu^2/\theta. It has a likelihood, so AIC works, and a smaller θ\theta 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 θ\theta = 1.27.

Negative binomial regressionRecorded · Python and R agreeRecorded 2026-11-17 · 93 values compared · largest relative difference 8.2e-11
R

χ²(6, N = 146) = 25.12, p < .001

LR χ²
25.116
p
< .001
Pearson dispersion
13.167
θ
1.275
AIC
1109.15

Plots

Hanging rootogramDoes a count model fit the distribution of counts — zeros, overdispersion, the tail?
View data
CountExpectedObserved
06.2149
17.1484
27.3466
37.2566
47.0261
56.72419
66.3898
76.0396
85.6894
95.3462
105.0154
114.6987
124.3972
134.1133
143.8468
153.5953
163.3603
173.1414
182.9361
192.7441
202.5663
212.4001
222.2454
232.1013
241.9671
251.8422
261.7260
271.6172
281.5162
291.4220
301.3342
311.2520
321.1752
331.1041
341.0371
350.97450
360.91623
370.86181
380.81091
390.76320
400.71862
410.67691
420.63770
430.60111
440.56670
450.53451
460.50421
470.47591
480.44921
490.42420
500.40070
Rate ratiosHow large are several estimates, how precise, and which exclude the null?
View data
Rate ratiohighTermlow
0.56590.7643Eth: N0.4190
1.0861.485Sex: M0.7937
0.63861.022Age: F10.3992
1.0921.735Age: F20.6874
1.4292.325Age: F30.8783
1.3391.930Lrn: SL0.9293
Simulated residuals against the uniform distributionIs a variable (or a set of residuals) approximately normal, and where does it depart?
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.

Simulated residuals against the predicted value (rank)How do two numeric variables move together?
View data
Predicted value (rank, 0–1)Scaled residual
0.86300.0609
0.86300.2907
0.86300.4415
0.71230.1907
0.71230.2127
0.71230.4610
0.71230.6178
0.71230.6278
0.65750.2796
0.65750.2480
0.65750.5600
0.34590.4097
0.34590.6320
0.98970.1326
0.98970.6420
0.98970.8685
0.98970.8779
0.76030.4340
0.76030.5303
0.76030.5130
0.76030.5206
0.76030.8440
0.76030.8640
0.76030.8840
0.95210.1660
0.95210.5197
0.95210.5222
0.95210.6047
0.95210.6804
0.95210.6965
0.95210.7234
0.78770.1195
0.68150.2056
0.68150.4104
0.68150.7773
0.68150.9600
0.54450.2312
0.54450.2942
0.54450.3338
0.54450.4085
0.54450.5494
0.54450.7145
0.54450.8067
0.54450.8779
0.54450.9720
0.54450.9760
0.27400.3544
0.27400.3013
0.27400.6171
0.27400.7698
0.27400.8040
0.90070.2321
0.90070.2936
0.90070.4266
0.90070.5016
0.90070.8060
0.90070.8614
0.90070.9080
0.90070.9343
0.73290.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

TermBSEzpRate ratio95% CI low95% CI high
(Intercept)2.8950.228412.672< .00118.07611.55228.284
Eth: N−0.56940.1533−3.713< .0010.56590.41900.7643
Sex: M0.08230.15990.5148.6071.0860.79371.485
Age: F1−0.44840.2397−1.870.0610.63860.39921.022
Age: F20.08810.23620.3729.7091.0920.68741.735
Age: F30.35690.24831.437.1511.4290.87832.325
Lrn: SL0.29210.18651.566.1171.3390.92931.930

Rate ratio = exp(B): the multiplicative change in the expected count.

Observed and expected count frequencies

CountObservedExpected
096.214
147.148
267.346
367.256
417.026
5196.724
686.389
766.039
845.689
925.346
1045.015
1174.698
1224.397
1334.113
1483.846
1533.595
1633.360
1743.141
1812.936
1912.744
2032.566

Simulated residual checks (DHARMa)

CheckStatisticp
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
))
Python

χ²(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

TermBSEzpRate ratio95% CI low95% CI high
(Intercept)2.8950.228412.672< .00118.07611.55228.284
Eth: N−0.56940.1533−3.713< .0010.56590.41900.7643
Sex: M0.08230.15990.5148.6071.0860.79371.485
Age: F1−0.44840.2397−1.870.0610.63860.39921.022
Age: F20.08810.23620.3729.7091.0920.68741.735
Age: F30.35690.24831.437.1511.4290.87832.325
Lrn: SL0.29210.18651.566.1171.3390.92931.930

Rate ratio = exp(B): the multiplicative change in the expected count.

Observed and expected count frequencies

CountObservedExpected
096.214
147.148
267.346
367.256
417.026
5196.724
686.389
766.039
845.689
925.346
1045.015
1174.698
1224.397
1334.113
1483.846
1533.595
1633.360
1743.141
1812.936
1912.744
2032.566

Simulated residual checks (DHARMa)

CheckStatisticp
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,
})
07

Count the zeros

Reflect

The 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?

08

Not every unit had the same chance

Read

A 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 ln⁡(exposure)\ln(\text{exposure}) with its coefficient fixed at 1, and you've got a model of the rate:

ln⁡E[Y]exposure=β0+β1x1+…\ln\frac{E[Y]}{\text{exposure}} = \beta_0 + \beta_1 x_1 + \dots
Poisson regressionRecorded · Python and R agreeRecorded 2026-11-17 · 118 values compared
R

χ²(9, N = 64) = 184.84, p < .001

LR χ²
184.84
p
< .001
Pearson dispersion
0.9005
AIC
388.74

Plots

Hanging rootogramDoes a count model fit the distribution of counts — zeros, overdispersion, the tail?
View data
CountExpectedObserved
00.58601
11.0540
21.3342
31.5971
41.8563
52.0323
62.0701
71.9852
81.8323
91.6680
101.5293
111.4271
121.3601
131.3170
141.2861
151.2551
161.2171
171.1680
181.1061
191.0364
200.96261
210.89000
220.82343
230.76610
240.71992
250.68511
260.66100
270.64560
280.63680
290.63190
300.62850
310.62420
320.61710
330.60601
340.59020
350.56951
360.54441
370.51572
380.48471
390.45291
400.42170
410.39260
420.36700
430.34570
440.32960
450.31890
460.31361
470.31330
480.31740
490.32501
500.33500
Rate ratiosHow large are several estimates, how precise, and which exclude the null?
View data
Rate ratiohighTermlow
1.0261.116District: 20.9432
1.0391.147District: 30.9413
1.2641.426District: 41.120
1.1751.297Group: 1-1.5l1.064
1.4811.650Group: 1.5-2l1.330
1.7572.024Group: >2l1.525
0.82610.9718Age: 25-290.7023
0.70830.8307Age: 30-350.6038
0.58470.6706Age: >350.5098
Simulated residuals against the uniform distributionIs a variable (or a set of residuals) approximately normal, and where does it depart?
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.

Simulated residuals against the predicted value (rank)How do two numeric variables move together?
View data
Predicted value (rank, 0–1)Scaled residual
0.59380.8677
0.62500.4595
0.54690.0579
0.92190.3926
0.71880.8627
0.84380.4847
0.87500.3218
10.5485
0.57810.0040
0.75000.2577
0.78130.9674
0.96880.6001
0.18750.1144
0.42190.6973
0.46880.4292
0.82810.6486
0.32810.9781
0.45310.5271
0.43750.8448
0.85940.3474
0.56250.2674
0.70310.5195
0.76560.1388
0.98440.7200
0.40630.3245
0.64060.9452
0.67190.5434
0.93750.1180
0.04690.8082
0.31250.8989
0.35940.2259
0.73440.3857
0.14060.3579
0.26560.6509
0.29690.4397
0.81250.6715
0.28130.4857
0.53130.4556
0.60940.7521
0.95310.4113
0.15630.8561
0.37500.8305
0.50000.7183
0.89060.5059
0.03130.8065
0.20310.0188
0.23440.3940
0.68750.2063
0.06250.1235
0.10940.4193
0.12500.2412
0.65630.3992
0.21880.5227
0.39060.0680
0.48440.6104
0.90630.5284
0.09380.3945
0.25000.2661
0.34380.6413
0.79690.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

TermBSEzpRate ratio95% CI low95% CI high
(Intercept)−1.8220.0768−23.724< .0010.16170.13910.1880
District: 20.02590.04300.6014.5481.0260.94321.116
District: 30.03850.05050.7627.4461.0390.94131.147
District: 40.23420.06173.798< .0011.2641.1201.426
Group: 1-1.5l0.16130.05053.193.0011.1751.0641.297
Group: 1.5-2l0.39280.05507.142< .0011.4811.3301.650
Group: >2l0.56340.07237.791< .0011.7571.5252.024
Age: 25-29−0.19100.0829−2.305.0210.82610.70230.9718
Age: 30-35−0.34500.0814−4.239< .0010.70830.60380.8307
Age: >35−0.53670.0700−7.672< .0010.58470.50980.6706

Rate ratio = exp(B): the multiplicative change in the expected count per unit of Holders.

Observed and expected count frequencies

CountObservedExpected
010.5860
101.054
221.334
311.597
431.856
532.032
612.070
721.985
831.832
901.668
1031.529
1111.427
1211.360
1301.317
1411.286
1511.255
1611.217
1701.168
1811.106
1941.036
2010.9626

Simulated residual checks (DHARMa)

CheckStatisticp
Uniformity (Kolmogorov–Smirnov D)0.0889.660
Spread (observed / simulated)0.5236.048
Zeros (observed / simulated)1.6671.000
Outliers (rows at the edge of their simulations)01.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
))
Python

χ²(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

TermBSEzpRate ratio95% CI low95% CI high
(Intercept)−1.8220.0768−23.724< .0010.16170.13910.1880
District: 20.02590.04300.6014.5481.0260.94321.116
District: 30.03850.05050.7627.4461.0390.94131.147
District: 40.23420.06173.798< .0011.2641.1201.426
Group: 1-1.5l0.16130.05053.193.0011.1751.0641.297
Group: 1.5-2l0.39280.05507.142< .0011.4811.3301.650
Group: >2l0.56340.07237.791< .0011.7571.5252.024
Age: 25-29−0.19100.0829−2.305.0210.82610.70230.9718
Age: 30-35−0.34500.0814−4.239< .0010.70830.60380.8307
Age: >35−0.53670.0700−7.672< .0010.58470.50980.6706

Rate ratio = exp(B): the multiplicative change in the expected count per unit of Holders.

Observed and expected count frequencies

CountObservedExpected
010.5860
101.054
221.334
311.597
431.856
532.032
612.070
721.985
831.832
901.668
1031.529
1111.427
1211.360
1301.317
1411.286
1511.255
1611.217
1701.168
1811.106
1941.036
2010.9626

Simulated residual checks (DHARMa)

CheckStatisticp
Uniformity (Kolmogorov–Smirnov D)0.0889.660
Spread (observed / simulated)0.5236.048
Zeros (observed / simulated)1.6671.000
Outliers (rows at the edge of their simulations)01.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.

09

Check your understanding

Checkpoint

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

10

Fit yours

In the app

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

Python
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())
R
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.

11

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