DRegression models · regression.zero_inflated
Zero-inflated and hurdle count models
Do the counts have more zeros than a Poisson or negative binomial model allows, and what drives the zeros versus the counts?
Two-part models for counts with excess zeros: zero-inflated Poisson / negative binomial (a logistic model for "always zero" mixed with a count model) and hurdle Poisson / negative binomial (a logistic model for crossing zero and a zero-truncated count model for the positives). Count effects as incidence-rate ratios, zero-model coefficients as log-odds, observed versus expected zeros, and Vuong's test against the ordinary count model.
A real result
Example “Zinb bio”, recorded in both engines. In the app, “Try this example” loads it into Analyze.
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
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.
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.
Do it in CodeSplash Run it on your own data, in Python or R, with the code to prove it.
Worked examples in the app
- Zinb bios4_bio · outcome: articles · predictors: gender, married, kids under 6, prestige, mentor · zero_predictors: mentor
- Zip bios4_bio · outcome: articles · predictors: gender, married, kids under 6, prestige, mentor · zero_predictors: mentor
- Hurdle poisson sames4_bio · outcome: articles · predictors: gender, kids under 6, mentor
- Hurdle negbin intercepts4_bio · outcome: articles · predictors: gender, married, kids under 6, prestige, mentor
- Degenerate constants4_bio · outcome: articles · predictors: gender, married, kids under 6, prestige, mentor · zero_predictors: mentor
- Degenerate n3s4_bio · outcome: articles · predictors: gender, married, kids under 6, prestige, mentor · zero_predictors: mentor
- Degenerate single levels4_bio · outcome: articles · predictors: gender, married, kids under 6, prestige, mentor · zero_predictors: mentor
- Degenerate tiess4_bio · outcome: articles · predictors: gender, married, kids under 6, prestige, mentor · zero_predictors: mentor
In the guides
Where it sits in the decision guides
- Counts, rates and ordinal outcomes · Statistics Guide · B — Compare groups
- Count outcome: Poisson / negative binomial / zero-inflated · Statistics Guide · D — Predict an outcome
- Model-specific checks (VIF, PH, PO, dispersion) · Statistics Guide · Step 2 — Check assumptions
What you need
- Count outcomenumeric · 1 column
- Non-negative whole numbers.
- Count-model predictorsnumeric / categorical / boolean · 1–20 columns · 2–30 levels
- Predictors of the count part of the model.
- Zero-model predictorsnumeric / categorical / boolean · 0–20 columns · 2–30 levels
- Predictors of the zeros (used when "Zero model" is "Chosen predictors").
Choices you make
statistics
- Modeldefault zinb
Zero-inflated models mix extra zeros with a count model; hurdle models treat any zero vs positive as a separate step.
- Zero-inflated Poisson — Mixes a Poisson count with extra zeros from a second process; pick it when some units are never at risk.
- Zero-inflated negative binomial(default) — Like zero-inflated Poisson, for counts that also vary more than their mean.
- Hurdle Poisson — Models zero versus not, then positive counts by a truncated Poisson; pick it when all zeros come from one process.
- Hurdle negative binomial — A hurdle model whose positive counts vary more than their mean.
- Zero modeldefault same
Predictors for the extra-zero part: the same as the count model, an intercept only, or ones you choose.
- Same predictors as the count model(default) — Uses the count model's predictors for the zero part; the usual start.
- Intercept only — Gives the zero part one constant; pick it when extra zeros don't depend on predictors.
- Chosen predictors (zero-model role) — Uses the columns in the zero-model role; pick it when you know what drives the zeros.
hypothesis
- Confidence leveldefault 0.95
How sure the intervals should be: 0.95 gives 95% confidence intervals. Higher confidence means wider intervals.
Checks and remedies
CodeSplash checks each testable assumption on every run and shows the result on the card; premises the data can’t test are marked. If a check fails, these are the ways forward.
Excess zeros
Compares observed zeros with those the fitted model expects; Vuong's test compares against the ordinary count model (its validity for nested-at-the-boundary models is debated — Wilson 2015).
Converged fit
What it reports
- Tests: Two-part model vs ordinary count model (Vuong)
- n
- How many independent units the analysis used; it sets precision and power.
- model
- The exact variant that ran (for example Welch vs classic F), shown so the result can be reported and reproduced.
- zero_model
- Mixes an always-zero group, with its own logistic model, with an ordinary count model that can also produce zeros.
- loglik
- The logarithm of the likelihood; higher (less negative) means the model fits the data better.
- aic
- A model score balancing fit against complexity; lower is better, and only differences matter.
- bic
- Like AIC but with a stronger penalty for parameters as n grows; favors simpler models.
- n_params
- How many values a model learns from the data: a regression's coefficients (intercept included) or a network's weights and biases.
- theta
- A count model with an extra parameter θ, so the variance is μ + μ²/θ. A smaller θ means more extra spread.
- zeros_observed
- More zeros than a Poisson or negative-binomial count model expects.
- zeros_expected
- More zeros than a Poisson or negative-binomial count model expects.
- vuong_z
- An estimate in standard-error units, compared with the standard normal distribution.
- vuong_p
- How surprising your data would be if the null hypothesis were true, as a probability.
- converged
- Whether an iterative fit found a stable solution; warnings mean estimates may be unreliable.
Per group, level or term: count_coef[<term>], count_se[<term>], count_p[<term>], irr[<term>], zero_coef[<term>], zero_se[<term>], zero_p[<term>]
Python and R
Python and R agree to 6 decimals (relative tolerance 1e-6). Python uses pandas, numpy, scipy, statsmodels, codesplash; R uses pscl, MASS, nanoparquet, codesplashr.
Default traps between the two languages
- R fits pscl::zeroinfl / hurdle (BFGS, reltol 1e-15); Python fits statsmodels' ZeroInflatedPoisson / ZeroInflatedNegativeBinomialP / Logit + TruncatedLF* models from pscl's starting values. pscl's BFGS stops on the flat log-likelihood with gradients near 1e-3 (coefficients about 3e-7 from the optimum), so both engines finish with Newton steps on the same twin log-likelihood (cs zi_polish); from either start they reach the same optimum to ~1e-9.
- Standard errors in both engines come from the same observed information: the Hessian of the twin log-likelihood (cs zi_loglik) by central second differences, evaluated at each engine's estimates; second differences of a sum over all rows carry rounding noise of about 1e-6 relative in the SEs (1e-5 in small p-values), hence the SE and p bands. summary() of a pscl fit inverts optim's coarser Hessian (step 1e-3; differences up to ~3e-4) and statsmodels' own ZIP Hessian is about 1% off, so neither library's SEs are used.
- NB dispersion is reported as θ = 1/α. Vuong's statistic is the raw one (pscl also prints AIC/BIC-corrected versions); the ordinary NB model uses the same alternation as MASS::glm.nb in both engines (cs glm twins).
The exact script CodeSplash ran for example “Zinb bio” · 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 exact script CodeSplash ran for example “Zinb bio” · 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
))
Sources
- Lambert, D. (1992). Zero-inflated Poisson regression, with an application to defects in manufacturing. Technometrics, 34, 1–14.
- Mullahy, J. (1986). Specification and testing of some modified count data models. Journal of Econometrics, 33, 341–365.
- Zeileis, A., Kleiber, C., & Jackman, S. (2008). Regression models for count data in R. Journal of Statistical Software, 27(8).
- Vuong, Q. H. (1989). Likelihood ratio tests for model selection and non-nested hypotheses. Econometrica, 57, 307–333.
- Wilson, P. (2015). The misuse of the Vuong test for non-nested models to test for zero-inflation. Economics Letters, 127, 51–53.
From the CodeSplash method registry · regression.zero_inflated v1.0.1.