Skip to content

Too many zeros: zero-inflated, hurdle and censored models

A pile of zeros can come from overdispersion, from a second process, from a decision, or from a limit. Each points to a different model, and the zero part reads differently in each.

Advanced ~13 min11 steps

What runs in CodeSplash

You will be able to

  • Tell sampling zeros from structural zeros
  • Fit a zero-inflated model and read its two parts
  • Say how a hurdle model differs, and why its zero coefficients flip sign
  • Read Vuong's test with care, and recognize when a pile of zeros is really censoring

Read first

01

Two kinds of zero

Read

A PhD student publishes no articles in three years. Perhaps they submitted and had bad luck. Perhaps they were never going to publish.

Those are two kinds of zero. A sampling zero comes from the same process as the positive counts. A structural zero comes from a different one. An ordinary count model has only the first kind.

In this sample of 915 biochemistry students, 275 had no articles.

02

A mixture of two processes

Read

A zero-inflated modelZero-inflated modelMixes an always-zero group, with its own logistic model, with an ordinary count model that can also produce zeros. adds a second equation:

P(Y=0)=π+(1−π) Pcount(0)P(Y = 0) = \pi + (1 - \pi)\,P_{\text{count}}(0)

π\pi is the chance of being an always-zero case, and it gets its own logistic model. Everyone else follows a Poisson or negative binomial, and those counts can still be zero.

So a zero has two possible sources, and the model never says which one produced a given row.

03

Does a flexible model need the extra part?

Predict

Predict first

Zero inflation beats plain Poisson here: Vuong's testVuong testCompares two models' row-by-row log-likelihoods, without assuming either is true. A positive z favors the first. gives p < .001. A negative binomial already allows more zeros than a Poisson. Will zero inflation beat it as decisively?

Yes, equally decisivelyLess decisivelyIt can't be tested
Reveal

Less decisively: p = .060. The negative binomial had already absorbed much of the "excess". Comparing the two zero-inflated fits, AIC falls from 3,227 to 3,125 once the count part allows extra spread.

04

Read the card

In the app
Zero-inflated negative binomialRecorded · Python and R agreeRecorded 2026-11-17 · 43 values compared · largest relative difference 1.8e-5
R

Zero-inflated negative binomial (n = 915): log-likelihood -1553.27, AIC 3124.5; 286.4 zeros expected vs 275 observed; Vuong z = 1.88, p = .060.

Log-likelihood
−1553.27
AIC
3124.54
BIC
3167.91
θ (NB dispersion)
2.726
Vuong z (vs ordinary count model)
1.881
p (Vuong)
.060

Plots

Incidence-rate ratios (count model)How large are several estimates, how precise, and which exclude the null?
View data
IRRhightermlow
0.80900.9315gender[Women]0.7027
1.1501.348married[Married]0.9805
0.84570.9372kids under 60.7630
1.0021.074prestige0.9345
1.0251.032mentor1.018

Assumptions

  • Excess zeros — 275 zeros observed, 286.4 expected by the two-part model; Vuong z = 1.88 against the ordinary count model.
  • Converged fit — The likelihood maximization converged.

Count model (log rate)

TermEstimateSEzpIRRLowerUpper
(Intercept)0.40400.14172.8510.00441.4981.1351.977
gender[Women]−0.21190.0719−2.9460.00320.80900.70270.9315
married[Married]0.13950.08121.7180.08591.1500.98051.348
kids under 6−0.16760.0525−3.1950.00140.84570.76300.9372
prestige0.00200.03560.05520.95601.0020.93451.074
mentor0.02440.00356.9344.080e-121.0251.0181.032

Zero model: log-odds of an excess (structural) zero

TermEstimateSEzpOdds ratio
(Intercept)−0.80670.3532−2.2840.02240.4463
mentor−0.60950.2458−2.4800.01310.5436
  • Zero-inflated models: zero-model coefficients describe the probability of an excess (structural) zero.
  • Vuong's test of non-nested models is controversial for zero inflation (Wilson 2015); compare AIC too.
The exact R script · R R version 4.5.1 (2025-06-13)
# Zero-inflated and hurdle count models
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method regression.zero_inflated 1.0.1 · spec 9bd8c59a7a782764
# Dataset: s4_bio (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.

# %% Setup
suppressPackageStartupMessages(library(pscl))
library(codesplashr) # cs_sel_names_from (coefficient names shared with Python), cs_glm_nb (MASS::glm.nb), cs_cnt_vuong

# %% Data
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/s4_bio.parquet", col_select = c("articles", "gender", "married", "kids under 6", "prestige", "mentor")))
n_input <- nrow(df)
df[["gender"]] <- factor(df[["gender"]], levels = c("Men", "Women"))  # stored level order
df[["married"]] <- factor(df[["married"]], levels = c("Single", "Married"))  # stored level order
df <- df[stats::complete.cases(df[c("articles", "gender", "married", "kids under 6", "prestige", "mentor")]), , 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("articles", "gender", "married", "kids under 6", "prestige", "mentor"))  # infinite values stop the run (registry/errors.yaml)

# %% Data and formulas
yname <- "articles"
predictors <- c("gender", "married", "kids under 6", "prestige", "mentor")
zero_model <- "chosen"
zero_terms <- switch(zero_model, same = predictors, intercept = character(0), chosen = c("mentor"))
if (zero_model == "chosen" && !length(zero_terms)) stop("Choose the zero-model predictors (or pick 'Same predictors' / 'Intercept only')")
y <- as.numeric(df[[yname]])
if (any(y < 0) || any(y != round(y))) stop(sprintf("%s must hold whole-number counts ≥ 0", yname))
model <- "zinb"
# Degenerate input stops with a catalog error; Python runs the same checks in the same order.
# More rows than parameters: both parts' coefficients, plus theta for the negative binomial.
n_params <- length(cs_design_labels(df, predictors)) + length(cs_design_labels(df, zero_terms)) + (if (model %in% c("zinb", "hurdle_negbin")) 1 else 0)
cs_check_rows(nrow(df), n_params + 1, "A zero-inflated or hurdle model")
for (col in c(yname, union(predictors, zero_terms))) cs_check_not_constant(df[[col]], col)  # one value (or one level with data) is no variation
if (!any(y == 0)) cs_error("CS_E_UNDEFINED", what = "A zero-inflated or hurdle model", reason = sprintf("%s has no zeros", yname))
df$.y <- y
rhs <- function(terms) if (length(terms)) paste(sprintf("`%s`", terms), collapse = " + ") else "1"
f <- stats::as.formula(paste(".y ~", rhs(predictors), "|", rhs(zero_terms)))
n <- nrow(df)

# %% Two-part model (pscl)
dist <- if (model %in% c("zip", "hurdle_poisson")) "poisson" else "negbin"
fit <- if (startsWith(model, "hurdle")) {
  hurdle(f, data = df, dist = dist, zero.dist = "binomial", link = "logit", control = hurdle.control(reltol = 1e-15, maxit = 10000))
} else {
  zeroinfl(f, data = df, dist = dist, link = "logit", control = zeroinfl.control(reltol = 1e-15, maxit = 10000))
}
conf <- 0.95
zc <- stats::qnorm(1 - (1 - conf) / 2)
xnames <- cs_sel_names_from(stats::model.matrix(fit, model = "count"), attr(fit$terms$count, "term.labels"), fit$levels)
znames <- cs_sel_names_from(stats::model.matrix(fit, model = "zero"), attr(fit$terms$zero, "term.labels"), fit$levels)
xm <- stats::model.matrix(fit, model = "count")
zm <- stats::model.matrix(fit, model = "zero")
# pscl's BFGS stops early on flat likelihoods and summary(fit) inverts optim's coarse Hessian: polish
# with Newton steps on the shared log-likelihood (as the Python engine does) and take SEs from the
# observed information.
nbin <- dist == "negbin"
pol <- cs_cnt_zi_polish(c(fit$coefficients$count, fit$coefficients$zero, if (nbin) log(fit$theta)), y, xm, zm, model)
kx <- ncol(xm)
kz <- ncol(zm)
cb <- unname(pol$params[seq_len(kx)])
zb <- unname(pol$params[kx + seq_len(kz)])
cse <- pol$se[seq_len(kx)]
zse <- pol$se[kx + seq_len(kz)]
theta <- if (nbin) exp(pol$params[kx + kz + 1]) else NaN
ll_obs <- cs_cnt_zi_loglik_obs(pol$params, y, xm, zm, model)
p_zero <- cs_cnt_zi_p_zero(pol$params, xm, zm, model)
loglik <- sum(ll_obs)
k <- length(pol$params)
aic <- -2 * loglik + 2 * k
bic <- -2 * loglik + log(n) * k

# %% Ordinary count model and Vuong's test
fstd <- stats::as.formula(paste(".y ~", rhs(predictors)))
if (dist == "negbin") {
  nb <- cs_glm_nb(fstd, df, epsilon = 1e-12)  # MASS::glm.nb
  ll0 <- stats::dnbinom(y, size = nb$theta, mu = stats::fitted(nb$fit), log = TRUE)
} else {
  std <- stats::glm(fstd, family = stats::poisson(), data = df, control = stats::glm.control(epsilon = 1e-14, maxit = 100))
  ll0 <- stats::dpois(y, stats::fitted(std), log = TRUE)
}
vu <- cs_cnt_vuong(ll_obs, ll0)
zeros_obs <- sum(y == 0)
zeros_exp <- sum(p_zero)
converged <- isTRUE(fit$converged)

# %% Assumptions
assumptions <- list(
  list(key = "excess_zeros", label = "Excess zeros", status = "info",
       detail = sprintf("%d zeros observed, %.1f expected by the two-part model; Vuong z = %.2f against the ordinary count model.", zeros_obs, zeros_exp, vu$z)),
  list(key = "convergence", label = "Converged fit", status = if (converged) "pass" else "warn",
       detail = if (converged) "The likelihood maximization converged." else "The optimizer did not report convergence; check the estimates.")
)

# %% Result
labels <- c(zip = "Zero-inflated Poisson", zinb = "Zero-inflated negative binomial", hurdle_poisson = "Hurdle Poisson", hurdle_negbin = "Hurdle negative binomial")
values <- list(n = n, model = model, zero_model = zero_model, loglik = loglik, aic = aic, bic = bic, n_params = k,
               theta = theta, zeros_observed = zeros_obs, zeros_expected = zeros_exp, vuong_z = vu$z, vuong_p = vu$p, converged = converged)
count_rows <- list()
for (j in seq_along(xnames)) {
  pz <- 2 * stats::pnorm(-abs(cb[j] / cse[j]))
  values[[sprintf("count_coef[%s]", xnames[j])]] <- cb[j]
  values[[sprintf("count_se[%s]", xnames[j])]] <- cse[j]
  values[[sprintf("count_p[%s]", xnames[j])]] <- pz
  values[[sprintf("irr[%s]", xnames[j])]] <- exp(cb[j])
  count_rows[[j]] <- list(term = xnames[j], b = cb[j], se = cse[j], z = cb[j] / cse[j], p = pz, irr = exp(cb[j]),
                          low = exp(cb[j] - zc * cse[j]), high = exp(cb[j] + zc * cse[j]))
}
zero_rows <- list()
for (j in seq_along(znames)) {
  pz <- 2 * stats::pnorm(-abs(zb[j] / zse[j]))
  values[[sprintf("zero_coef[%s]", znames[j])]] <- zb[j]
  values[[sprintf("zero_se[%s]", znames[j])]] <- zse[j]
  values[[sprintf("zero_p[%s]", znames[j])]] <- pz
  zero_rows[[j]] <- list(term = znames[j], b = zb[j], se = zse[j], z = zb[j] / zse[j], p = pz, or = exp(zb[j]))
}
zero_title <- if (startsWith(model, "hurdle")) "Zero model: log-odds of crossing the hurdle (y > 0)" else "Zero model: log-odds of an excess (structural) zero"
coef_cols <- list(list(key = "term", label = "Term", type = "string"), list(key = "b", label = "Estimate", type = "number"),
                  list(key = "se", label = "SE", type = "number"), list(key = "z", label = "z", type = "number"),
                  list(key = "p", label = "p", type = "number", format = "p"))
eff <- Filter(function(r) r$term != "(Intercept)", count_rows)
cs_publish(list(
  method = "regression.zero_inflated",
  methodVersion = "1.0.1",
  title = labels[[model]],
  engine = cs_engine_info("pscl", "MASS", "nanoparquet"),
  n = n,
  summary = sprintf("%s (n = %d): log-likelihood %.2f, AIC %.1f; %.1f zeros expected vs %d observed; Vuong z = %.2f, %s.",
                    labels[[model]], n, loglik, aic, zeros_exp, zeros_obs, vu$z, cs_fmt_p(vu$p)),
  statistics = list(
    list(key = "loglik", label = "Log-likelihood", value = loglik),
    list(key = "aic", label = "AIC", value = aic),
    list(key = "bic", label = "BIC", value = bic),
    list(key = "theta", label = "θ (NB dispersion)", value = theta),
    list(key = "vuong_z", label = "Vuong z (vs ordinary count model)", value = vu$z),
    list(key = "vuong_p", label = "p (Vuong)", value = vu$p, format = "p")
  ),
  tables = list(
    list(key = "count", title = "Count model (log rate)",
         columns = c(coef_cols, list(list(key = "irr", label = "IRR", type = "number"), list(key = "low", label = "Lower", type = "number"),
                                     list(key = "high", label = "Upper", type = "number"))),
         rows = count_rows),
    list(key = "zero", title = zero_title, columns = c(coef_cols, list(list(key = "or", label = "Odds ratio", type = "number"))), rows = zero_rows)
  ),
  assumptions = assumptions,
  warnings = warnings,
  notes = list(if (startsWith(model, "hurdle")) "Hurdle models: zero-model coefficients describe P(count > 0)." else "Zero-inflated models: zero-model coefficients describe the probability of an excess (structural) zero.",
               "Vuong's test of non-nested models is controversial for zero inflation (Wilson 2015); compare AIC too."),
  charts = if (length(eff)) list(cs_chart(
    "irr", "forest", "Incidence-rate ratios (count model)",
    list(label = cs_col("term", vapply(eff, function(r) r$term, "")), estimate = cs_col("IRR", vapply(eff, function(r) r$irr, 0)),
         low = cs_col("low", vapply(eff, function(r) r$low, 0)), high = cs_col("high", vapply(eff, function(r) r$high, 0)))
  )) else list(),
  values = values
))
Python

Zero-inflated negative binomial (n = 915): log-likelihood -1553.27, AIC 3124.5; 286.4 zeros expected vs 275 observed; Vuong z = 1.88, p = .060.

Log-likelihood
−1553.27
AIC
3124.54
BIC
3167.91
θ (NB dispersion)
2.726
Vuong z (vs ordinary count model)
1.881
p (Vuong)
.060

To keep this page light, the plots are shown once, under the R tab.

Assumptions

  • Excess zeros — 275 zeros observed, 286.4 expected by the two-part model; Vuong z = 1.88 against the ordinary count model.
  • Converged fit — The likelihood maximization converged.

Count model (log rate)

TermEstimateSEzpIRRLowerUpper
(Intercept)0.40400.14172.8510.00441.4981.1351.977
gender[Women]−0.21190.0719−2.9460.00320.80900.70270.9315
married[Married]0.13950.08121.7180.08591.1500.98051.348
kids under 6−0.16760.0525−3.1950.00140.84570.76300.9372
prestige0.00200.03560.05520.95601.0020.93451.074
mentor0.02440.00356.9344.080e-121.0251.0181.032

Zero model: log-odds of an excess (structural) zero

TermEstimateSEzpOdds ratio
(Intercept)−0.80670.3532−2.2840.02240.4463
mentor−0.60950.2458−2.4800.01310.5436
  • Zero-inflated models: zero-model coefficients describe the probability of an excess (structural) zero.
  • Vuong's test of non-nested models is controversial for zero inflation (Wilson 2015); compare AIC too.
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Zero-inflated and hurdle count models
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method regression.zero_inflated 1.0.1 · spec 9bd8c59a7a782764
# Dataset: s4_bio (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.

# %% Setup
import math

import numpy as np
import pandas as pd
from scipy import stats
from scipy.special import gammaln

import codesplash as cs
from codesplash.errors import check_not_constant
from codesplash.stats import counts as csc  # statsmodels ZI / hurdle fits with pscl's starts; Vuong (twins of codesplashr)
from codesplash.stats import glm as csglm  # NB2 as MASS::glm.nb
from codesplash.stats import selection as sel  # design columns named like the R twin

# %% Data
df = pd.read_parquet("tests/parity/fixtures/s4_bio.parquet", columns=["articles", "gender", "married", "kids under 6", "prestige", "mentor"])
n_input = len(df)
df["gender"] = pd.Categorical(df["gender"], categories=["Men", "Women"])  # stored level order
df["married"] = pd.Categorical(df["married"], categories=["Single", "Married"])  # stored level order
df = df.dropna(subset=["articles", "gender", "married", "kids under 6", "prestige", "mentor"])  # listwise deletion over the analysis columns
df["gender"] = df["gender"].cat.remove_unused_categories()
df["married"] = df["married"].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, ["articles", "gender", "married", "kids under 6", "prestige", "mentor"])  # infinite values stop the run (registry/errors.yaml)

# %% Data and designs
yname = "articles"
predictors = ["gender", "married", "kids under 6", "prestige", "mentor"]
zero_model = "chosen"
zero_terms = {"same": predictors, "intercept": [], "chosen": ["mentor"]}[zero_model]
if zero_model == "chosen" and not zero_terms:
    raise ValueError("Choose the zero-model predictors (or pick 'Same predictors' / 'Intercept only')")
kinds = {"articles":"numeric","gender":"categorical","kids under 6":"numeric","married":"categorical","mentor":"numeric","prestige":"numeric"}
y = df[yname].to_numpy(dtype=float)
if np.any(y < 0) or np.any(y != np.round(y)):
    raise ValueError(f"{yname} must hold whole-number counts ≥ 0")
levels = {p: ([str(v) for v in df[p].cat.categories] if kinds[p] in ("categorical", "boolean") else None) for p in set(predictors) | set(zero_terms)}
x, xnames, _ = sel.design(df, predictors, levels)
z, znames, _ = sel.design(df, zero_terms, levels)
n = len(y)
model = "zinb"
# Degenerate input stops with a catalog error; R runs the same checks in the same order.
# More rows than parameters: both parts' coefficients, plus θ for the negative binomial.
n_params = x.shape[1] + z.shape[1] + (1 if model in ("zinb", "hurdle_negbin") else 0)
cs.check_rows(n, n_params + 1, "A zero-inflated or hurdle model")
for col in [yname] + list(dict.fromkeys(predictors + zero_terms)):
    check_not_constant(df[col], col)  # one value (or one level with data) is no variation
if not np.any(y == 0):
    cs.cs_error("CS_E_UNDEFINED", what="A zero-inflated or hurdle model", reason=f"{yname} has no zeros")

# %% Two-part model (statsmodels; pscl::zeroinfl / hurdle in R)
fit = csc.zero_count_fit(y, x, z, model)
nb = model in ("zinb", "hurdle_negbin")
# Newton polishing on the shared log-likelihood (the R engine polishes pscl's fit the same way),
# then SEs from the observed information.
start = np.r_[fit["count"], fit["zero"], [math.log(fit["theta"])] if nb else []]
params, se_all = csc.zi_polish(start, y, x, z, model)
kx, kz = x.shape[1], z.shape[1]
fit.update({"count": params[:kx], "count_se": se_all[:kx], "zero": params[kx : kx + kz], "zero_se": se_all[kx : kx + kz],
            "theta": math.exp(params[-1]) if nb else math.nan, "ll_obs": csc.zi_loglik_obs(params, y, x, z, model),
            "p_zero": csc.zi_p_zero(params, x, z, model)})
conf = 0.95
zc = stats.norm.ppf(1 - (1 - conf) / 2)
loglik = float(fit["ll_obs"].sum())
k = fit["k"]
aic, bic = -2 * loglik + 2 * k, -2 * loglik + math.log(n) * k

# %% Ordinary count model and Vuong's test
if nb:
    std, theta0, _ = csglm.nb_fit(y, x, tol=1e-12)  # MASS::glm.nb
    mu0 = np.asarray(std.mu)
    ll0 = gammaln(y + theta0) - gammaln(theta0) - gammaln(y + 1) + theta0 * np.log(theta0 / (theta0 + mu0)) + y * np.log(mu0 / (theta0 + mu0))
else:
    std = sel.fit_model(x, y, "poisson")  # glm(family = poisson), deviance criterion 1e-14
    mu0 = std["mu"]
    ll0 = y * np.log(mu0) - mu0 - gammaln(y + 1)
vu = csc.vuong(fit["ll_obs"], ll0)
zeros_obs = int(np.sum(y == 0))
zeros_exp = float(np.sum(fit["p_zero"]))

# %% Assumptions
assumptions = [
    {"key": "excess_zeros", "label": "Excess zeros", "status": "info",
     "detail": f"{zeros_obs} zeros observed, {zeros_exp:.1f} expected by the two-part model; Vuong z = {vu['z']:.2f} against the ordinary count model."},
    {"key": "convergence", "label": "Converged fit", "status": "pass" if fit["converged"] else "warn",
     "detail": "The likelihood maximization converged." if fit["converged"] else "The optimizer did not report convergence; check the estimates."},
]

# %% Result
labels = {"zip": "Zero-inflated Poisson", "zinb": "Zero-inflated negative binomial", "hurdle_poisson": "Hurdle Poisson", "hurdle_negbin": "Hurdle negative binomial"}
values = {"n": n, "model": model, "zero_model": zero_model, "loglik": loglik, "aic": aic, "bic": bic, "n_params": k,
          "theta": fit["theta"], "zeros_observed": zeros_obs, "zeros_expected": zeros_exp, "vuong_z": vu["z"], "vuong_p": vu["p"],
          "converged": fit["converged"]}
count_rows, zero_rows = [], []
for nm, b, s in zip(xnames, fit["count"], fit["count_se"]):
    pz = float(2 * stats.norm.sf(abs(b / s)))
    values.update({f"count_coef[{nm}]": float(b), f"count_se[{nm}]": float(s), f"count_p[{nm}]": pz, f"irr[{nm}]": math.exp(b)})
    count_rows.append({"term": nm, "b": float(b), "se": float(s), "z": float(b / s), "p": pz, "irr": math.exp(b),
                       "low": math.exp(b - zc * s), "high": math.exp(b + zc * s)})
for nm, b, s in zip(znames, fit["zero"], fit["zero_se"]):
    pz = float(2 * stats.norm.sf(abs(b / s)))
    values.update({f"zero_coef[{nm}]": float(b), f"zero_se[{nm}]": float(s), f"zero_p[{nm}]": pz})
    zero_rows.append({"term": nm, "b": float(b), "se": float(s), "z": float(b / s), "p": pz, "or": math.exp(b)})
zero_title = "Zero model: log-odds of crossing the hurdle (y > 0)" if model.startswith("hurdle") else "Zero model: log-odds of an excess (structural) zero"
coef_cols = [{"key": "term", "label": "Term", "type": "string"}, {"key": "b", "label": "Estimate", "type": "number"},
             {"key": "se", "label": "SE", "type": "number"}, {"key": "z", "label": "z", "type": "number"},
             {"key": "p", "label": "p", "type": "number", "format": "p"}]
eff = [r for r in count_rows if r["term"] != "(Intercept)"]
cs.publish({
    "method": "regression.zero_inflated",
    "methodVersion": "1.0.1",
    "title": labels[model],
    "engine": cs.engine_info("pandas", "numpy", "scipy", "statsmodels"),
    "n": n,
    "summary": f"{labels[model]} (n = {n}): log-likelihood {loglik:.2f}, AIC {aic:.1f}; {zeros_exp:.1f} zeros expected vs {zeros_obs} observed; Vuong z = {vu['z']:.2f}, {cs.fmt_p(vu['p'])}.",
    "statistics": [
        {"key": "loglik", "label": "Log-likelihood", "value": loglik},
        {"key": "aic", "label": "AIC", "value": aic},
        {"key": "bic", "label": "BIC", "value": bic},
        {"key": "theta", "label": "θ (NB dispersion)", "value": fit["theta"]},
        {"key": "vuong_z", "label": "Vuong z (vs ordinary count model)", "value": vu["z"]},
        {"key": "vuong_p", "label": "p (Vuong)", "value": vu["p"], "format": "p"},
    ],
    "tables": [
        {"key": "count", "title": "Count model (log rate)",
         "columns": coef_cols + [{"key": "irr", "label": "IRR", "type": "number"}, {"key": "low", "label": "Lower", "type": "number"}, {"key": "high", "label": "Upper", "type": "number"}],
         "rows": count_rows},
        {"key": "zero", "title": zero_title, "columns": coef_cols + [{"key": "or", "label": "Odds ratio", "type": "number"}], "rows": zero_rows},
    ],
    "assumptions": assumptions,
    "warnings": warnings,
    "notes": ["Hurdle models: zero-model coefficients describe P(count > 0)." if model.startswith("hurdle") else "Zero-inflated models: zero-model coefficients describe the probability of an excess (structural) zero.",
              "Vuong's test of non-nested models is controversial for zero inflation (Wilson 2015); compare AIC too."],
    "charts": [cs.chart(
        "irr", "forest", "Incidence-rate ratios (count model)",
        {"label": cs.col("term", [r["term"] for r in eff]), "estimate": cs.col("IRR", [r["irr"] for r in eff]),
         "low": cs.col("low", [r["low"] for r in eff]), "high": cs.col("high", [r["high"] for r in eff])},
    )] if eff else [],
    "values": values,
})

The card has two tables. Count model rows describe students who aren't always-zero. Zero model rows are the log-odds of an excess (structural) zero.

The model expects 286 zeros against 275 observed. Vuong's test is a guide here, not a verdict: it has known problems when one model sits at the boundary of the other.

05

Hurdle models: one source of zeros

Read

A hurdle modelHurdle modelOne logistic model for crossing zero, and a zero-truncated count model for the positive counts. tells a different story. One logistic equation decides whether a row crosses zero. A zero-truncated count model describes how far it goes once it has. Every zero comes from the first equation.

Zero inflation suits zeros from people who could have had a count and didn't. A hurdle suits a zero that's a decision: buying nothing, or never seeing a doctor.

A hurdle model reproduces the observed zeros by design. Here it expects 275 of them, so the zero count can't tell you whether it fits.

06

Watch the sign

Predict

Predict first

Students with a more productive mentor are less likely to have no articles. A ZIP's zero part models being an always-zero case. A hurdle's zero part models crossing zero. What sign should the mentor coefficient take in each?

Same sign in bothOpposite signsNo way to know
Reveal

Opposite signs: negative in the ZIP, positive in the hurdle. Check both cards below. Before you read a zero part, check which event it models.

Zero-inflated PoissonRecorded · Python and R agreeRecorded 2026-11-17 · 43 values compared · largest relative difference 4.3e-10
R

Zero-inflated Poisson (n = 915): log-likelihood -1605.73, AIC 3227.5; 272.6 zeros expected vs 275 observed; Vuong z = 4.11, p < .001.

Log-likelihood
−1605.73
AIC
3227.47
BIC
3266.02
θ (NB dispersion)
—
Vuong z (vs ordinary count model)
4.112
p (Vuong)
< .001

Plots

Incidence-rate ratios (count model)How large are several estimates, how precise, and which exclude the null?
View data
IRRhightermlow
0.80370.9019gender[Women]0.7163
1.1431.301married[Married]1.004
0.84960.9250kids under 60.7804
0.99351.051prestige0.9395
1.0181.023mentor1.014

Assumptions

  • Excess zeros — 275 zeros observed, 272.6 expected by the two-part model; Vuong z = 4.11 against the ordinary count model.
  • Converged fit — The likelihood maximization converged.

Count model (log rate)

TermEstimateSEzpIRRLowerUpper
(Intercept)0.63020.11315.5722.521e-81.8781.5052.344
gender[Women]−0.21850.0588−3.7160.00020.80370.71630.9019
married[Married]0.13340.06622.0160.04381.1431.0041.301
kids under 6−0.16300.0434−3.7570.00020.84960.78040.9250
prestige−0.00650.0285−0.22840.81930.99350.93951.051
mentor0.01830.00238.0915.918e-161.0181.0141.023

Zero model: log-odds of an excess (structural) zero

TermEstimateSEzpOdds ratio
(Intercept)−0.68370.2053−3.3310.00090.5047
mentor−0.13030.0402−3.2400.00120.8779
  • Zero-inflated models: zero-model coefficients describe the probability of an excess (structural) zero.
  • Vuong's test of non-nested models is controversial for zero inflation (Wilson 2015); compare AIC too.
The exact R script · R R version 4.5.1 (2025-06-13)
# Zero-inflated and hurdle count models
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method regression.zero_inflated 1.0.1 · spec f945ef3f7e3f03e0
# Dataset: s4_bio (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.

# %% Setup
suppressPackageStartupMessages(library(pscl))
library(codesplashr) # cs_sel_names_from (coefficient names shared with Python), cs_glm_nb (MASS::glm.nb), cs_cnt_vuong

# %% Data
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/s4_bio.parquet", col_select = c("articles", "gender", "married", "kids under 6", "prestige", "mentor")))
n_input <- nrow(df)
df[["gender"]] <- factor(df[["gender"]], levels = c("Men", "Women"))  # stored level order
df[["married"]] <- factor(df[["married"]], levels = c("Single", "Married"))  # stored level order
df <- df[stats::complete.cases(df[c("articles", "gender", "married", "kids under 6", "prestige", "mentor")]), , 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("articles", "gender", "married", "kids under 6", "prestige", "mentor"))  # infinite values stop the run (registry/errors.yaml)

# %% Data and formulas
yname <- "articles"
predictors <- c("gender", "married", "kids under 6", "prestige", "mentor")
zero_model <- "chosen"
zero_terms <- switch(zero_model, same = predictors, intercept = character(0), chosen = c("mentor"))
if (zero_model == "chosen" && !length(zero_terms)) stop("Choose the zero-model predictors (or pick 'Same predictors' / 'Intercept only')")
y <- as.numeric(df[[yname]])
if (any(y < 0) || any(y != round(y))) stop(sprintf("%s must hold whole-number counts ≥ 0", yname))
model <- "zip"
# Degenerate input stops with a catalog error; Python runs the same checks in the same order.
# More rows than parameters: both parts' coefficients, plus theta for the negative binomial.
n_params <- length(cs_design_labels(df, predictors)) + length(cs_design_labels(df, zero_terms)) + (if (model %in% c("zinb", "hurdle_negbin")) 1 else 0)
cs_check_rows(nrow(df), n_params + 1, "A zero-inflated or hurdle model")
for (col in c(yname, union(predictors, zero_terms))) cs_check_not_constant(df[[col]], col)  # one value (or one level with data) is no variation
if (!any(y == 0)) cs_error("CS_E_UNDEFINED", what = "A zero-inflated or hurdle model", reason = sprintf("%s has no zeros", yname))
df$.y <- y
rhs <- function(terms) if (length(terms)) paste(sprintf("`%s`", terms), collapse = " + ") else "1"
f <- stats::as.formula(paste(".y ~", rhs(predictors), "|", rhs(zero_terms)))
n <- nrow(df)

# %% Two-part model (pscl)
dist <- if (model %in% c("zip", "hurdle_poisson")) "poisson" else "negbin"
fit <- if (startsWith(model, "hurdle")) {
  hurdle(f, data = df, dist = dist, zero.dist = "binomial", link = "logit", control = hurdle.control(reltol = 1e-15, maxit = 10000))
} else {
  zeroinfl(f, data = df, dist = dist, link = "logit", control = zeroinfl.control(reltol = 1e-15, maxit = 10000))
}
conf <- 0.95
zc <- stats::qnorm(1 - (1 - conf) / 2)
xnames <- cs_sel_names_from(stats::model.matrix(fit, model = "count"), attr(fit$terms$count, "term.labels"), fit$levels)
znames <- cs_sel_names_from(stats::model.matrix(fit, model = "zero"), attr(fit$terms$zero, "term.labels"), fit$levels)
xm <- stats::model.matrix(fit, model = "count")
zm <- stats::model.matrix(fit, model = "zero")
# pscl's BFGS stops early on flat likelihoods and summary(fit) inverts optim's coarse Hessian: polish
# with Newton steps on the shared log-likelihood (as the Python engine does) and take SEs from the
# observed information.
nbin <- dist == "negbin"
pol <- cs_cnt_zi_polish(c(fit$coefficients$count, fit$coefficients$zero, if (nbin) log(fit$theta)), y, xm, zm, model)
kx <- ncol(xm)
kz <- ncol(zm)
cb <- unname(pol$params[seq_len(kx)])
zb <- unname(pol$params[kx + seq_len(kz)])
cse <- pol$se[seq_len(kx)]
zse <- pol$se[kx + seq_len(kz)]
theta <- if (nbin) exp(pol$params[kx + kz + 1]) else NaN
ll_obs <- cs_cnt_zi_loglik_obs(pol$params, y, xm, zm, model)
p_zero <- cs_cnt_zi_p_zero(pol$params, xm, zm, model)
loglik <- sum(ll_obs)
k <- length(pol$params)
aic <- -2 * loglik + 2 * k
bic <- -2 * loglik + log(n) * k

# %% Ordinary count model and Vuong's test
fstd <- stats::as.formula(paste(".y ~", rhs(predictors)))
if (dist == "negbin") {
  nb <- cs_glm_nb(fstd, df, epsilon = 1e-12)  # MASS::glm.nb
  ll0 <- stats::dnbinom(y, size = nb$theta, mu = stats::fitted(nb$fit), log = TRUE)
} else {
  std <- stats::glm(fstd, family = stats::poisson(), data = df, control = stats::glm.control(epsilon = 1e-14, maxit = 100))
  ll0 <- stats::dpois(y, stats::fitted(std), log = TRUE)
}
vu <- cs_cnt_vuong(ll_obs, ll0)
zeros_obs <- sum(y == 0)
zeros_exp <- sum(p_zero)
converged <- isTRUE(fit$converged)

# %% Assumptions
assumptions <- list(
  list(key = "excess_zeros", label = "Excess zeros", status = "info",
       detail = sprintf("%d zeros observed, %.1f expected by the two-part model; Vuong z = %.2f against the ordinary count model.", zeros_obs, zeros_exp, vu$z)),
  list(key = "convergence", label = "Converged fit", status = if (converged) "pass" else "warn",
       detail = if (converged) "The likelihood maximization converged." else "The optimizer did not report convergence; check the estimates.")
)

# %% Result
labels <- c(zip = "Zero-inflated Poisson", zinb = "Zero-inflated negative binomial", hurdle_poisson = "Hurdle Poisson", hurdle_negbin = "Hurdle negative binomial")
values <- list(n = n, model = model, zero_model = zero_model, loglik = loglik, aic = aic, bic = bic, n_params = k,
               theta = theta, zeros_observed = zeros_obs, zeros_expected = zeros_exp, vuong_z = vu$z, vuong_p = vu$p, converged = converged)
count_rows <- list()
for (j in seq_along(xnames)) {
  pz <- 2 * stats::pnorm(-abs(cb[j] / cse[j]))
  values[[sprintf("count_coef[%s]", xnames[j])]] <- cb[j]
  values[[sprintf("count_se[%s]", xnames[j])]] <- cse[j]
  values[[sprintf("count_p[%s]", xnames[j])]] <- pz
  values[[sprintf("irr[%s]", xnames[j])]] <- exp(cb[j])
  count_rows[[j]] <- list(term = xnames[j], b = cb[j], se = cse[j], z = cb[j] / cse[j], p = pz, irr = exp(cb[j]),
                          low = exp(cb[j] - zc * cse[j]), high = exp(cb[j] + zc * cse[j]))
}
zero_rows <- list()
for (j in seq_along(znames)) {
  pz <- 2 * stats::pnorm(-abs(zb[j] / zse[j]))
  values[[sprintf("zero_coef[%s]", znames[j])]] <- zb[j]
  values[[sprintf("zero_se[%s]", znames[j])]] <- zse[j]
  values[[sprintf("zero_p[%s]", znames[j])]] <- pz
  zero_rows[[j]] <- list(term = znames[j], b = zb[j], se = zse[j], z = zb[j] / zse[j], p = pz, or = exp(zb[j]))
}
zero_title <- if (startsWith(model, "hurdle")) "Zero model: log-odds of crossing the hurdle (y > 0)" else "Zero model: log-odds of an excess (structural) zero"
coef_cols <- list(list(key = "term", label = "Term", type = "string"), list(key = "b", label = "Estimate", type = "number"),
                  list(key = "se", label = "SE", type = "number"), list(key = "z", label = "z", type = "number"),
                  list(key = "p", label = "p", type = "number", format = "p"))
eff <- Filter(function(r) r$term != "(Intercept)", count_rows)
cs_publish(list(
  method = "regression.zero_inflated",
  methodVersion = "1.0.1",
  title = labels[[model]],
  engine = cs_engine_info("pscl", "MASS", "nanoparquet"),
  n = n,
  summary = sprintf("%s (n = %d): log-likelihood %.2f, AIC %.1f; %.1f zeros expected vs %d observed; Vuong z = %.2f, %s.",
                    labels[[model]], n, loglik, aic, zeros_exp, zeros_obs, vu$z, cs_fmt_p(vu$p)),
  statistics = list(
    list(key = "loglik", label = "Log-likelihood", value = loglik),
    list(key = "aic", label = "AIC", value = aic),
    list(key = "bic", label = "BIC", value = bic),
    list(key = "theta", label = "θ (NB dispersion)", value = theta),
    list(key = "vuong_z", label = "Vuong z (vs ordinary count model)", value = vu$z),
    list(key = "vuong_p", label = "p (Vuong)", value = vu$p, format = "p")
  ),
  tables = list(
    list(key = "count", title = "Count model (log rate)",
         columns = c(coef_cols, list(list(key = "irr", label = "IRR", type = "number"), list(key = "low", label = "Lower", type = "number"),
                                     list(key = "high", label = "Upper", type = "number"))),
         rows = count_rows),
    list(key = "zero", title = zero_title, columns = c(coef_cols, list(list(key = "or", label = "Odds ratio", type = "number"))), rows = zero_rows)
  ),
  assumptions = assumptions,
  warnings = warnings,
  notes = list(if (startsWith(model, "hurdle")) "Hurdle models: zero-model coefficients describe P(count > 0)." else "Zero-inflated models: zero-model coefficients describe the probability of an excess (structural) zero.",
               "Vuong's test of non-nested models is controversial for zero inflation (Wilson 2015); compare AIC too."),
  charts = if (length(eff)) list(cs_chart(
    "irr", "forest", "Incidence-rate ratios (count model)",
    list(label = cs_col("term", vapply(eff, function(r) r$term, "")), estimate = cs_col("IRR", vapply(eff, function(r) r$irr, 0)),
         low = cs_col("low", vapply(eff, function(r) r$low, 0)), high = cs_col("high", vapply(eff, function(r) r$high, 0)))
  )) else list(),
  values = values
))
Python

Zero-inflated Poisson (n = 915): log-likelihood -1605.73, AIC 3227.5; 272.6 zeros expected vs 275 observed; Vuong z = 4.11, p < .001.

Log-likelihood
−1605.73
AIC
3227.47
BIC
3266.02
θ (NB dispersion)
—
Vuong z (vs ordinary count model)
4.112
p (Vuong)
< .001

To keep this page light, the plots are shown once, under the R tab.

Assumptions

  • Excess zeros — 275 zeros observed, 272.6 expected by the two-part model; Vuong z = 4.11 against the ordinary count model.
  • Converged fit — The likelihood maximization converged.

Count model (log rate)

TermEstimateSEzpIRRLowerUpper
(Intercept)0.63020.11315.5722.521e-81.8781.5052.344
gender[Women]−0.21850.0588−3.7160.00020.80370.71630.9019
married[Married]0.13340.06622.0160.04381.1431.0041.301
kids under 6−0.16300.0434−3.7570.00020.84960.78040.9250
prestige−0.00650.0285−0.22840.81930.99350.93951.051
mentor0.01830.00238.0915.918e-161.0181.0141.023

Zero model: log-odds of an excess (structural) zero

TermEstimateSEzpOdds ratio
(Intercept)−0.68370.2053−3.3310.00090.5047
mentor−0.13030.0402−3.2400.00120.8779
  • Zero-inflated models: zero-model coefficients describe the probability of an excess (structural) zero.
  • Vuong's test of non-nested models is controversial for zero inflation (Wilson 2015); compare AIC too.
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Zero-inflated and hurdle count models
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method regression.zero_inflated 1.0.1 · spec f945ef3f7e3f03e0
# Dataset: s4_bio (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.

# %% Setup
import math

import numpy as np
import pandas as pd
from scipy import stats
from scipy.special import gammaln

import codesplash as cs
from codesplash.errors import check_not_constant
from codesplash.stats import counts as csc  # statsmodels ZI / hurdle fits with pscl's starts; Vuong (twins of codesplashr)
from codesplash.stats import glm as csglm  # NB2 as MASS::glm.nb
from codesplash.stats import selection as sel  # design columns named like the R twin

# %% Data
df = pd.read_parquet("tests/parity/fixtures/s4_bio.parquet", columns=["articles", "gender", "married", "kids under 6", "prestige", "mentor"])
n_input = len(df)
df["gender"] = pd.Categorical(df["gender"], categories=["Men", "Women"])  # stored level order
df["married"] = pd.Categorical(df["married"], categories=["Single", "Married"])  # stored level order
df = df.dropna(subset=["articles", "gender", "married", "kids under 6", "prestige", "mentor"])  # listwise deletion over the analysis columns
df["gender"] = df["gender"].cat.remove_unused_categories()
df["married"] = df["married"].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, ["articles", "gender", "married", "kids under 6", "prestige", "mentor"])  # infinite values stop the run (registry/errors.yaml)

# %% Data and designs
yname = "articles"
predictors = ["gender", "married", "kids under 6", "prestige", "mentor"]
zero_model = "chosen"
zero_terms = {"same": predictors, "intercept": [], "chosen": ["mentor"]}[zero_model]
if zero_model == "chosen" and not zero_terms:
    raise ValueError("Choose the zero-model predictors (or pick 'Same predictors' / 'Intercept only')")
kinds = {"articles":"numeric","gender":"categorical","kids under 6":"numeric","married":"categorical","mentor":"numeric","prestige":"numeric"}
y = df[yname].to_numpy(dtype=float)
if np.any(y < 0) or np.any(y != np.round(y)):
    raise ValueError(f"{yname} must hold whole-number counts ≥ 0")
levels = {p: ([str(v) for v in df[p].cat.categories] if kinds[p] in ("categorical", "boolean") else None) for p in set(predictors) | set(zero_terms)}
x, xnames, _ = sel.design(df, predictors, levels)
z, znames, _ = sel.design(df, zero_terms, levels)
n = len(y)
model = "zip"
# Degenerate input stops with a catalog error; R runs the same checks in the same order.
# More rows than parameters: both parts' coefficients, plus θ for the negative binomial.
n_params = x.shape[1] + z.shape[1] + (1 if model in ("zinb", "hurdle_negbin") else 0)
cs.check_rows(n, n_params + 1, "A zero-inflated or hurdle model")
for col in [yname] + list(dict.fromkeys(predictors + zero_terms)):
    check_not_constant(df[col], col)  # one value (or one level with data) is no variation
if not np.any(y == 0):
    cs.cs_error("CS_E_UNDEFINED", what="A zero-inflated or hurdle model", reason=f"{yname} has no zeros")

# %% Two-part model (statsmodels; pscl::zeroinfl / hurdle in R)
fit = csc.zero_count_fit(y, x, z, model)
nb = model in ("zinb", "hurdle_negbin")
# Newton polishing on the shared log-likelihood (the R engine polishes pscl's fit the same way),
# then SEs from the observed information.
start = np.r_[fit["count"], fit["zero"], [math.log(fit["theta"])] if nb else []]
params, se_all = csc.zi_polish(start, y, x, z, model)
kx, kz = x.shape[1], z.shape[1]
fit.update({"count": params[:kx], "count_se": se_all[:kx], "zero": params[kx : kx + kz], "zero_se": se_all[kx : kx + kz],
            "theta": math.exp(params[-1]) if nb else math.nan, "ll_obs": csc.zi_loglik_obs(params, y, x, z, model),
            "p_zero": csc.zi_p_zero(params, x, z, model)})
conf = 0.95
zc = stats.norm.ppf(1 - (1 - conf) / 2)
loglik = float(fit["ll_obs"].sum())
k = fit["k"]
aic, bic = -2 * loglik + 2 * k, -2 * loglik + math.log(n) * k

# %% Ordinary count model and Vuong's test
if nb:
    std, theta0, _ = csglm.nb_fit(y, x, tol=1e-12)  # MASS::glm.nb
    mu0 = np.asarray(std.mu)
    ll0 = gammaln(y + theta0) - gammaln(theta0) - gammaln(y + 1) + theta0 * np.log(theta0 / (theta0 + mu0)) + y * np.log(mu0 / (theta0 + mu0))
else:
    std = sel.fit_model(x, y, "poisson")  # glm(family = poisson), deviance criterion 1e-14
    mu0 = std["mu"]
    ll0 = y * np.log(mu0) - mu0 - gammaln(y + 1)
vu = csc.vuong(fit["ll_obs"], ll0)
zeros_obs = int(np.sum(y == 0))
zeros_exp = float(np.sum(fit["p_zero"]))

# %% Assumptions
assumptions = [
    {"key": "excess_zeros", "label": "Excess zeros", "status": "info",
     "detail": f"{zeros_obs} zeros observed, {zeros_exp:.1f} expected by the two-part model; Vuong z = {vu['z']:.2f} against the ordinary count model."},
    {"key": "convergence", "label": "Converged fit", "status": "pass" if fit["converged"] else "warn",
     "detail": "The likelihood maximization converged." if fit["converged"] else "The optimizer did not report convergence; check the estimates."},
]

# %% Result
labels = {"zip": "Zero-inflated Poisson", "zinb": "Zero-inflated negative binomial", "hurdle_poisson": "Hurdle Poisson", "hurdle_negbin": "Hurdle negative binomial"}
values = {"n": n, "model": model, "zero_model": zero_model, "loglik": loglik, "aic": aic, "bic": bic, "n_params": k,
          "theta": fit["theta"], "zeros_observed": zeros_obs, "zeros_expected": zeros_exp, "vuong_z": vu["z"], "vuong_p": vu["p"],
          "converged": fit["converged"]}
count_rows, zero_rows = [], []
for nm, b, s in zip(xnames, fit["count"], fit["count_se"]):
    pz = float(2 * stats.norm.sf(abs(b / s)))
    values.update({f"count_coef[{nm}]": float(b), f"count_se[{nm}]": float(s), f"count_p[{nm}]": pz, f"irr[{nm}]": math.exp(b)})
    count_rows.append({"term": nm, "b": float(b), "se": float(s), "z": float(b / s), "p": pz, "irr": math.exp(b),
                       "low": math.exp(b - zc * s), "high": math.exp(b + zc * s)})
for nm, b, s in zip(znames, fit["zero"], fit["zero_se"]):
    pz = float(2 * stats.norm.sf(abs(b / s)))
    values.update({f"zero_coef[{nm}]": float(b), f"zero_se[{nm}]": float(s), f"zero_p[{nm}]": pz})
    zero_rows.append({"term": nm, "b": float(b), "se": float(s), "z": float(b / s), "p": pz, "or": math.exp(b)})
zero_title = "Zero model: log-odds of crossing the hurdle (y > 0)" if model.startswith("hurdle") else "Zero model: log-odds of an excess (structural) zero"
coef_cols = [{"key": "term", "label": "Term", "type": "string"}, {"key": "b", "label": "Estimate", "type": "number"},
             {"key": "se", "label": "SE", "type": "number"}, {"key": "z", "label": "z", "type": "number"},
             {"key": "p", "label": "p", "type": "number", "format": "p"}]
eff = [r for r in count_rows if r["term"] != "(Intercept)"]
cs.publish({
    "method": "regression.zero_inflated",
    "methodVersion": "1.0.1",
    "title": labels[model],
    "engine": cs.engine_info("pandas", "numpy", "scipy", "statsmodels"),
    "n": n,
    "summary": f"{labels[model]} (n = {n}): log-likelihood {loglik:.2f}, AIC {aic:.1f}; {zeros_exp:.1f} zeros expected vs {zeros_obs} observed; Vuong z = {vu['z']:.2f}, {cs.fmt_p(vu['p'])}.",
    "statistics": [
        {"key": "loglik", "label": "Log-likelihood", "value": loglik},
        {"key": "aic", "label": "AIC", "value": aic},
        {"key": "bic", "label": "BIC", "value": bic},
        {"key": "theta", "label": "θ (NB dispersion)", "value": fit["theta"]},
        {"key": "vuong_z", "label": "Vuong z (vs ordinary count model)", "value": vu["z"]},
        {"key": "vuong_p", "label": "p (Vuong)", "value": vu["p"], "format": "p"},
    ],
    "tables": [
        {"key": "count", "title": "Count model (log rate)",
         "columns": coef_cols + [{"key": "irr", "label": "IRR", "type": "number"}, {"key": "low", "label": "Lower", "type": "number"}, {"key": "high", "label": "Upper", "type": "number"}],
         "rows": count_rows},
        {"key": "zero", "title": zero_title, "columns": coef_cols + [{"key": "or", "label": "Odds ratio", "type": "number"}], "rows": zero_rows},
    ],
    "assumptions": assumptions,
    "warnings": warnings,
    "notes": ["Hurdle models: zero-model coefficients describe P(count > 0)." if model.startswith("hurdle") else "Zero-inflated models: zero-model coefficients describe the probability of an excess (structural) zero.",
              "Vuong's test of non-nested models is controversial for zero inflation (Wilson 2015); compare AIC too."],
    "charts": [cs.chart(
        "irr", "forest", "Incidence-rate ratios (count model)",
        {"label": cs.col("term", [r["term"] for r in eff]), "estimate": cs.col("IRR", [r["irr"] for r in eff]),
         "low": cs.col("low", [r["low"] for r in eff]), "high": cs.col("high", [r["high"] for r in eff])},
    )] if eff else [],
    "values": values,
})
Hurdle PoissonRecorded · Python and R agreeRecorded 2026-11-17 · 41 values compared · largest relative difference 3.8e-6
R

Hurdle Poisson (n = 915): log-likelihood -1607.99, AIC 3232.0; 275.0 zeros expected vs 275 observed; Vuong z = 4.20, p < .001.

Log-likelihood
−1607.99
AIC
3231.97
BIC
3270.52
θ (NB dispersion)
—
Vuong z (vs ordinary count model)
4.200
p (Vuong)
< .001

Plots

Incidence-rate ratios (count model)How large are several estimates, how precise, and which exclude the null?
View data
IRRhightermlow
0.78750.8941gender[Women]0.6936
0.89160.9725kids under 60.8175
1.0191.023mentor1.014

Assumptions

  • Excess zeros — 275 zeros observed, 275.0 expected by the two-part model; Vuong z = 4.20 against the ordinary count model.
  • Converged fit — The likelihood maximization converged.

Count model (log rate)

TermEstimateSEzpIRRLowerUpper
(Intercept)0.69160.054712.6431.223e-361.9971.7942.223
gender[Women]−0.23890.0648−3.6890.00020.78750.69360.8941
kids under 6−0.11470.0443−2.5910.00960.89160.81750.9725
mentor0.01840.00228.2731.308e-161.0191.0141.023

Zero model: log-odds of crossing the hurdle (y > 0)

TermEstimateSEzpOdds ratio
(Intercept)0.49560.15203.2590.00111.641
gender[Women]−0.29110.1572−1.8520.06410.7474
kids under 6−0.20080.1001−2.0060.04490.8181
mentor0.08000.01256.3921.636e-101.083
  • Hurdle models: zero-model coefficients describe P(count > 0).
  • Vuong's test of non-nested models is controversial for zero inflation (Wilson 2015); compare AIC too.
The exact R script · R R version 4.5.1 (2025-06-13)
# Zero-inflated and hurdle count models
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method regression.zero_inflated 1.0.1 · spec efc77e8be886b2ee
# Dataset: s4_bio (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.

# %% Setup
suppressPackageStartupMessages(library(pscl))
library(codesplashr) # cs_sel_names_from (coefficient names shared with Python), cs_glm_nb (MASS::glm.nb), cs_cnt_vuong

# %% Data
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/s4_bio.parquet", col_select = c("articles", "gender", "kids under 6", "mentor")))
n_input <- nrow(df)
df[["gender"]] <- factor(df[["gender"]], levels = c("Men", "Women"))  # stored level order
df <- df[stats::complete.cases(df[c("articles", "gender", "kids under 6", "mentor")]), , 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("articles", "gender", "kids under 6", "mentor"))  # infinite values stop the run (registry/errors.yaml)

# %% Data and formulas
yname <- "articles"
predictors <- c("gender", "kids under 6", "mentor")
zero_model <- "same"
zero_terms <- switch(zero_model, same = predictors, intercept = character(0), chosen = c())
if (zero_model == "chosen" && !length(zero_terms)) stop("Choose the zero-model predictors (or pick 'Same predictors' / 'Intercept only')")
y <- as.numeric(df[[yname]])
if (any(y < 0) || any(y != round(y))) stop(sprintf("%s must hold whole-number counts ≥ 0", yname))
model <- "hurdle_poisson"
# Degenerate input stops with a catalog error; Python runs the same checks in the same order.
# More rows than parameters: both parts' coefficients, plus theta for the negative binomial.
n_params <- length(cs_design_labels(df, predictors)) + length(cs_design_labels(df, zero_terms)) + (if (model %in% c("zinb", "hurdle_negbin")) 1 else 0)
cs_check_rows(nrow(df), n_params + 1, "A zero-inflated or hurdle model")
for (col in c(yname, union(predictors, zero_terms))) cs_check_not_constant(df[[col]], col)  # one value (or one level with data) is no variation
if (!any(y == 0)) cs_error("CS_E_UNDEFINED", what = "A zero-inflated or hurdle model", reason = sprintf("%s has no zeros", yname))
df$.y <- y
rhs <- function(terms) if (length(terms)) paste(sprintf("`%s`", terms), collapse = " + ") else "1"
f <- stats::as.formula(paste(".y ~", rhs(predictors), "|", rhs(zero_terms)))
n <- nrow(df)

# %% Two-part model (pscl)
dist <- if (model %in% c("zip", "hurdle_poisson")) "poisson" else "negbin"
fit <- if (startsWith(model, "hurdle")) {
  hurdle(f, data = df, dist = dist, zero.dist = "binomial", link = "logit", control = hurdle.control(reltol = 1e-15, maxit = 10000))
} else {
  zeroinfl(f, data = df, dist = dist, link = "logit", control = zeroinfl.control(reltol = 1e-15, maxit = 10000))
}
conf <- 0.95
zc <- stats::qnorm(1 - (1 - conf) / 2)
xnames <- cs_sel_names_from(stats::model.matrix(fit, model = "count"), attr(fit$terms$count, "term.labels"), fit$levels)
znames <- cs_sel_names_from(stats::model.matrix(fit, model = "zero"), attr(fit$terms$zero, "term.labels"), fit$levels)
xm <- stats::model.matrix(fit, model = "count")
zm <- stats::model.matrix(fit, model = "zero")
# pscl's BFGS stops early on flat likelihoods and summary(fit) inverts optim's coarse Hessian: polish
# with Newton steps on the shared log-likelihood (as the Python engine does) and take SEs from the
# observed information.
nbin <- dist == "negbin"
pol <- cs_cnt_zi_polish(c(fit$coefficients$count, fit$coefficients$zero, if (nbin) log(fit$theta)), y, xm, zm, model)
kx <- ncol(xm)
kz <- ncol(zm)
cb <- unname(pol$params[seq_len(kx)])
zb <- unname(pol$params[kx + seq_len(kz)])
cse <- pol$se[seq_len(kx)]
zse <- pol$se[kx + seq_len(kz)]
theta <- if (nbin) exp(pol$params[kx + kz + 1]) else NaN
ll_obs <- cs_cnt_zi_loglik_obs(pol$params, y, xm, zm, model)
p_zero <- cs_cnt_zi_p_zero(pol$params, xm, zm, model)
loglik <- sum(ll_obs)
k <- length(pol$params)
aic <- -2 * loglik + 2 * k
bic <- -2 * loglik + log(n) * k

# %% Ordinary count model and Vuong's test
fstd <- stats::as.formula(paste(".y ~", rhs(predictors)))
if (dist == "negbin") {
  nb <- cs_glm_nb(fstd, df, epsilon = 1e-12)  # MASS::glm.nb
  ll0 <- stats::dnbinom(y, size = nb$theta, mu = stats::fitted(nb$fit), log = TRUE)
} else {
  std <- stats::glm(fstd, family = stats::poisson(), data = df, control = stats::glm.control(epsilon = 1e-14, maxit = 100))
  ll0 <- stats::dpois(y, stats::fitted(std), log = TRUE)
}
vu <- cs_cnt_vuong(ll_obs, ll0)
zeros_obs <- sum(y == 0)
zeros_exp <- sum(p_zero)
converged <- isTRUE(fit$converged)

# %% Assumptions
assumptions <- list(
  list(key = "excess_zeros", label = "Excess zeros", status = "info",
       detail = sprintf("%d zeros observed, %.1f expected by the two-part model; Vuong z = %.2f against the ordinary count model.", zeros_obs, zeros_exp, vu$z)),
  list(key = "convergence", label = "Converged fit", status = if (converged) "pass" else "warn",
       detail = if (converged) "The likelihood maximization converged." else "The optimizer did not report convergence; check the estimates.")
)

# %% Result
labels <- c(zip = "Zero-inflated Poisson", zinb = "Zero-inflated negative binomial", hurdle_poisson = "Hurdle Poisson", hurdle_negbin = "Hurdle negative binomial")
values <- list(n = n, model = model, zero_model = zero_model, loglik = loglik, aic = aic, bic = bic, n_params = k,
               theta = theta, zeros_observed = zeros_obs, zeros_expected = zeros_exp, vuong_z = vu$z, vuong_p = vu$p, converged = converged)
count_rows <- list()
for (j in seq_along(xnames)) {
  pz <- 2 * stats::pnorm(-abs(cb[j] / cse[j]))
  values[[sprintf("count_coef[%s]", xnames[j])]] <- cb[j]
  values[[sprintf("count_se[%s]", xnames[j])]] <- cse[j]
  values[[sprintf("count_p[%s]", xnames[j])]] <- pz
  values[[sprintf("irr[%s]", xnames[j])]] <- exp(cb[j])
  count_rows[[j]] <- list(term = xnames[j], b = cb[j], se = cse[j], z = cb[j] / cse[j], p = pz, irr = exp(cb[j]),
                          low = exp(cb[j] - zc * cse[j]), high = exp(cb[j] + zc * cse[j]))
}
zero_rows <- list()
for (j in seq_along(znames)) {
  pz <- 2 * stats::pnorm(-abs(zb[j] / zse[j]))
  values[[sprintf("zero_coef[%s]", znames[j])]] <- zb[j]
  values[[sprintf("zero_se[%s]", znames[j])]] <- zse[j]
  values[[sprintf("zero_p[%s]", znames[j])]] <- pz
  zero_rows[[j]] <- list(term = znames[j], b = zb[j], se = zse[j], z = zb[j] / zse[j], p = pz, or = exp(zb[j]))
}
zero_title <- if (startsWith(model, "hurdle")) "Zero model: log-odds of crossing the hurdle (y > 0)" else "Zero model: log-odds of an excess (structural) zero"
coef_cols <- list(list(key = "term", label = "Term", type = "string"), list(key = "b", label = "Estimate", type = "number"),
                  list(key = "se", label = "SE", type = "number"), list(key = "z", label = "z", type = "number"),
                  list(key = "p", label = "p", type = "number", format = "p"))
eff <- Filter(function(r) r$term != "(Intercept)", count_rows)
cs_publish(list(
  method = "regression.zero_inflated",
  methodVersion = "1.0.1",
  title = labels[[model]],
  engine = cs_engine_info("pscl", "MASS", "nanoparquet"),
  n = n,
  summary = sprintf("%s (n = %d): log-likelihood %.2f, AIC %.1f; %.1f zeros expected vs %d observed; Vuong z = %.2f, %s.",
                    labels[[model]], n, loglik, aic, zeros_exp, zeros_obs, vu$z, cs_fmt_p(vu$p)),
  statistics = list(
    list(key = "loglik", label = "Log-likelihood", value = loglik),
    list(key = "aic", label = "AIC", value = aic),
    list(key = "bic", label = "BIC", value = bic),
    list(key = "theta", label = "θ (NB dispersion)", value = theta),
    list(key = "vuong_z", label = "Vuong z (vs ordinary count model)", value = vu$z),
    list(key = "vuong_p", label = "p (Vuong)", value = vu$p, format = "p")
  ),
  tables = list(
    list(key = "count", title = "Count model (log rate)",
         columns = c(coef_cols, list(list(key = "irr", label = "IRR", type = "number"), list(key = "low", label = "Lower", type = "number"),
                                     list(key = "high", label = "Upper", type = "number"))),
         rows = count_rows),
    list(key = "zero", title = zero_title, columns = c(coef_cols, list(list(key = "or", label = "Odds ratio", type = "number"))), rows = zero_rows)
  ),
  assumptions = assumptions,
  warnings = warnings,
  notes = list(if (startsWith(model, "hurdle")) "Hurdle models: zero-model coefficients describe P(count > 0)." else "Zero-inflated models: zero-model coefficients describe the probability of an excess (structural) zero.",
               "Vuong's test of non-nested models is controversial for zero inflation (Wilson 2015); compare AIC too."),
  charts = if (length(eff)) list(cs_chart(
    "irr", "forest", "Incidence-rate ratios (count model)",
    list(label = cs_col("term", vapply(eff, function(r) r$term, "")), estimate = cs_col("IRR", vapply(eff, function(r) r$irr, 0)),
         low = cs_col("low", vapply(eff, function(r) r$low, 0)), high = cs_col("high", vapply(eff, function(r) r$high, 0)))
  )) else list(),
  values = values
))
Python

Hurdle Poisson (n = 915): log-likelihood -1607.99, AIC 3232.0; 275.0 zeros expected vs 275 observed; Vuong z = 4.20, p < .001.

Log-likelihood
−1607.99
AIC
3231.97
BIC
3270.52
θ (NB dispersion)
—
Vuong z (vs ordinary count model)
4.200
p (Vuong)
< .001

To keep this page light, the plots are shown once, under the R tab.

Assumptions

  • Excess zeros — 275 zeros observed, 275.0 expected by the two-part model; Vuong z = 4.20 against the ordinary count model.
  • Converged fit — The likelihood maximization converged.

Count model (log rate)

TermEstimateSEzpIRRLowerUpper
(Intercept)0.69160.054712.6431.223e-361.9971.7942.223
gender[Women]−0.23890.0648−3.6890.00020.78750.69360.8941
kids under 6−0.11470.0443−2.5910.00960.89160.81750.9725
mentor0.01840.00228.2731.308e-161.0191.0141.023

Zero model: log-odds of crossing the hurdle (y > 0)

TermEstimateSEzpOdds ratio
(Intercept)0.49560.15203.2590.00111.641
gender[Women]−0.29110.1572−1.8520.06410.7474
kids under 6−0.20080.1001−2.0060.04490.8181
mentor0.08000.01256.3921.636e-101.083
  • Hurdle models: zero-model coefficients describe P(count > 0).
  • Vuong's test of non-nested models is controversial for zero inflation (Wilson 2015); compare AIC too.
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Zero-inflated and hurdle count models
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method regression.zero_inflated 1.0.1 · spec efc77e8be886b2ee
# Dataset: s4_bio (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.

# %% Setup
import math

import numpy as np
import pandas as pd
from scipy import stats
from scipy.special import gammaln

import codesplash as cs
from codesplash.errors import check_not_constant
from codesplash.stats import counts as csc  # statsmodels ZI / hurdle fits with pscl's starts; Vuong (twins of codesplashr)
from codesplash.stats import glm as csglm  # NB2 as MASS::glm.nb
from codesplash.stats import selection as sel  # design columns named like the R twin

# %% Data
df = pd.read_parquet("tests/parity/fixtures/s4_bio.parquet", columns=["articles", "gender", "kids under 6", "mentor"])
n_input = len(df)
df["gender"] = pd.Categorical(df["gender"], categories=["Men", "Women"])  # stored level order
df = df.dropna(subset=["articles", "gender", "kids under 6", "mentor"])  # listwise deletion over the analysis columns
df["gender"] = df["gender"].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, ["articles", "gender", "kids under 6", "mentor"])  # infinite values stop the run (registry/errors.yaml)

# %% Data and designs
yname = "articles"
predictors = ["gender", "kids under 6", "mentor"]
zero_model = "same"
zero_terms = {"same": predictors, "intercept": [], "chosen": []}[zero_model]
if zero_model == "chosen" and not zero_terms:
    raise ValueError("Choose the zero-model predictors (or pick 'Same predictors' / 'Intercept only')")
kinds = {"articles":"numeric","gender":"categorical","kids under 6":"numeric","mentor":"numeric"}
y = df[yname].to_numpy(dtype=float)
if np.any(y < 0) or np.any(y != np.round(y)):
    raise ValueError(f"{yname} must hold whole-number counts ≥ 0")
levels = {p: ([str(v) for v in df[p].cat.categories] if kinds[p] in ("categorical", "boolean") else None) for p in set(predictors) | set(zero_terms)}
x, xnames, _ = sel.design(df, predictors, levels)
z, znames, _ = sel.design(df, zero_terms, levels)
n = len(y)
model = "hurdle_poisson"
# Degenerate input stops with a catalog error; R runs the same checks in the same order.
# More rows than parameters: both parts' coefficients, plus θ for the negative binomial.
n_params = x.shape[1] + z.shape[1] + (1 if model in ("zinb", "hurdle_negbin") else 0)
cs.check_rows(n, n_params + 1, "A zero-inflated or hurdle model")
for col in [yname] + list(dict.fromkeys(predictors + zero_terms)):
    check_not_constant(df[col], col)  # one value (or one level with data) is no variation
if not np.any(y == 0):
    cs.cs_error("CS_E_UNDEFINED", what="A zero-inflated or hurdle model", reason=f"{yname} has no zeros")

# %% Two-part model (statsmodels; pscl::zeroinfl / hurdle in R)
fit = csc.zero_count_fit(y, x, z, model)
nb = model in ("zinb", "hurdle_negbin")
# Newton polishing on the shared log-likelihood (the R engine polishes pscl's fit the same way),
# then SEs from the observed information.
start = np.r_[fit["count"], fit["zero"], [math.log(fit["theta"])] if nb else []]
params, se_all = csc.zi_polish(start, y, x, z, model)
kx, kz = x.shape[1], z.shape[1]
fit.update({"count": params[:kx], "count_se": se_all[:kx], "zero": params[kx : kx + kz], "zero_se": se_all[kx : kx + kz],
            "theta": math.exp(params[-1]) if nb else math.nan, "ll_obs": csc.zi_loglik_obs(params, y, x, z, model),
            "p_zero": csc.zi_p_zero(params, x, z, model)})
conf = 0.95
zc = stats.norm.ppf(1 - (1 - conf) / 2)
loglik = float(fit["ll_obs"].sum())
k = fit["k"]
aic, bic = -2 * loglik + 2 * k, -2 * loglik + math.log(n) * k

# %% Ordinary count model and Vuong's test
if nb:
    std, theta0, _ = csglm.nb_fit(y, x, tol=1e-12)  # MASS::glm.nb
    mu0 = np.asarray(std.mu)
    ll0 = gammaln(y + theta0) - gammaln(theta0) - gammaln(y + 1) + theta0 * np.log(theta0 / (theta0 + mu0)) + y * np.log(mu0 / (theta0 + mu0))
else:
    std = sel.fit_model(x, y, "poisson")  # glm(family = poisson), deviance criterion 1e-14
    mu0 = std["mu"]
    ll0 = y * np.log(mu0) - mu0 - gammaln(y + 1)
vu = csc.vuong(fit["ll_obs"], ll0)
zeros_obs = int(np.sum(y == 0))
zeros_exp = float(np.sum(fit["p_zero"]))

# %% Assumptions
assumptions = [
    {"key": "excess_zeros", "label": "Excess zeros", "status": "info",
     "detail": f"{zeros_obs} zeros observed, {zeros_exp:.1f} expected by the two-part model; Vuong z = {vu['z']:.2f} against the ordinary count model."},
    {"key": "convergence", "label": "Converged fit", "status": "pass" if fit["converged"] else "warn",
     "detail": "The likelihood maximization converged." if fit["converged"] else "The optimizer did not report convergence; check the estimates."},
]

# %% Result
labels = {"zip": "Zero-inflated Poisson", "zinb": "Zero-inflated negative binomial", "hurdle_poisson": "Hurdle Poisson", "hurdle_negbin": "Hurdle negative binomial"}
values = {"n": n, "model": model, "zero_model": zero_model, "loglik": loglik, "aic": aic, "bic": bic, "n_params": k,
          "theta": fit["theta"], "zeros_observed": zeros_obs, "zeros_expected": zeros_exp, "vuong_z": vu["z"], "vuong_p": vu["p"],
          "converged": fit["converged"]}
count_rows, zero_rows = [], []
for nm, b, s in zip(xnames, fit["count"], fit["count_se"]):
    pz = float(2 * stats.norm.sf(abs(b / s)))
    values.update({f"count_coef[{nm}]": float(b), f"count_se[{nm}]": float(s), f"count_p[{nm}]": pz, f"irr[{nm}]": math.exp(b)})
    count_rows.append({"term": nm, "b": float(b), "se": float(s), "z": float(b / s), "p": pz, "irr": math.exp(b),
                       "low": math.exp(b - zc * s), "high": math.exp(b + zc * s)})
for nm, b, s in zip(znames, fit["zero"], fit["zero_se"]):
    pz = float(2 * stats.norm.sf(abs(b / s)))
    values.update({f"zero_coef[{nm}]": float(b), f"zero_se[{nm}]": float(s), f"zero_p[{nm}]": pz})
    zero_rows.append({"term": nm, "b": float(b), "se": float(s), "z": float(b / s), "p": pz, "or": math.exp(b)})
zero_title = "Zero model: log-odds of crossing the hurdle (y > 0)" if model.startswith("hurdle") else "Zero model: log-odds of an excess (structural) zero"
coef_cols = [{"key": "term", "label": "Term", "type": "string"}, {"key": "b", "label": "Estimate", "type": "number"},
             {"key": "se", "label": "SE", "type": "number"}, {"key": "z", "label": "z", "type": "number"},
             {"key": "p", "label": "p", "type": "number", "format": "p"}]
eff = [r for r in count_rows if r["term"] != "(Intercept)"]
cs.publish({
    "method": "regression.zero_inflated",
    "methodVersion": "1.0.1",
    "title": labels[model],
    "engine": cs.engine_info("pandas", "numpy", "scipy", "statsmodels"),
    "n": n,
    "summary": f"{labels[model]} (n = {n}): log-likelihood {loglik:.2f}, AIC {aic:.1f}; {zeros_exp:.1f} zeros expected vs {zeros_obs} observed; Vuong z = {vu['z']:.2f}, {cs.fmt_p(vu['p'])}.",
    "statistics": [
        {"key": "loglik", "label": "Log-likelihood", "value": loglik},
        {"key": "aic", "label": "AIC", "value": aic},
        {"key": "bic", "label": "BIC", "value": bic},
        {"key": "theta", "label": "θ (NB dispersion)", "value": fit["theta"]},
        {"key": "vuong_z", "label": "Vuong z (vs ordinary count model)", "value": vu["z"]},
        {"key": "vuong_p", "label": "p (Vuong)", "value": vu["p"], "format": "p"},
    ],
    "tables": [
        {"key": "count", "title": "Count model (log rate)",
         "columns": coef_cols + [{"key": "irr", "label": "IRR", "type": "number"}, {"key": "low", "label": "Lower", "type": "number"}, {"key": "high", "label": "Upper", "type": "number"}],
         "rows": count_rows},
        {"key": "zero", "title": zero_title, "columns": coef_cols + [{"key": "or", "label": "Odds ratio", "type": "number"}], "rows": zero_rows},
    ],
    "assumptions": assumptions,
    "warnings": warnings,
    "notes": ["Hurdle models: zero-model coefficients describe P(count > 0)." if model.startswith("hurdle") else "Zero-inflated models: zero-model coefficients describe the probability of an excess (structural) zero.",
              "Vuong's test of non-nested models is controversial for zero inflation (Wilson 2015); compare AIC too."],
    "charts": [cs.chart(
        "irr", "forest", "Incidence-rate ratios (count model)",
        {"label": cs.col("term", [r["term"] for r in eff]), "estimate": cs.col("IRR", [r["irr"] for r in eff]),
         "low": cs.col("low", [r["low"] for r in eff]), "high": cs.col("high", [r["high"] for r in eff])},
    )] if eff else [],
    "values": values,
})
07

Zeros that are really limits

Read

A pile at zero isn't always about counts. Overtime hours are a measurement, and they pile up at zero because people who'd "work" fewer hours than none still show zero. That's censoringCensoringFollow-up ended before the event happened, so you only know the event time is later than observed. at a limit, and a Tobit modelTobit modelRegression for a numeric outcome observed only inside limits, assuming a normal latent outcome lies behind it. fits it: a normal latent outcome that you only see above the limit.

Censored regression (Tobit)Recorded · Python and R agreeRecorded 2026-11-17 · 60 values compared
R

χ²(4, N = 400) = 185.65, p < .001, σ = 4.24

LR χ²
185.65
p
< .001
σ
4.241
Censored
13.3%

Plots

Effects on the latent outcomeHow large are several estimates, how precise, and which exclude the null?
View data
BhighTermlow
0.83030.9908educ0.6698
0.23020.2808exper0.1796
−1.577−1.093kids−2.061
2.0262.922union: true1.130
Observed outcome against the fitted latent meanHow does a Tobit model's latent mean relate to outcomes that pile up at a limit?
View data
Fitted latent mean (x′β)hoursCensoring
4.0446.083observed
2.4059.452observed
4.3140left-censored
6.2802.094observed
5.6630left-censored
9.95514.405observed
9.2995.388observed
8.4868.341observed
5.9876.467observed
1.4780left-censored
8.83110.231observed
6.91411.441observed
7.90911.074observed
9.8874.404observed
1.1930left-censored
1.2065.914observed
8.4104.877observed
8.2290.7510observed
5.8459.805observed
12.86210.335observed
4.5118.118observed
4.1019.481observed
1.9760left-censored
6.6256.232observed
5.5084.294observed
9.9568.475observed
1.5421.665observed
4.8914.889observed
7.6118.561observed
7.76412.321observed
8.8698.656observed
5.4907.640observed
7.4912.260observed
5.0720.6890observed
12.53513.229observed
4.3709.310observed
4.7881.897observed
12.60413.732observed
7.1009.390observed
10.37412.967observed
7.8485.799observed
1.4790left-censored
1.4880left-censored
7.6798.334observed
−0.74921observed
9.7597.401observed
2.8970left-censored
5.04012.324observed
7.3132.202observed
2.0311.629observed
4.2903.799observed
6.0064.971observed
8.77214.641observed
5.4925.825observed
8.06814.836observed
4.81810.417observed
7.09114.886observed
7.1596.423observed
1.8818.988observed
3.7260.9130observed

First 60 of 400 rows.

Assumptions

  • Share censored — 53 rows at the lower and 0 at the upper limit (13% censored).
  • Maximum likelihood converged — Newton–Raphson converged in 5 iterations.
  • Normal latent errors with constant variance — Not testable directly from censored data; if in doubt compare with quantile regression at a quantile above the censoring point.

Coefficients (latent outcome) and average marginal effects

TermBSEzp95% CI low95% CI highEffect on E[y]
(Intercept)−6.9391.118−6.207< .001−9.130−4.748—
educ0.83030.081910.138< .0010.66980.99080.7150
exper0.23020.02588.919< .0010.17960.28080.1983
kids−1.5770.2471−6.383< .001−2.061−1.093−1.358
union: true2.0260.45734.431< .0011.1302.9221.745

B is the effect on the latent (uncensored) outcome; the effect on the observed mean is B × 0.861, the average probability of being uncensored.

  • Maximum likelihood (Newton–Raphson from OLS, 5 iterations); covariance from the observed information; Wald z tests; σ = 4.2415 (SE by the delta method from log σ).
The exact R script · R R version 4.5.1 (2025-06-13)
# Censored regression (Tobit)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method regression.censored 1.0.2 · spec 4770572910295758
# Dataset: c3_tobit (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/c3_tobit.parquet", col_select = c("hours", "educ", "exper", "kids", "union")))
n_input <- nrow(df)
df[["union"]] <- factor(df[["union"]], levels = c("false", "true"))  # stored level order
df <- df[stats::complete.cases(df[c("hours", "educ", "exper", "kids", "union")]), , 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("hours", "educ", "exper", "kids", "union"))  # infinite values stop the run (registry/errors.yaml)

# %% Design matrix
outcome <- "hours"
predictors <- c("educ", "exper", "kids", "union")
left <- 0  # values at or below are censored (NULL = no lower limit)
right <- NULL  # values at or above are censored (NULL = no upper limit)
interactions <- "none"
conf <- 0.95
if (is.null(left) && is.null(right)) stop("Set a lower limit, an upper limit or both: without censoring, use linear regression.")
terms <- cs_design_labels(df, predictors, interactions)
# Degenerate input stops with a catalog error; Python runs the same checks in the same order.
cs_check_rows(nrow(df), length(terms) + 1, "Censored 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
X <- model.matrix(cs_model_formula(outcome, predictors, interactions), data = df)
stopifnot(length(terms) == ncol(X))
colnames(X) <- terms
if (qr(X)$rank < ncol(X)) cs_error("CS_E_COLLINEAR")
n <- nrow(X)
k <- ncol(X)
y <- as.numeric(df[[outcome]])

# %% Fit: maximum likelihood (Newton-Raphson twin, identical in Python)
fit <- cs_tobit_fit(X, y, left, right)
null <- cs_tobit_fit(matrix(1, n, 1), y, left, right)
b <- fit$beta
se_all <- sqrt(diag(fit$cov))
se <- se_all[1:k]
zval <- b / se
pval <- 2 * pnorm(abs(zval), lower.tail = FALSE)
crit <- qnorm(1 - (1 - conf) / 2)
sigma <- fit$sigma
sigma_se <- sigma * se_all[k + 1]  # delta method from log sigma
lr <- 2 * (fit$loglik - null$loglik)
lr_df <- k - 1
lr_p <- pchisq(lr, lr_df, lower.tail = FALSE)
aic <- -2 * fit$loglik + 2 * (k + 1)
bic <- -2 * fit$loglik + log(n) * (k + 1)
eff <- cs_tobit_effects(X, b, sigma, left, right)
censored <- fit$n_left + fit$n_right

# %% Assumptions
share <- censored / n
assumptions <- list(
  list(key = "censoring", label = "Share censored", status = if (share > 0.5) "warn" else if (censored > 0) "info" else "warn", statistic = share,
       detail = paste0(sprintf("%d rows at the lower and %d at the upper limit (%.0f%% censored)", fit$n_left, fit$n_right, 100 * share),
                       if (share > 0.5) "; with more than half censored the normal-shape assumption drives the estimates." else if (censored > 0) "." else "; no row is censored, so ordinary linear regression gives the same answer.")),
  list(key = "convergence", label = "Maximum likelihood converged", status = if (fit$converged) "pass" else "fail",
       detail = if (fit$converged) sprintf("Newton–Raphson converged in %d iterations.", fit$iterations) else "The likelihood did not converge; estimates are unreliable."),
  list(key = "normality", label = "Normal latent errors with constant variance", status = "info",
       detail = "Not testable directly from censored data; if in doubt compare with quantile regression at a quantile above the censoring point.")
)

# %% Result
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],
                                                     ame = if (terms[j] == "(Intercept)") NULL else eff$ame[j]))
values <- list()
for (cf in coefs) {
  for (key in c("coef", "se", "z", "p", "ci_low", "ci_high")) values[[sprintf("%s[%s]", key, cf$term)]] <- if (key == "coef") cf$estimate else cf[[key]]
  if (!is.null(cf$ame)) values[[sprintf("ame[%s]", cf$term)]] <- cf$ame
}
values <- c(values, list(n = n, k = k, n_left = fit$n_left, n_right = fit$n_right, n_uncensored = fit$n_uncensored, censored_share = share,
                         left = left, right = right, sigma = sigma, sigma_se = sigma_se, log_sigma = fit$log_sigma, log_lik = fit$loglik,
                         log_lik_null = null$loglik, lr_chi2 = lr, lr_df = lr_df, lr_p = lr_p, aic = aic, bic = bic,
                         scale_factor = eff$scale, prob_uncensored = eff$prob_uncensored, mm_share = eff$mm_share, converged = fit$converged,
                         iterations = fit$iterations, n_params = k + 1, max_interaction_order = if (interactions != "none" && length(predictors) >= 2) 2 else 1,
                         missing_share = if (n_input > 0) n_dropped / n_input else 0))
limits <- paste(c(if (!is.null(left)) sprintf("below at %s", sprintf("%g", left)), if (!is.null(right)) sprintf("above at %s", sprintf("%g", right))), collapse = " and ")
significant <- vapply(Filter(function(cf) cf$p < 1 - conf, coefs[-1]), `[[`, "", "term")
summary <- paste0(sprintf("Tobit regression of %s censored %s (n = %d, %d censored): LR χ²(%d) = %.2f, %s; σ = %.3f. ", outcome, limits, n, censored, lr_df, lr, cs_fmt_p(lr_p), sigma),
                  if (length(significant)) sprintf("Significant terms: %s.", paste(significant, collapse = ", ")) else "No individual term is significant.")
pct <- sprintf("%.0f%%", conf * 100)
sl <- coefs[-1]
cs_publish(list(
  method = "regression.censored",
  methodVersion = "1.0.2",
  title = "Censored regression (Tobit)",
  engine = cs_engine_info("stats", "nanoparquet"),
  n = n,
  summary = summary,
  apa = sprintf("χ²(%d, N = %d) = %.2f, %s, σ = %.2f", lr_df, n, lr, cs_fmt_p(lr_p), sigma),
  statistics = list(list(key = "lr_chi2", label = "LR χ²", value = lr), list(key = "lr_p", label = "p", value = lr_p, format = "p"),
                    list(key = "sigma", label = "σ", value = sigma), list(key = "censored_share", label = "Censored", value = share, format = "percent")),
  tables = list(list(key = "coefficients", title = "Coefficients (latent outcome) and average marginal effects", columns = list(
    list(key = "term", label = "Term", type = "string"), list(key = "estimate", label = "B", type = "number"),
    list(key = "se", label = "SE", type = "number"), list(key = "z", label = "z", type = "number"),
    list(key = "p", label = "p", type = "pvalue"), list(key = "ci_low", label = paste(pct, "CI low"), type = "number"),
    list(key = "ci_high", label = paste(pct, "CI high"), type = "number"), list(key = "ame", label = "Effect on E[y]", type = "number")),
    rows = coefs, note = sprintf("B is the effect on the latent (uncensored) outcome; the effect on the observed mean is B × %.3f, the average probability of being uncensored.", eff$scale))),
  effectSizes = list(),
  assumptions = assumptions,
  warnings = warnings,
  notes = list(sprintf("Maximum likelihood (Newton–Raphson from OLS, %d iterations); covariance from the observed information; Wald z tests; σ = %.4f (SE by the delta method from log σ).", fit$iterations, sigma)),
  charts = list(cs_chart("coefficients", "forest", "Effects on the latent outcome", list(
    label = cs_col("Term", vapply(sl, `[[`, "", "term"), kind = "categorical"), estimate = cs_col("B", vapply(sl, `[[`, 0, "estimate")),
    low = cs_col("low", vapply(sl, `[[`, 0, "ci_low")), high = cs_col("high", vapply(sl, `[[`, 0, "ci_high"))), controls = list(reference = 0)),
    # Observed outcome against the fitted latent mean x'b, censored rows marked at their limit (Chart Lab `censored-fit`).
    cs_chart("fit", "censored-fit", "Observed outcome against the fitted latent mean", list(
      fitted = cs_col("Fitted latent mean (x\u2032\u03b2)", as.numeric(X %*% b), kind = "numeric"),
      observed = cs_col(outcome, as.numeric(y), kind = "numeric"),
      status = cs_col("Censoring", ifelse(!is.null(left) & y <= (if (is.null(left)) -Inf else left), "left-censored",
                                   ifelse(!is.null(right) & y >= (if (is.null(right)) Inf else right), "right-censored", "observed")),
                      kind = "categorical")))),
  values = values
))
Python

χ²(4, N = 400) = 185.65, p < .001, σ = 4.24

LR χ²
185.65
p
< .001
σ
4.241
Censored
13.3%

To keep this page light, the plots are shown once, under the R tab.

Assumptions

  • Share censored — 53 rows at the lower and 0 at the upper limit (13% censored).
  • Maximum likelihood converged — Newton–Raphson converged in 5 iterations.
  • Normal latent errors with constant variance — Not testable directly from censored data; if in doubt compare with quantile regression at a quantile above the censoring point.

Coefficients (latent outcome) and average marginal effects

TermBSEzp95% CI low95% CI highEffect on E[y]
(Intercept)−6.9391.118−6.207< .001−9.130−4.748—
educ0.83030.081910.138< .0010.66980.99080.7150
exper0.23020.02588.919< .0010.17960.28080.1983
kids−1.5770.2471−6.383< .001−2.061−1.093−1.358
union: true2.0260.45734.431< .0011.1302.9221.745

B is the effect on the latent (uncensored) outcome; the effect on the observed mean is B × 0.861, the average probability of being uncensored.

  • Maximum likelihood (Newton–Raphson from OLS, 5 iterations); covariance from the observed information; Wald z tests; σ = 4.2415 (SE by the delta method from log σ).
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Censored regression (Tobit)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method regression.censored 1.0.2 · spec 4770572910295758
# Dataset: c3_tobit (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
from scipy import stats

import codesplash as cs
from codesplash.errors import check_not_constant
from codesplash.stats import regression as csreg
from codesplash.stats import tobit as cstobit

# %% Data
df = pd.read_parquet("tests/parity/fixtures/c3_tobit.parquet", columns=["hours", "educ", "exper", "kids", "union"])
n_input = len(df)
df["union"] = pd.Categorical(df["union"], categories=["false", "true"])  # stored level order
df = df.dropna(subset=["hours", "educ", "exper", "kids", "union"])  # listwise deletion over the analysis columns
df["union"] = df["union"].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, ["hours", "educ", "exper", "kids", "union"])  # infinite values stop the run (registry/errors.yaml)

# %% Design matrix
outcome = "hours"
predictors = ["educ", "exper", "kids", "union"]
left = 0  # values at or below are censored (None = no lower limit)
right = None  # values at or above are censored (None = no upper limit)
interactions = "none"
conf = 0.95
if left is None and right is None:
    raise ValueError("Set a lower limit, an upper limit or both: without censoring, use linear regression.")
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, "Censored 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)
Xv = X.to_numpy(dtype=float)
y = df[outcome].to_numpy(dtype=float)

# %% Fit: maximum likelihood (Newton–Raphson twin, identical in R)
fit = cstobit.tobit_fit(Xv, y, left, right)
null = cstobit.tobit_fit(np.ones((n, 1)), y, left, right)
b = fit["beta"]
se_all = np.sqrt(np.diag(fit["cov"]))
se = se_all[:k]
zval = b / se
pval = 2 * stats.norm.sf(np.abs(zval))
crit = stats.norm.ppf(1 - (1 - conf) / 2)
sigma = fit["sigma"]
sigma_se = sigma * se_all[k]  # delta method from log σ
lr = 2 * (fit["loglik"] - null["loglik"])
lr_df = k - 1
lr_p = float(stats.chi2.sf(lr, lr_df))
aic = -2 * fit["loglik"] + 2 * (k + 1)
bic = -2 * fit["loglik"] + np.log(n) * (k + 1)
eff = cstobit.tobit_effects(Xv, b, sigma, left, right)
censored = fit["n_left"] + fit["n_right"]

# %% Assumptions
share = censored / n
assumptions = [
    {"key": "censoring", "label": "Share censored", "status": "warn" if share > 0.5 else ("info" if censored else "warn"), "statistic": share,
     "detail": (f"{fit['n_left']} rows at the lower and {fit['n_right']} at the upper limit ({share:.0%} censored)"
                + ("; with more than half censored the normal-shape assumption drives the estimates." if share > 0.5
                   else "." if censored else "; no row is censored, so ordinary linear regression gives the same answer."))},
    {"key": "convergence", "label": "Maximum likelihood converged", "status": "pass" if fit["converged"] else "fail",
     "detail": f"Newton–Raphson converged in {fit['iterations']} iterations." if fit["converged"] else "The likelihood did not converge; estimates are unreliable."},
    {"key": "normality", "label": "Normal latent errors with constant variance", "status": "info",
     "detail": "Not testable directly from censored data; if in doubt compare with quantile regression at a quantile above the censoring point."},
]

# %% Result
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]),
          "ame": None if t == "(Intercept)" else float(eff["ame"][j])} for j, t in enumerate(terms)]
values = {}
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")})
    if c["ame"] is not None:
        values[f"ame[{c['term']}]"] = c["ame"]
values.update({"n": n, "k": k, "n_left": fit["n_left"], "n_right": fit["n_right"], "n_uncensored": fit["n_uncensored"], "censored_share": share,
               "left": left, "right": right, "sigma": sigma, "sigma_se": float(sigma_se), "log_sigma": fit["log_sigma"], "log_lik": fit["loglik"],
               "log_lik_null": null["loglik"], "lr_chi2": float(lr), "lr_df": float(lr_df), "lr_p": lr_p, "aic": float(aic), "bic": float(bic),
               "scale_factor": eff["scale"], "prob_uncensored": eff["prob_uncensored"], "mm_share": eff["mm_share"], "converged": fit["converged"],
               "iterations": fit["iterations"], "n_params": k + 1, "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})
limits = " and ".join(([f"below at {left:g}"] if left is not None else []) + ([f"above at {right:g}"] if right is not None else []))
significant = [c["term"] for c in coefs[1:] if c["p"] < 1 - conf]
summary = (f"Tobit regression of {outcome} censored {limits} (n = {n}, {censored} censored): LR χ²({lr_df}) = {lr:.2f}, {cs.fmt_p(lr_p)}; σ = {sigma:.3f}. "
           + (f"Significant terms: {', '.join(significant)}." if significant else "No individual term is significant."))
pct = f"{conf:.0%}"
slopes = coefs[1:]
cs.publish({
    "method": "regression.censored",
    "methodVersion": "1.0.2",
    "title": "Censored regression (Tobit)",
    "engine": cs.engine_info("pandas", "numpy", "scipy"),
    "n": n,
    "summary": summary,
    "apa": f"χ²({lr_df}, N = {n}) = {lr:.2f}, {cs.fmt_p(lr_p)}, σ = {sigma:.2f}",
    "statistics": [{"key": "lr_chi2", "label": "LR χ²", "value": float(lr)}, {"key": "lr_p", "label": "p", "value": lr_p, "format": "p"},
                   {"key": "sigma", "label": "σ", "value": sigma}, {"key": "censored_share", "label": "Censored", "value": share, "format": "percent"}],
    "tables": [
        {"key": "coefficients", "title": "Coefficients (latent outcome) and average marginal effects", "columns": [
            {"key": "term", "label": "Term", "type": "string"}, {"key": "estimate", "label": "B", "type": "number"},
            {"key": "se", "label": "SE", "type": "number"}, {"key": "z", "label": "z", "type": "number"},
            {"key": "p", "label": "p", "type": "pvalue"}, {"key": "ci_low", "label": f"{pct} CI low", "type": "number"},
            {"key": "ci_high", "label": f"{pct} CI high", "type": "number"}, {"key": "ame", "label": "Effect on E[y]", "type": "number"}],
         "rows": coefs, "note": f"B is the effect on the latent (uncensored) outcome; the effect on the observed mean is B × {eff['scale']:.3f}, the average probability of being uncensored."},
    ],
    "effectSizes": [],
    "assumptions": assumptions,
    "warnings": warnings,
    "notes": [f"Maximum likelihood (Newton–Raphson from OLS, {fit['iterations']} iterations); covariance from the observed information; Wald z tests; "
              f"σ = {sigma:.4f} (SE by the delta method from log σ)."],
    "charts": [cs.chart("coefficients", "forest", "Effects on the latent outcome", {
        "label": cs.col("Term", [c["term"] for c in slopes], kind="categorical"), "estimate": cs.col("B", [c["estimate"] for c in slopes]),
        "low": cs.col("low", [c["ci_low"] for c in slopes]), "high": cs.col("high", [c["ci_high"] for c in slopes])}, controls={"reference": 0}),
        # Observed outcome against the fitted latent mean x′β, censored rows marked at their limit (Chart Lab `censored-fit`).
        cs.chart("fit", "censored-fit", "Observed outcome against the fitted latent mean", {
            "fitted": cs.col("Fitted latent mean (x′β)", [float(v) for v in Xv @ b], kind="numeric"),
            "observed": cs.col(outcome, [float(v) for v in y], kind="numeric"),
            "status": cs.col("Censoring", ["left-censored" if (left is not None and v <= left) else "right-censored" if (right is not None and v >= right) else "observed" for v in y],
                             kind="categorical")})],
    "values": values,
})

Here 53 of 400 rows sit at the limit, 13% of the data. Dropping them, or treating zero as an ordinary value, tends to flatten the slopes.

08

What does zero mean in your data?

Reflect

Take an outcome you know. Is a zero "it could have happened and didn't", "it could never happen for this unit", "they chose not to", or "it's below what we can see"?

Those answers point to a count model, a zero-inflated model, a hurdle and a Tobit model. Write your answer down before you fit anything: the choice should come from how the data arose, not from which fit looks best.

09

Check your understanding

Checkpoint

Check yourself

A Poisson model badly underpredicts zeros. What should you try first?

Show the answer

Answer: b

Overdispersion also produces more zeros than a Poisson expects. Fix that first, and see what remains.

Check yourself

In a zero-inflated model, what does the zero part estimate?

Show the answer

Answer: b

Observed zeros come from both parts. The zero model describes only the extra source.

Check yourself

A predictor has a positive coefficient in a hurdle model's zero part. What does it say?

Show the answer

Answer: a

The hurdle's binary equation models crossing zero. A zero-inflated model's binary equation models the opposite event.

Check yourself

Blood lead readings below the lab's limit of detection are all recorded as that limit. Which model fits best?

Show the answer

Answer: c

The values exist but can't be seen below the limit. That's censoring, and the outcome isn't a count.

10

Fit yours

In the app

Pick a Count outcome, then Count-model predictors. Set Model to zero-inflated or hurdle. Zero model can reuse the same predictors, use an intercept only, or take the ones you choose under Zero-model predictors.

For limits on a measured outcome, use censored regression.

Python
import pandas as pd
import statsmodels.api as sm
from patsy import dmatrix
from statsmodels.discrete.count_model import ZeroInflatedNegativeBinomialP

df = pd.read_csv("s4_bio.csv")
X = dmatrix('gender + married + Q("kids under 6") + prestige + mentor', df, return_type="dataframe")
Z = sm.add_constant(df[["mentor"]])
fit = ZeroInflatedNegativeBinomialP(df["articles"], X, exog_infl=Z).fit(method="bfgs", maxiter=5000, disp=0)
print(fit.summary())
print("AIC:", fit.aic)
R
library(pscl)

df <- read.csv("s4_bio.csv", check.names = FALSE)
zinb <- zeroinfl(articles ~ gender + married + `kids under 6` + prestige + mentor | mentor,
                 data = df, dist = "negbin")
summary(zinb)
AIC(zinb)

hd <- hurdle(articles ~ gender + `kids under 6` + mentor, data = df, dist = "poisson")
summary(hd)
11

Recap

Recap
  • Try a negative binomial before deciding that zeros are in excess.
  • Zero-inflated models have two sources of zeros, and a hurdle has one.
  • The zero parts model opposite events, so their signs flip.
  • A pile at a limit on a measured outcome is censoring, which is a Tobit problem.

Concepts in this lesson