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.
What runs in CodeSplash
- Zero-inflated and hurdle count models Verified in Python and R
- Censored regression (Tobit) Verified in Python and R
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
Two kinds of zero
ReadA 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.
A mixture of two processes
ReadA 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:
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.
Does a flexible model need the extra part?
PredictPredict 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?
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.
Read the card
In the appZero-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
View data
| IRR | high | term | low |
|---|---|---|---|
| 0.8090 | 0.9315 | gender[Women] | 0.7027 |
| 1.150 | 1.348 | married[Married] | 0.9805 |
| 0.8457 | 0.9372 | kids under 6 | 0.7630 |
| 1.002 | 1.074 | prestige | 0.9345 |
| 1.025 | 1.032 | mentor | 1.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)
| Term | Estimate | SE | z | p | IRR | Lower | Upper |
|---|---|---|---|---|---|---|---|
| (Intercept) | 0.4040 | 0.1417 | 2.851 | 0.0044 | 1.498 | 1.135 | 1.977 |
| gender[Women] | −0.2119 | 0.0719 | −2.946 | 0.0032 | 0.8090 | 0.7027 | 0.9315 |
| married[Married] | 0.1395 | 0.0812 | 1.718 | 0.0859 | 1.150 | 0.9805 | 1.348 |
| kids under 6 | −0.1676 | 0.0525 | −3.195 | 0.0014 | 0.8457 | 0.7630 | 0.9372 |
| prestige | 0.0020 | 0.0356 | 0.0552 | 0.9560 | 1.002 | 0.9345 | 1.074 |
| mentor | 0.0244 | 0.0035 | 6.934 | 4.080e-12 | 1.025 | 1.018 | 1.032 |
Zero model: log-odds of an excess (structural) zero
| Term | Estimate | SE | z | p | Odds ratio |
|---|---|---|---|---|---|
| (Intercept) | −0.8067 | 0.3532 | −2.284 | 0.0224 | 0.4463 |
| mentor | −0.6095 | 0.2458 | −2.480 | 0.0131 | 0.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
))
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)
| Term | Estimate | SE | z | p | IRR | Lower | Upper |
|---|---|---|---|---|---|---|---|
| (Intercept) | 0.4040 | 0.1417 | 2.851 | 0.0044 | 1.498 | 1.135 | 1.977 |
| gender[Women] | −0.2119 | 0.0719 | −2.946 | 0.0032 | 0.8090 | 0.7027 | 0.9315 |
| married[Married] | 0.1395 | 0.0812 | 1.718 | 0.0859 | 1.150 | 0.9805 | 1.348 |
| kids under 6 | −0.1676 | 0.0525 | −3.195 | 0.0014 | 0.8457 | 0.7630 | 0.9372 |
| prestige | 0.0020 | 0.0356 | 0.0552 | 0.9560 | 1.002 | 0.9345 | 1.074 |
| mentor | 0.0244 | 0.0035 | 6.934 | 4.080e-12 | 1.025 | 1.018 | 1.032 |
Zero model: log-odds of an excess (structural) zero
| Term | Estimate | SE | z | p | Odds ratio |
|---|---|---|---|---|---|
| (Intercept) | −0.8067 | 0.3532 | −2.284 | 0.0224 | 0.4463 |
| mentor | −0.6095 | 0.2458 | −2.480 | 0.0131 | 0.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.
Hurdle models: one source of zeros
ReadA 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.
Watch the sign
PredictPredict 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?
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 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
View data
| IRR | high | term | low |
|---|---|---|---|
| 0.8037 | 0.9019 | gender[Women] | 0.7163 |
| 1.143 | 1.301 | married[Married] | 1.004 |
| 0.8496 | 0.9250 | kids under 6 | 0.7804 |
| 0.9935 | 1.051 | prestige | 0.9395 |
| 1.018 | 1.023 | mentor | 1.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)
| Term | Estimate | SE | z | p | IRR | Lower | Upper |
|---|---|---|---|---|---|---|---|
| (Intercept) | 0.6302 | 0.1131 | 5.572 | 2.521e-8 | 1.878 | 1.505 | 2.344 |
| gender[Women] | −0.2185 | 0.0588 | −3.716 | 0.0002 | 0.8037 | 0.7163 | 0.9019 |
| married[Married] | 0.1334 | 0.0662 | 2.016 | 0.0438 | 1.143 | 1.004 | 1.301 |
| kids under 6 | −0.1630 | 0.0434 | −3.757 | 0.0002 | 0.8496 | 0.7804 | 0.9250 |
| prestige | −0.0065 | 0.0285 | −0.2284 | 0.8193 | 0.9935 | 0.9395 | 1.051 |
| mentor | 0.0183 | 0.0023 | 8.091 | 5.918e-16 | 1.018 | 1.014 | 1.023 |
Zero model: log-odds of an excess (structural) zero
| Term | Estimate | SE | z | p | Odds ratio |
|---|---|---|---|---|---|
| (Intercept) | −0.6837 | 0.2053 | −3.331 | 0.0009 | 0.5047 |
| mentor | −0.1303 | 0.0402 | −3.240 | 0.0012 | 0.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
))
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)
| Term | Estimate | SE | z | p | IRR | Lower | Upper |
|---|---|---|---|---|---|---|---|
| (Intercept) | 0.6302 | 0.1131 | 5.572 | 2.521e-8 | 1.878 | 1.505 | 2.344 |
| gender[Women] | −0.2185 | 0.0588 | −3.716 | 0.0002 | 0.8037 | 0.7163 | 0.9019 |
| married[Married] | 0.1334 | 0.0662 | 2.016 | 0.0438 | 1.143 | 1.004 | 1.301 |
| kids under 6 | −0.1630 | 0.0434 | −3.757 | 0.0002 | 0.8496 | 0.7804 | 0.9250 |
| prestige | −0.0065 | 0.0285 | −0.2284 | 0.8193 | 0.9935 | 0.9395 | 1.051 |
| mentor | 0.0183 | 0.0023 | 8.091 | 5.918e-16 | 1.018 | 1.014 | 1.023 |
Zero model: log-odds of an excess (structural) zero
| Term | Estimate | SE | z | p | Odds ratio |
|---|---|---|---|---|---|
| (Intercept) | −0.6837 | 0.2053 | −3.331 | 0.0009 | 0.5047 |
| mentor | −0.1303 | 0.0402 | −3.240 | 0.0012 | 0.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 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
View data
| IRR | high | term | low |
|---|---|---|---|
| 0.7875 | 0.8941 | gender[Women] | 0.6936 |
| 0.8916 | 0.9725 | kids under 6 | 0.8175 |
| 1.019 | 1.023 | mentor | 1.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)
| Term | Estimate | SE | z | p | IRR | Lower | Upper |
|---|---|---|---|---|---|---|---|
| (Intercept) | 0.6916 | 0.0547 | 12.643 | 1.223e-36 | 1.997 | 1.794 | 2.223 |
| gender[Women] | −0.2389 | 0.0648 | −3.689 | 0.0002 | 0.7875 | 0.6936 | 0.8941 |
| kids under 6 | −0.1147 | 0.0443 | −2.591 | 0.0096 | 0.8916 | 0.8175 | 0.9725 |
| mentor | 0.0184 | 0.0022 | 8.273 | 1.308e-16 | 1.019 | 1.014 | 1.023 |
Zero model: log-odds of crossing the hurdle (y > 0)
| Term | Estimate | SE | z | p | Odds ratio |
|---|---|---|---|---|---|
| (Intercept) | 0.4956 | 0.1520 | 3.259 | 0.0011 | 1.641 |
| gender[Women] | −0.2911 | 0.1572 | −1.852 | 0.0641 | 0.7474 |
| kids under 6 | −0.2008 | 0.1001 | −2.006 | 0.0449 | 0.8181 |
| mentor | 0.0800 | 0.0125 | 6.392 | 1.636e-10 | 1.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
))
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)
| Term | Estimate | SE | z | p | IRR | Lower | Upper |
|---|---|---|---|---|---|---|---|
| (Intercept) | 0.6916 | 0.0547 | 12.643 | 1.223e-36 | 1.997 | 1.794 | 2.223 |
| gender[Women] | −0.2389 | 0.0648 | −3.689 | 0.0002 | 0.7875 | 0.6936 | 0.8941 |
| kids under 6 | −0.1147 | 0.0443 | −2.591 | 0.0096 | 0.8916 | 0.8175 | 0.9725 |
| mentor | 0.0184 | 0.0022 | 8.273 | 1.308e-16 | 1.019 | 1.014 | 1.023 |
Zero model: log-odds of crossing the hurdle (y > 0)
| Term | Estimate | SE | z | p | Odds ratio |
|---|---|---|---|---|---|
| (Intercept) | 0.4956 | 0.1520 | 3.259 | 0.0011 | 1.641 |
| gender[Women] | −0.2911 | 0.1572 | −1.852 | 0.0641 | 0.7474 |
| kids under 6 | −0.2008 | 0.1001 | −2.006 | 0.0449 | 0.8181 |
| mentor | 0.0800 | 0.0125 | 6.392 | 1.636e-10 | 1.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,
})
Zeros that are really limits
ReadA 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.
χ²(4, N = 400) = 185.65, p < .001, σ = 4.24
- LR χ²
- 185.65
- p
- < .001
- σ
- 4.241
- Censored
- 13.3%
Plots
View data
| B | high | Term | low |
|---|---|---|---|
| 0.8303 | 0.9908 | educ | 0.6698 |
| 0.2302 | 0.2808 | exper | 0.1796 |
| −1.577 | −1.093 | kids | −2.061 |
| 2.026 | 2.922 | union: true | 1.130 |
View data
| Fitted latent mean (x′β) | hours | Censoring |
|---|---|---|
| 4.044 | 6.083 | observed |
| 2.405 | 9.452 | observed |
| 4.314 | 0 | left-censored |
| 6.280 | 2.094 | observed |
| 5.663 | 0 | left-censored |
| 9.955 | 14.405 | observed |
| 9.299 | 5.388 | observed |
| 8.486 | 8.341 | observed |
| 5.987 | 6.467 | observed |
| 1.478 | 0 | left-censored |
| 8.831 | 10.231 | observed |
| 6.914 | 11.441 | observed |
| 7.909 | 11.074 | observed |
| 9.887 | 4.404 | observed |
| 1.193 | 0 | left-censored |
| 1.206 | 5.914 | observed |
| 8.410 | 4.877 | observed |
| 8.229 | 0.7510 | observed |
| 5.845 | 9.805 | observed |
| 12.862 | 10.335 | observed |
| 4.511 | 8.118 | observed |
| 4.101 | 9.481 | observed |
| 1.976 | 0 | left-censored |
| 6.625 | 6.232 | observed |
| 5.508 | 4.294 | observed |
| 9.956 | 8.475 | observed |
| 1.542 | 1.665 | observed |
| 4.891 | 4.889 | observed |
| 7.611 | 8.561 | observed |
| 7.764 | 12.321 | observed |
| 8.869 | 8.656 | observed |
| 5.490 | 7.640 | observed |
| 7.491 | 2.260 | observed |
| 5.072 | 0.6890 | observed |
| 12.535 | 13.229 | observed |
| 4.370 | 9.310 | observed |
| 4.788 | 1.897 | observed |
| 12.604 | 13.732 | observed |
| 7.100 | 9.390 | observed |
| 10.374 | 12.967 | observed |
| 7.848 | 5.799 | observed |
| 1.479 | 0 | left-censored |
| 1.488 | 0 | left-censored |
| 7.679 | 8.334 | observed |
| −0.7492 | 1 | observed |
| 9.759 | 7.401 | observed |
| 2.897 | 0 | left-censored |
| 5.040 | 12.324 | observed |
| 7.313 | 2.202 | observed |
| 2.031 | 1.629 | observed |
| 4.290 | 3.799 | observed |
| 6.006 | 4.971 | observed |
| 8.772 | 14.641 | observed |
| 5.492 | 5.825 | observed |
| 8.068 | 14.836 | observed |
| 4.818 | 10.417 | observed |
| 7.091 | 14.886 | observed |
| 7.159 | 6.423 | observed |
| 1.881 | 8.988 | observed |
| 3.726 | 0.9130 | observed |
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
| Term | B | SE | z | p | 95% CI low | 95% CI high | Effect on E[y] |
|---|---|---|---|---|---|---|---|
| (Intercept) | −6.939 | 1.118 | −6.207 | < .001 | −9.130 | −4.748 | — |
| educ | 0.8303 | 0.0819 | 10.138 | < .001 | 0.6698 | 0.9908 | 0.7150 |
| exper | 0.2302 | 0.0258 | 8.919 | < .001 | 0.1796 | 0.2808 | 0.1983 |
| kids | −1.577 | 0.2471 | −6.383 | < .001 | −2.061 | −1.093 | −1.358 |
| union: true | 2.026 | 0.4573 | 4.431 | < .001 | 1.130 | 2.922 | 1.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
))
χ²(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
| Term | B | SE | z | p | 95% CI low | 95% CI high | Effect on E[y] |
|---|---|---|---|---|---|---|---|
| (Intercept) | −6.939 | 1.118 | −6.207 | < .001 | −9.130 | −4.748 | — |
| educ | 0.8303 | 0.0819 | 10.138 | < .001 | 0.6698 | 0.9908 | 0.7150 |
| exper | 0.2302 | 0.0258 | 8.919 | < .001 | 0.1796 | 0.2808 | 0.1983 |
| kids | −1.577 | 0.2471 | −6.383 | < .001 | −2.061 | −1.093 | −1.358 |
| union: true | 2.026 | 0.4573 | 4.431 | < .001 | 1.130 | 2.922 | 1.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.
What does zero mean in your data?
ReflectTake 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.
Check your understanding
CheckpointCheck 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.
Fit yours
In the appPick 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.
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)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)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