What it is for
Suppose you survey 300 sites for a bird and count how many you see at each. A zero can happen for two different reasons:
the site is unsuitable: the bird does not live there, so the count is always zero, however long you look;
the site is suitable, but on the day of the survey you saw none.
A Poisson model knows only the second reason. It treats every zero as bad luck, so when many sites are simply empty it expects far fewer zeros than you observe, and its estimates of how abundant the bird is get pulled down. The figure shows this on simulated survey data (the data are created in the worked example below): 142 of the 300 sites gave a zero, but a Poisson fit expects only 55.
A zero-inflated model describes both reasons at once. It has two parts, each with its own covariates:
the zero part: the probability \(p\) that a site is unsuitable (here it depends on forest cover);
the count part: the expected count at a suitable site (here it depends on the food supply).
So the model answers two questions separately: where does the species live, and how many are there where it lives. Use it when the data have more zeros than a Poisson, binomial or negative binomial fit expects, and there is a reason for some zeros to be certain: species absent from a habitat, patients who can never have the event, machines that are switched off. If the extra zeros have no such reason and the counts are simply more variable than a Poisson allows, consider a negative binomial instead.
Parametrization
These families have two linear predictors:
\(\eta_i\), the linear predictor of the formula (
fixedandrandom), built from the latent field as for every other family;\(\eta^{\text{simple}}_i\), the simple predictor, built from the covariates \(x_{i1}, \dots, x_{im}\) in the
"simple"list of the response: \[\eta^{\text{simple}}_i = \sum_{j=1}^{m} \beta_j x_{ij}, \qquad m \le 10 \ (m \le 9 \text{ in the negative binomial families}).\] It holds fixed effects only, and its coefficients \(\beta_j\) are hyperparameters.
In 0poisson, 0binomial and 0nbinomial the simple
predictor gives the probability of a certain zero (in the bird survey, that the site
is unsuitable) and the formula gives the count:
\[\begin{aligned} f(y_i \mid \eta_i, \eta^{\text{simple}}_i) &= p_i\, 1[y_i = 0] + (1 - p_i)\, g(y_i \mid \eta_i), \qquad y_i = 0, 1, 2, \dots \ (\le n_i \text{ for the binomial}) \\ p_i &= \frac{\exp(\eta^{\text{simple}}_i)}{1 + \exp(\eta^{\text{simple}}_i)} \end{aligned}\]
The likelihood adds two cases, each weighted by its probability. Whether a site is suitable is not observed; the model only gives the probability of each case:
| Case | Probability | Distribution of \(y_i\) in this case |
|---|---|---|
| unsuitable site (certain zero) | \(p_i\) | \(1[y_i = 0]\): 1 for a count of 0 and 0 for any other count, so the count is always 0 |
| suitable site | \(1 - p_i\) | \(g(y_i \mid \eta_i)\): any count, including 0 by chance |
where
\(p_i\) is the probability of a certain zero, computed from the simple predictor (the logit link shown is the default);
\(g\) is the count distribution, computed from the formula's predictor \(\eta_i\). It is the likelihood of the ordinary family, the one you would use without zero inflation: the same distribution, mean and link as
family="poisson","binomial"or"nbinomial". A zero-inflated model is that ordinary model plus a probability \(p_i\) of a certain zero; with \(p_i = 0\) it is the ordinary model again.Poisson, as in the Poisson likelihood, with mean \(\mu_i = E_i \exp(\eta_i)\), where \(E_i\) is the exposure (default 1): \[g(y_i \mid \eta_i) = \frac{\mu_i^{y_i} e^{-\mu_i}}{y_i!};\]
binomial, as in the binomial likelihood, with \(n_i\) trials and success probability \(q_i = \exp(\eta_i) / (1 + \exp(\eta_i))\): \[g(y_i \mid \eta_i) = \binom{n_i}{y_i} q_i^{y_i} (1 - q_i)^{n_i - y_i};\]
negative binomial, as in the negative binomial likelihood, with mean \(\mu_i = E_i \exp(\eta_i)\) and size \(r\), so that the variance is \(\mu_i + \mu_i^2 / r\) (with
"variant": 1, \(r\) is replaced by \(E_i r\) throughout): \[g(y_i \mid \eta_i, r) = \frac{\Gamma(y_i + r)}{\Gamma(r)\, y_i!} \left(\frac{r}{r + \mu_i}\right)^{r} \left(\frac{\mu_i}{r + \mu_i}\right)^{y_i}.\]
A zero can therefore come from either source. For the Poisson,
\[P(y_i = 0 \mid \eta_i, \eta^{\text{simple}}_i) = p_i + (1 - p_i)\, e^{-\mu_i}, \qquad E(y_i \mid \eta_i, \eta^{\text{simple}}_i) = (1 - p_i)\, \mu_i:\]
the first term is the certain zeros, the second the zeros the count distribution produces by chance.
1poisson puts the point mass at one instead, and \(g\) is a Poisson
conditioned on \(y_i > 0\):
\[f(y_i \mid \eta_i, \eta^{\text{simple}}_i) = p_i\, 1[y_i = 1] + (1 - p_i)\, \frac{\mu_i^{y_i} e^{-\mu_i}}{y_i!\,(1 - e^{-\mu_i})}, \qquad y_i = 1, 2, \dots\]
with \(p_i\) and \(\mu_i = E_i \exp(\eta_i)\) as above.
The S families
The families ending in S swap the roles: the formula gives the
probability of a certain zero, \(p_i = \exp(\eta_i) / (1 + \exp(\eta_i))\), and the
simple predictor gives the count, with \(\eta^{\text{simple}}_i\) in place of
\(\eta_i\) in \(g\) (\(\mu_i = E_i \exp(\eta^{\text{simple}}_i)\), or
\(q_i = \exp(\eta^{\text{simple}}_i) / (1 + \exp(\eta^{\text{simple}}_i))\) for the
binomial). Use them when the probability of a certain zero needs random effects.
| Family | Count distribution | Probability of a certain zero from | Count from |
|---|---|---|---|
0poisson | Poisson | simple predictor | formula |
0poissonS | Poisson | formula | simple predictor |
0binomial | binomial | simple predictor | formula |
0binomialS | binomial | formula | simple predictor |
0nbinomial | negative binomial | simple predictor | formula |
0nbinomialS | negative binomial | formula | simple predictor |
1poisson | zero-truncated Poisson | simple predictor (point mass at one) | formula |
1poissonS | zero-truncated Poisson | formula (point mass at one) | simple predictor |
The links shown here are the defaults; the others are listed under Link Functions.
The response
The response is a dict with three keys:
"y": the counts, as a column name or an array;"simple": the covariates of the simple predictor, as column names or arrays. It has no implicit intercept: list"1"to include one. It takes at most 10 terms (9 for the negative binomial families);"E"(exposure) or, for the binomial families,"Ntrials"(number of trials). Both are optional and 1 by default.
The coefficients of the simple predictor are hyperparameters, so they appear
in summary_hyperpar, in the order of the "simple" list, in rows
named beta1 for 0poisson observations, beta2 for 0poisson
observations and so on (with the family's own name, and two spaces before
observations). Positional access, such as
result.summary_hyperpar.iloc[0], avoids typing the names. The negative
binomial families list the size first and number the coefficients from
beta0; see Negative binomial.
summary_fitted_values summarises the inverse link of the formula's
predictor for each observation: \(\exp(\eta_i)\) in 0poisson,
0nbinomial and 1poisson (the count rate for one unit of
exposure), \(q_i\) in 0binomial, and \(p_i\), the probability of a certain
zero, in the S families. It leaves out \(E_i\) and the other part of the model, so it
is not \(E(y_i)\); in 0poisson, \(E(y_i) = (1 - p_i)\,\mu_i\).
Worked example
This example uses the simulated bird survey from the figure at the top of the page. Because the data are simulated, the true values are known, so we can check what the model recovers.
1. The data
An observer visits each of 300 sites once and records:
count: the number of birds of the species seen during the visit;forest: how much of the site is covered by trees;food: how much food the site offers the bird;hours: how long the observer stayed at the site counting, between 1 and 3 hours. A longer visit gives more chances to see a bird.
| count | forest | food | hours |
|---|---|---|---|
| 13 | 0.00 | 1.51 | 2.71 |
| 7 | 0.30 | 0.56 | 1.81 |
| 0 | −0.27 | −0.06 | 1.01 |
| 0 | −0.89 | −0.58 | 2.57 |
| 4 | −0.45 | −0.63 | 1.49 |
| … | … | … | … |
forest and food are drawn from a standard normal distribution,
so 0 is a typical value and most sites lie between −2 and 2.
The data were generated so that sites with less forest are more often unsuitable,
and at suitable sites the count grows with food and with survey time. Food has no
effect on whether a site is suitable, and forest has no effect on how many birds a
suitable site holds. 142 sites (47%) have a count of zero.
The code below creates the data. Run it first; the other snippets on this page
use the data frame df it builds.
import numpy as np
import pandas as pd
from pyinla import pyinla
rng = np.random.default_rng(7)
n = 300
forest = rng.normal(size=n)
food = rng.normal(size=n)
hours = rng.uniform(1, 3, size=n)
# Unsuitable sites: the less forest, the more likely
p_empty = 1 / (1 + np.exp(-(-0.3 - 1.5 * forest)))
empty = rng.random(n) < p_empty
# Counts at suitable sites: more food and longer surveys, more birds
count = rng.poisson(hours * np.exp(0.8 + 0.6 * food))
df = pd.DataFrame({"count": np.where(empty, 0, count),
"forest": forest, "food": food, "hours": hours})
2. Fitting the model
The two parts of the model are given in two places. The zero part, whether a
site is unsuitable, goes in the "simple" list inside the response; here
it has an intercept and forest. The count part goes in fixed as usual;
here an intercept and food. Survey time is the exposure "E", so that
a survey twice as long expects twice as many birds.
result = pyinla(
model={
"response": {"y": "count", "E": "hours", "simple": ["1", "forest"]},
"fixed": ["1", "food"],
},
family="0poisson",
data=df,
control={"family": {"hyper": [
{"id": "beta1", "prior": "normal", "param": [0, 0.1]},
{"id": "beta2", "prior": "normal", "param": [0, 0.1]},
]}},
)
The control block gives the two coefficients of the zero part vague
priors. The default priors can be too strong; see
Hyperparameters.
3. The estimates
The count part is in result.summary_fixed, on the log scale. The zero
part is in result.summary_hyperpar, on the logit scale, as
beta1 (the intercept) and beta2 (forest), in the order of the
"simple" list.
| Part | Term | Posterior mean | 95% interval | True value |
|---|---|---|---|---|
| Count | intercept | 0.83 | 0.76 to 0.91 | 0.8 |
| Count | food | 0.59 | 0.51 to 0.67 | 0.6 |
| Zero | intercept (beta1) | −0.43 | −0.71 to −0.15 | −0.3 |
| Zero | forest (beta2) | −1.16 | −1.53 to −0.81 | −1.5 |
Every interval contains the true value.
4. Interpreting the estimates
On their natural scales the estimates say:
A suitable site with food at 0 is expected to give exp(0.83) = 2.3 birds per hour of survey. Each unit more food multiplies this by exp(0.59) = 1.8.
A site with forest at 0 is unsuitable with probability 1 / (1 + exp(0.43)) = 0.39. One unit more forest lowers this to 1 / (1 + exp(0.43 + 1.16)) = 0.17. The negative forest coefficient means that forest makes a site more likely to hold the bird.
5. Compared with a Poisson model
A Poisson model fitted to the same data, with both covariates in the formula, cannot separate the two reasons for a zero:
poisson = pyinla(model={"response": "count", "fixed": ["1", "food", "forest"]},
family="poisson", data=df, E=df["hours"])
| Poisson | Zero-inflated Poisson | Truth | |
|---|---|---|---|
| Food effect on the count | 0.48 (0.40 to 0.56) | 0.59 (0.51 to 0.67) | 0.6 |
| Forest effect on the count | 0.46 (0.37 to 0.54) | not in the count part | 0 |
| Sites expected to give zero | 55 | 143 | 142 observed |
The Poisson model underestimates the effect of food, and it reports a forest effect on abundance that does not exist: forest only decides whether the bird is present, but the Poisson model reads the empty sites in poorly forested areas as sites with few birds.
Hyperparameters
The coefficients \(\beta_1, \dots, \beta_m\) of the simple predictor, and for the negative binomial families also the size.
| Slot | Default prior | Default initial value | Other priors |
|---|---|---|---|
beta1 | normal, mean −4, precision 10 | −4 | gaussian, laplace, flat |
beta2 to beta10 (beta9 in the negative binomial families) | normal, mean 0, precision 10 | 0 | gaussian, laplace, flat |
size (negative binomial) | pc.mgamma, parameter 7 | log(10), a size of 10 | loggamma, normal, gaussian, flat, logtnormal |
The size is estimated on the log scale, so its "initial" is a log size:
"initial": np.log(3) starts it at 3. The coefficients have no
transformation.
Set your own priors
The default for beta1 puts \(p_i\) at about 0.02 (logit −4) where the
simple predictor's covariates are 0, and with a standard deviation of 0.32 it is strong
enough to move the estimate. In the
worked example (true intercept −0.3) the default priors give −1.02, with
an interval of −1.31 to −0.73 that misses the truth, and put the probability
that a site with forest at 0 is unsuitable at 0.27, against 0.43 in truth. The
vague prior used there, normal with mean 0 and precision 0.1, gives −0.43, and
a probability of 0.39. Set your own priors, as in the example. A
coefficient can also be fixed at its "initial" value with "fixed": True.
Swapped families
In the families ending in S the simple predictor is the count, so
beta1 is the intercept of the count. Its default prior is the same as in
the other families, normal with mean −4, where it suits the intercept of a zero
probability; here it pulls the count down: on the worked example's data the defaults
give 0.76 instead of 0.83. Set the priors here too. With the roles of the two predictors swapped:
result = pyinla(
model={
"response": {"y": "count", "E": "hours", "simple": ["1", "food"]}, # count part
"fixed": ["1", "forest"], # zero part
},
family="0poissonS",
data=df,
control={"family": {"hyper": [
{"id": "beta1", "prior": "normal", "param": [0, 0.1]},
{"id": "beta2", "prior": "normal", "param": [0, 0.1]},
]}},
)
The count part, now beta1 and beta2, is 0.83 and 0.59 as
before, and the forest effect on the zero probability is −1.18 (−1.54 to
−0.81).
Link Functions
The link of the simple predictor is set with
control={"family": {"link_simple": ...}} and the link of the formula
with "link".
| Family | link_simple | link |
|---|---|---|
0poisson, 1poisson, 0nbinomial | logit (default), probit, cloglog | log |
0binomial | logit (default), probit, cloglog | logit (default), probit, cloglog, ccloglog, cauchit, loglog, log |
0poissonS, 1poissonS | log | logit (default), probit, cloglog, ccloglog, cauchit, loglog |
0nbinomialS | log | logit (default), probit, cloglog, ccloglog, cauchit |
0binomialS | logit (default), probit, cloglog | logit (default), probit, cloglog, ccloglog, cauchit, loglog |
Negative binomial
0nbinomial and 0nbinomialS also estimate the size, set
with "id": "size". "variant" may be 0 or 1. The simple
predictor takes at most 9 terms here. In the output its coefficients are
labelled from beta0: the coefficient set with "id": "beta1"
is reported as beta0. That coefficient cannot be fixed in these two
families.
Here pyINLA departs from upstream on purpose. Upstream writes the prior of
beta1 into the slot the engine reads as the size, so the size silently
gets the normal(−4, 10) prior meant for the intercept and is pulled towards
small values. pyINLA gives the size its own prior, so results for these two
families differ from upstream's. All other families match upstream.
Validation Rules
The counts must be non-negative integers (at least 1 for the one-inflated families). Missing counts are allowed: they do not enter the likelihood, and their fitted values are on the scale of the linear predictor unless
control["predictor"]sets"link": 1."E"must be strictly positive and"Ntrials"positive integers, with no count above its"Ntrials". If omitted they are 1 for every observation, so a binomial family without"Ntrials"takes 0/1 data only."simple"must be a non-empty list of column names or arrays (and"1"), finite wherever the count is observed.The response dict takes only
"y","simple"and"E"or"Ntrials".EandNtrialsare not accepted as arguments ofpyinla()for these families.These families cannot yet be combined with other likelihoods in one fit.
control["family"]["hyper"]is a list of dicts with the keys"id","prior","param","initial"and"fixed". An entry without"id"takes the slot at its position in the list;"theta1","theta2", … name the slots by position (in the negative binomial families"theta1"is the size).Each slot may be given once, and only for coefficients the simple predictor has:
beta3needs at least three terms.
Specification
family="0poisson","0poissonS","0binomial","0binomialS","0nbinomial","0nbinomialS","1poisson","1poissonS"Required arguments:
model["response"]: a dict with"y"(the counts) and"simple"(the simple predictor)
Optional arguments:
"E"(Poisson and negative binomial) or"Ntrials"(binomial) in the response dictoffset: added to the formula's linear predictorweights: one per observation, multiplying its log-likelihoodcontrol["family"]["link_simple"]andcontrol["family"]["link"]control["family"]["variant"](negative binomial, 0 or 1)