Count Regression with Variable Exposure

Code
%config InlineBackend.figure_format = "retina"
%config InlineBackend.print_figure_kwargs = {'bbox_inches': None}

import arviz as az
import bambi as bmb
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd

plt.style.use("bambi.mplstyle")
seed = sum(map(ord, "Count regression with Variable Exposure"))
rng = np.random.default_rng(seed)

This example is based on the “Roaches” example from Regression and Other Stories by Gelman, Hill, and Vehtari. The example is a count regression model with an offset term.

The data is the number of roaches caught in 262 apartments. Some pest control treatment was applied to 158 (treatment=1) of the apartments, and 104 apartments received no treatment (treatment=0). The other columns in the data are:

roaches = pd.read_csv("data/roaches.csv", index_col=0)
# rescale
roaches["roach1"] = roaches["roach1"] / 100
roaches.head()
y roach1 treatment senior exposure2
1 153 3.0800 1 0 0.800000
2 127 3.3125 1 0 0.600000
3 7 0.0167 1 0 1.000000
4 7 0.0300 1 0 1.000000
5 0 0.0200 1 0 1.142857

Poisson regression

One way to model this is to say that there is some rate of roaches per trap-day , and that the number of roaches caught is a Poisson random variable with a rate that is proportional to the number of trap-days (the exposure). That is:

\begin{align*} y_i &\sim \text{Poisson}(\text{exposure2}_i \times \rho_i) \\ \log(\rho_i) &= \beta_0 + \beta_1 \text{treatment}_i + \beta_2 \text{roach1}_i + \beta_3 \text{senior}_i \end{align*}

With a little algebra, we can rewrite this as a generalized linear model:

\begin{align*} y_i &\sim \text{Poisson}(\lambda_i) \\ \log(\lambda_i) &= \beta_0 + \beta_1 \text{treatment}_i + \beta_2 \text{roach1}_i + \beta_3 \text{senior}_i + \log(\text{exposure2}_i) \end{align*}

However, we don’t want to estimate a coefficient for \log(\text{exposure2}), we want to simply add it as an offset. In bambi we do this by using the offset function in the formula to specify that a term should not be multiplied by a coefficient to estimate and simply added. The formula for the model is then:

"y ~ roach1 + treatment + senior + offset(log(exposure2))"

If you are familiar with R this offset term is the same as the offset term in the glm function.

model_1 = bmb.Model(
    "y ~ roach1 + treatment  + senior + offset(log(exposure2))",
    family="poisson",
    data=roaches,
)
idata_1 = model_1.fit(random_seed=seed)
NUTS[nutpie]: [roach1, treatment, senior, Intercept_centered]

az.summary(idata_1, var_names=["~Intercept_centered"])
mean sd eti89_lb eti89_ub ess_bulk ess_tail r_hat mcse_mean mcse_sd
roach1 0.6983 0.0088 0.68 0.71 3257 3218 1.00 0.00015 0.00011
treatment -0.5175 0.0249 -0.56 -0.48 3899 3178 1.00 0.0004 0.00029
senior -0.379 0.0333 -0.43 -0.33 3806 3087 1.00 0.00054 0.00039
Intercept 3.0891 0.0213 3.1 3.1 3779 3265 1.00 0.00035 0.00025

The sampling seems to have gone well based on ess and r_hat. If this were a real analysis one would also need to check priors, trace plots and other diagnostics. However, let’s see if the model predicts the distribution of roaches (y) observed. We can do this by looking at the posterior predictive distribution for the model. We plot the log of y to make the results easier to see.

def plot_log_posterior_ppc(model, idata):
    # plot posterior predictive check
    model.predict(idata, kind="response", inplace=True)
    var_name = "log(y + 1)"
    # there is probably a better way
    idata.posterior_predictive[var_name] = np.log(idata.posterior_predictive["y"] + 1)
    idata.observed_data[var_name] = np.log(idata.observed_data["y"] + 1)
    return az.plot_ppc_dist(idata, var_names=[var_name])
plot_log_posterior_ppc(model_1, idata_1);

It appears that we are drastically under predicting the number of apartments with a small number of roaches. This suggests creating a test statistic measuring the fraction of zeros, both in the observed data and in the simulated replications (posterior predictions). We can then use this to check the model fit.

# check number of zeros in y
def check_zeros(idata):
    # flatten over chains:
    sampled_zeros = (
        (idata.posterior_predictive["y"] == 0).mean(("__obs__")).values.flatten()
    )
    print(f"Fraction of zeros in the observed data: {np.mean(roaches['y']==0)}")
    print(
        f"Fraction of zeros in the posterior predictive check: {np.mean(sampled_zeros)}"
    )
    print(f" 80% CI: {np.percentile(sampled_zeros, [10, 90])}")


check_zeros(idata_1)
Fraction of zeros in the observed data: 0.35877862595419846
Fraction of zeros in the posterior predictive check: 0.0006793893129770992
 80% CI: [0.         0.00381679]

The Poisson model here does not succeed in reproducing the observed fraction of zeros. In the data we have about 36% zeros, while in the replications we almost always have no zeros or very few. Gelman, Hill, and Vehtari suggest we try an overdispersed and more flexible model like the negative binomial.

Negative Binomial Fit

model_2 = bmb.Model(
    "y ~ roach1 + treatment  + senior + offset(log(exposure2))",
    family="negativebinomial",
    data=roaches,
)
idata_2 = model_2.fit(random_seed=seed)
NUTS[nutpie]: [alpha, roach1, treatment, senior, Intercept_centered]

az.summary(idata_2)
mean sd eti89_lb eti89_ub ess_bulk ess_tail r_hat mcse_mean mcse_sd
roach1 1.322 0.252 0.94 1.7 5016 2971 1.00 0.0037 0.0026
treatment -0.787 0.244 -1.2 -0.4 5245 3226 1.00 0.0034 0.0024
senior -0.323 0.262 -0.75 0.1 5306 3538 1.00 0.0036 0.0026
Intercept_centered 2.834 0.121 2.6 3 5256 3510 1.00 0.0017 0.0012
alpha 0.2723 0.025 0.23 0.31 5428 3265 1.00 0.00034 0.00025
Intercept 2.85 0.235 2.5 3.2 4518 3372 1.00 0.0035 0.0025
plot_log_posterior_ppc(model_2, idata_2);

check_zeros(idata_2)
Fraction of zeros in the observed data: 0.35877862595419846
Fraction of zeros in the posterior predictive check: 0.3381832061068702
 80% CI: [0.29007634 0.38931298]
def plot_zeros(ax, idata, model_label, **kwargs):
    data_zeros = np.mean(roaches["y"] == 0)
    # flatten over chains:
    sampled_zeros = (
        (idata.posterior_predictive["y"] == 0).mean(("__obs__")).values.flatten()
    )
    ax.hist(sampled_zeros, alpha=0.5, **kwargs)
    ax.axvline(data_zeros, color="red", linestyle="--")
    ax.set_xlabel("Fraction of zeros")
    ax.set_title(f"Model: {model_label}")
    ax.yaxis.set_visible(False)
    ax.set_facecolor("white")
    return ax


fig, ax = plt.subplots(1, 2, figsize=(8, 4))
plot_zeros(
    ax[0], idata_1, "Poisson", bins=2
)  # use 2 bins to make it more clear. Almost no zeros.
plot_zeros(ax[1], idata_2, "Negative Binomial", bins=30)

fig.legend(
    ["Observed data", "Posterior predictive"],
    loc="center left",
    bbox_to_anchor=(0.05, 0.8),
);

The negative binomial distribution fit works much better, predicting the number of zeros consistent with the observed data.

Regression and Other Stories introduces a further improvement by introducing a zero-inflated regression later in the chapter, but I will not persue that here, after all the point of this example is to illustrate the use of offsets.

PyMC equivalent model

The model behind the scenes looks like this for the Poission model.

pymc_model = model_1.backend
pymc_model.model

\begin{array}{rcl} \text{roach1\_data} &= &\operatorname{Data}(\text{<shared>})\\\text{treatment\_data} &= &\operatorname{Data}(\text{<shared>})\\\text{senior\_data} &= &\operatorname{Data}(\text{<shared>})\\\text{offset(log(exposure2))\_data} &= &\operatorname{Data}(\text{<shared>})\\\text{y\_data} &= &\operatorname{Data}(\text{<shared>})\\\text{roach1} &\sim & \operatorname{Normal}(0,~3.33)\\\text{treatment} &\sim & \operatorname{Normal}(0,~5.11)\\\text{senior} &\sim & \operatorname{Normal}(0,~5.43)\\\text{Intercept\_centered} &\sim & \operatorname{Normal}(0,~4.52)\\\text{Intercept} &= &\operatorname{Deterministic}(f(\text{Intercept\_centered},~\text{senior},~\text{treatment},~\text{roach1}))\\\text{mu} &= &\operatorname{Deterministic}(f(\text{offset(log(exposure2))\_data},~\text{Intercept\_centered},~\text{senior},~\text{treatment},~\text{roach1},~\text{senior\_data},~\text{treatment\_data},~\text{roach1\_data}))\\\text{y} &\sim & \operatorname{Poisson}(\text{mu}) \end{array}

Let’s look at the equivalent (Poisson) model in PYMC:

import pymc as pm

with pm.Model() as model_pymc:
    # priors
    alpha = pm.Normal("Intercept", mu=0, sigma=4.5)
    beta_roach1 = pm.Normal("beta_roach1", mu=0, sigma=3.3)
    beta_treatment = pm.Normal("beta_treatment", mu=0, sigma=5.11)
    beta_senior = pm.Normal("beta_senior", mu=0, sigma=5.43)

    # likelihood
    # see no beta for exposure2
    mu = pm.math.exp(
        alpha
        + beta_roach1 * roaches["roach1"]
        + beta_treatment * roaches["treatment"]
        + beta_senior * roaches["senior"]
        + pm.math.log(roaches["exposure2"])
    )

    y = pm.Poisson("y", mu=mu, observed=roaches["y"])

    idata_pymc = pm.sample(1000)

az.summary(idata_pymc)
NUTS[nutpie]: [Intercept, beta_roach1, beta_treatment, beta_senior]

mean sd eti89_lb eti89_ub ess_bulk ess_tail r_hat mcse_mean mcse_sd
Intercept 3.0892 0.0208 3.1 3.1 2357 2530 1.00 0.00043 0.00029
beta_roach1 0.6983 0.0089 0.68 0.71 2382 2744 1.00 0.00018 0.00012
beta_treatment -0.5165 0.0239 -0.55 -0.48 2798 2492 1.00 0.00045 0.00031
beta_senior -0.38 0.0331 -0.43 -0.33 2820 2824 1.00 0.00062 0.00044

In this model (model_pymc) we have the equivalent Poisson regression with everything explicit to illustrate what the ‘offset’ function is doing. It simply makes it possible to express a term like this in the formulae string in a bambi model.

%load_ext watermark
%watermark -n -u -v -iv -w
Last updated: Sat, 29 Aug 2026

Python implementation: CPython
Python version       : 3.14.7
IPython version      : 9.16.1

arviz     : 1.3.0
bambi     : 0.20.1.dev78+g69d4473ea.d20260829
matplotlib: 3.11.1
numpy     : 2.4.6
pandas    : 2.3.3
pymc      : 6.3.1

Watermark: 2.6.0