← All examples

Count Models

Regression for count data, threaded by one problem — extra-Poisson variation, the near-universal fact that real counts vary more than a plain Poisson allows, and the different ways to model it. It starts with the two core GLMs, Poisson and Negative Binomial regression, where the NB's dispersion parameter restores calibrated inference under overdispersion. The hierarchical Poisson GLMM adds group random effects on the log-rate, and the hierarchical binomial GLMM is its twin on grouped proportions — together completing the Gaussian / Poisson / binomial hierarchical-GLM grid. Zero-inflated Poisson and Negative Binomial handle counts with far more zeros than any Poisson can produce, splitting structural from sampling zeros via a data-augmentation Gibbs sampler. And the Besag–York–Mollié spatial model closes the set — disease mapping where an intrinsic-CAR prior pools each area toward its map neighbours rather than a global mean. Each is built from scratch and cross-checked across PyMC and R.

What makes a count different. A count is a whole number of things that happened — seizures in a fortnight, seeds that germinated on a plate, cases of a disease in a district. Three properties separate it from an ordinary measurement. It cannot be negative. It has no natural ceiling (or, for grouped counts, a known one: you cannot germinate more seeds than you planted). And — the property that drives this entire section — its variability is tied to its level rather than free of it. A district averaging 2 cases will never show a deviation of ±50; one averaging 500 will never show a deviation of ±2. Ordinary regression assumes the spread of the errors is the same everywhere, and for counts that assumption is not merely wrong, it is impossible. The Poisson builds the tie in exactly: variance = mean. That is equidispersion, it is the strongest assumption made anywhere in this section, and every model below is a response to the fact that real counts vary more than it permits.

GLM, and what the link does. Every model here is a generalised linear model — the extension of ordinary regression to outcomes that are not Normal. The machinery is the same in each case: form a linear combination of the predictors, then pass it through a link function that maps it onto the scale the outcome actually lives on. Counts cannot be negative, so the link is the log: the model predicts log(rate), and exponentiating returns a rate that is positive whatever the coefficients do. When a random effect per group is added on top, the model becomes a GLMM, the second M standing for mixed — mixing coefficients that are fixed across the whole sample with coefficients that vary from group to group. Four of the five examples below are GLMMs.

Why the log link makes everything a ratio. A consequence worth stating, because it governs how every result on these pages is reported. On a log scale, adding a coefficient multiplies the rate: a coefficient of −0.23 means the rate is multiplied by e−0.23 = 0.79, a 21% reduction. That multiplier is the rate ratio, and it is what count models report instead of a difference, because a difference would mean something different for a hospital doing 47 operations than for one doing 810. The same object appears as a relative risk in disease mapping and as an incidence rate ratio in epidemiology; they are the same number under different names.

The offset, which is how counts become rates. Comparing raw counts across units of different size is meaningless — a district with 39 lip-cancer cases and one with 9 are not comparable until you know how many people are in each. The standard device is an offset: a term added to the linear predictor whose coefficient is fixed at 1 rather than estimated. Putting log(expected cases) in as an offset is exactly equivalent to modelling the ratio of observed to expected, so the coefficients become statements about rates while the likelihood stays a proper count likelihood. In the spatial model below the offset is age-standardised expected cases; elsewhere it would be population, exposure time, or number of trials.

One construction, four kinds of outcome. The hierarchical models in this collection are worth seeing as a single grid rather than as separate examples, because they are the same construction with the likelihood swapped. In every case each unit — a rat, a patient, a plate, a district — gets its own intercept, those intercepts are treated as draws from one common Normal distribution, and that distribution’s spread is estimated alongside everything else. What changes between them is only what sits on top. With a Gaussian outcome it is the Rats growth model, in the regression section. With a Poisson outcome it is Epil, below. With a binomial outcome it is Seeds, also below. With a binary outcome measured repeatedly it is the toenail trial, in limited dependent variables. Same random intercept, four likelihoods — and the only thing the choice of likelihood really changes is the sampler: conjugate and exact for the Gaussian, Pólya–Gamma for the binary and binomial logits, and Metropolis-within-Gibbs for the Poisson, which has no such trick available.

One construction, four likelihoods

The hierarchical models in this collection are the same object four times over. Each unit keeps its own intercept; those intercepts are treated as draws from one common Normal whose spread is estimated alongside everything else. Only the row changes — what kind of outcome sits on top, and therefore which sampler the conditional distributions admit.

OutcomeLikelihoodExample Unit that variesSampler it admits
a measurementGaussian Rats growth curves ratfully conjugate — exact Gibbs
yes / no, repeatedBernoulli–logit Toenail trial patientPólya–Gamma — exact, tuning-free
k successes of nBinomial–logit Seeds germination platePólya–Gamma, or conjugate beta-binomial
a countPoisson–log Epil seizure counts patientno augmentation exists — Metropolis-within-Gibbs

The last column is the one worth reading across. Nothing about the model gets harder as you go down the table — the hierarchy is identical in all four rows. What changes is whether the likelihood happens to admit a trick that makes its conditional distributions Gaussian. The Gaussian case needs no trick. The two logit rows get one for free from Pólya–Gamma augmentation, which is why the binary and binomial examples run tuning-free Gibbs. The Poisson has no such trick, and that single absence is why the count models in this section fall back on Metropolis steps, need tuning, and mix more slowly than their siblings — a difference in the mathematics of the likelihood, not in the ambition of the model.

Bayesian Count Regression — Poisson & Negative Binomial

A from-scratch implementation of the two core count GLMs — Poisson (equidispersion) and Negative Binomial (NB2, with a dispersion parameter r) — each fit both by maximum likelihood (Newton/IRLS) and Bayesian random-walk Metropolis. The throughline is overdispersion: on equidispersed data MLE, Bayes, PyMC, and R glm coincide exactly (Bernstein–von Mises), but on overdispersed data the Poisson keeps β roughly right while its standard errors run ~1.7× too small — and NB recovers the dispersion and restores calibrated inference. Applied to the Epil epilepsy trial (Thall & Vail 1990; Pearson dispersion ≈4.71), where Poisson reports no treatment effect but NB finds a 21% seizure reduction (RR 0.79) — a gap traced to a single influential high-count patient that NB down-weights. Validated across four engines (from-scratch MLE & RW-Metropolis, PyMC, R glm/MASS::glm.nb), with the correlated repeated measures motivating a hierarchical-count follow-up (Breslow–Clayton 1993).

View example →

Bayesian Hierarchical Poisson

The hierarchical extension of count regression — a Poisson GLMM with group random effects on the log-rate (log μi = xi'β + bgi), a log-normal mixing that absorbs within-group correlation and overdispersion. Implemented from scratch via Metropolis-within-Gibbs (no Pólya–Gamma for Poisson), across three applications spanning the conjugacy spectrum: Epil (normal random intercept, non-conjugate) — where adding a patient random effect for the 4 correlated visits overturns the single-level treatment conclusion, pushing the progabide effect onto the significance boundary (the classic Breslow–Clayton pseudo-replication lesson); Pumps (gamma rate, conjugate) — an almost-pure-Gibbs sampler that is the explicit-random-effects form of the Negative Binomial; and Rugby (two crossed attack/defence effects) — recovering the 2014 Six Nations standings from 15 matches. Each application is cross-checked three ways — from-scratch sampler, PyMC NUTS, and R (lme4::glmer or the NB marginal).

View example →

Bayesian Hierarchical Binomial

A binomial GLMM — logistic regression on grouped counts with a group random effect that absorbs over-dispersion — the binomial twin of the hierarchical Poisson (Epil), completing the hierarchical-GLM grid (Gaussian / Poisson / binomial). Grouped binomial counts routinely vary more than a single logistic curve allows; a per-group random effect bi on the logit soaks up that extra-binomial spread — the logistic-scale analogue of the Negative Binomial's gamma mixing. Implemented from scratch via the same Metropolis-within-Gibbs as the Poisson GLMM, binomial likelihood swapped in. Three applications: Seeds (BUGS; 21 plates, 2×2 factorial) — over-dispersion in a designed experiment (the Breslow–Clayton interval-widening point); Surgical (BUGS; 12 hospitals) — the intercept-only "league table" problem, where partial pooling stabilises uneven-volume mortality rates (a raw 0/47 = 0% pulled to ~6%) and shows the ranking is genuinely uncertain; and Baseball (Efron–Morris) — James–Stein shrinkage two ways, contrasting the logit-normal GLMM with a conjugate beta-binomial (the binomial mirror of the gamma-Poisson/Pumps vs Poisson-GLMM/Epil conjugacy split). Cross-checked against PyMC and R (lme4::glmer, VGAM).

View example →

Bayesian Zero-Inflated Count Regression

A mixture count model for data with far more zeros than any Poisson can produce — zero-inflated Poisson (ZIP) and Negative Binomial (ZINB) — separating structural zeros (never at risk) from sampling zeros (at risk but caught none). Two linked regressions (a log-link count model and a logit zero-inflation model) are fit from scratch by a data-augmentation Gibbs sampler: drawing a latent regime indicator si decouples the awkward mixture into two ordinary GLMs — a logistic regression and a count regression, reusing the logit and Poisson/NB machinery from earlier examples. Applied to the UCLA/PyMC fish example (250 park groups, 57% zeros, variance ≈40× the mean): the data demand zero-inflation, and ZINB absorbs both the excess zeros and the overdispersion (r ≈ 0.35). Children roughly halve the catch, a camper raises it ~2.3×. Cross-checked against PyMC (built-in zero-inflated likelihoods) and R pscl::zeroinfl.

View example →

Bayesian Hierarchical Spatial Poisson Model

The spatial extension of the hierarchical Poisson — the classic Besag–York–Mollié (BYM) disease-mapping model (Clayton & Kaldor 1987; the WinBUGS "Lip" example), fit from scratch by Metropolis-within-Gibbs. Each area carries two random effects: an unstructured term θi and a structured spatial term φ with an intrinsic CAR prior that pulls each district toward the average of its map neighbours. Where the earlier hierarchical-Poisson models pooled toward a global mean, the ICAR prior is "pooling with a map" — borrowing strength from adjacent areas. Applied to Scotland lip cancer (56 districts): outdoor work raises risk (RR ≈ 1.4 per +10% agriculture/fishing/forestry), and the variation is almost entirely spatial (σφ ≫ σθ) — turning a noisy raw SMR map into a coherent north-vs-central-belt risk surface. Cross-checked against PyMC (pm.ICAR) and R (CARBayes::S.CARbym).

View example →