# GLM: Negative Binomial Regression¶

:

import re

import arviz as az
import bambi as bmb
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import pymc3 as pm
import seaborn as sns

from scipy import stats

print(f"Running on PyMC3 v{pm.__version__}")

Running on PyMC3 v3.11.2

:

RANDOM_SEED = 8927
rng = np.random.default_rng(RANDOM_SEED)

%config InlineBackend.figure_format = 'retina'
az.style.use("arviz-darkgrid")


This notebook demos negative binomial regression using the bambi library. It closely follows the GLM Poisson regression example by Jonathan Sedar (which is in turn inspired by a project by Ian Osvald) except the data here is negative binomially distributed instead of Poisson distributed.

Negative binomial regression is used to model count data for which the variance is higher than the mean. The negative binomial distribution can be thought of as a Poisson distribution whose rate parameter is gamma distributed, so that rate parameter can be adjusted to account for the increased variance.

## Generate Data¶

As in the Poisson regression example, we assume that sneezing occurs at some baseline rate, and that consuming alcohol, not taking antihistamines, or doing both, increase its frequency.

### Poisson Data¶

First, let’s look at some Poisson distributed data from the Poisson regression example.

:

# Mean Poisson values
theta_noalcohol_meds = 1  # no alcohol, took an antihist
theta_alcohol_meds = 3  # alcohol, took an antihist
theta_noalcohol_nomeds = 6  # no alcohol, no antihist
theta_alcohol_nomeds = 36  # alcohol, no antihist

# Create samples
q = 1000
df_pois = pd.DataFrame(
{
"nsneeze": np.concatenate(
(
rng.poisson(theta_noalcohol_meds, q),
rng.poisson(theta_alcohol_meds, q),
rng.poisson(theta_noalcohol_nomeds, q),
rng.poisson(theta_alcohol_nomeds, q),
)
),
"alcohol": np.concatenate(
(
np.repeat(False, q),
np.repeat(True, q),
np.repeat(False, q),
np.repeat(True, q),
)
),
"nomeds": np.concatenate(
(
np.repeat(False, q),
np.repeat(False, q),
np.repeat(True, q),
np.repeat(True, q),
)
),
}
)

:

df_pois.groupby(["nomeds", "alcohol"])["nsneeze"].agg(["mean", "var"])

:

mean var
nomeds alcohol
False False 1.047 1.127919
True 2.986 2.960765
True False 5.981 6.218858
True 35.929 36.064023

Since the mean and variance of a Poisson distributed random variable are equal, the sample means and variances are very close.

### Negative Binomial Data¶

Now, suppose every subject in the dataset had the flu, increasing the variance of their sneezing (and causing an unfortunate few to sneeze over 70 times a day). If the mean number of sneezes stays the same but variance increases, the data might follow a negative binomial distribution.

:

# Gamma shape parameter
alpha = 10

def get_nb_vals(mu, alpha, size):
"""Generate negative binomially distributed samples by
drawing a sample from a gamma distribution with mean mu and
shape parameter alpha', then drawing from a Poisson
distribution whose rate parameter is given by the sampled
gamma variable.

"""

g = stats.gamma.rvs(alpha, scale=mu / alpha, size=size)
return stats.poisson.rvs(g)

# Create samples
n = 1000
df = pd.DataFrame(
{
"nsneeze": np.concatenate(
(
get_nb_vals(theta_noalcohol_meds, alpha, n),
get_nb_vals(theta_alcohol_meds, alpha, n),
get_nb_vals(theta_noalcohol_nomeds, alpha, n),
get_nb_vals(theta_alcohol_nomeds, alpha, n),
)
),
"alcohol": np.concatenate(
(
np.repeat(False, n),
np.repeat(True, n),
np.repeat(False, n),
np.repeat(True, n),
)
),
"nomeds": np.concatenate(
(
np.repeat(False, n),
np.repeat(False, n),
np.repeat(True, n),
np.repeat(True, n),
)
),
}
)

:

df.groupby(["nomeds", "alcohol"])["nsneeze"].agg(["mean", "var"])

:

mean var
nomeds alcohol
False False 0.986 1.114919
True 2.970 3.660761
True False 5.870 8.703804
True 35.979 163.634193

As in the Poisson regression example, we see that drinking alcohol and/or not taking antihistamines increase the sneezing rate to varying degrees. Unlike in that example, for each combination of alcohol and nomeds, the variance of nsneeze is higher than the mean. This suggests that a Poisson distribution would be a poor fit for the data since the mean and variance of a Poisson distribution are equal.

## Visualize the Data¶

:

g = sns.catplot(x="nsneeze", row="nomeds", col="alcohol", data=df, kind="count", aspect=1.5)

# Make x-axis ticklabels less crowded
ax = g.axes[1, 0]
labels = range(len(ax.get_xticklabels(which="both")))
ax.set_xticks(labels[::5])
ax.set_xticklabels(labels[::5]);

/home/ada/.local/lib/python3.8/site-packages/seaborn/axisgrid.py:64: UserWarning: This figure was using constrained_layout==True, but that is incompatible with subplots_adjust and or tight_layout: setting constrained_layout==False.
self.fig.tight_layout(*args, **kwargs) ## Create GLM Model¶

:

fml = "nsneeze ~ alcohol + nomeds + alcohol:nomeds"

model = bmb.Model(fml, df, family="negativebinomial")
trace = model.fit(draws=1000, tune=1000, cores=2)

Auto-assigning NUTS sampler...
Multiprocess sampling (2 chains in 2 jobs)
NUTS: [nsneeze_alpha, alcohol:nomeds, nomeds, alcohol, Intercept]

100.00% [4000/4000 00:21<00:00 Sampling 2 chains, 0 divergences]
Sampling 2 chains for 1_000 tune and 1_000 draw iterations (2_000 + 2_000 draws total) took 22 seconds.
The number of effective samples is smaller than 25% for some parameters.


## View Results¶

:

az.plot_trace(trace); :

# Transform coefficients to recover parameter values
az.summary(np.exp(trace.posterior), kind="stats", var_names="~nsneeze_alpha")

:

mean sd hdi_3% hdi_97%
Intercept 0.987 0.034 0.922 1.049
alcohol 3.015 0.120 2.806 3.254
nomeds 5.954 0.228 5.513 6.379
alcohol:nomeds 2.037 0.091 1.871 2.219

The mean values are close to the values we specified when generating the data: - The base rate is a constant 1. - Drinking alcohol triples the base rate. - Not taking antihistamines increases the base rate by 6 times. - Drinking alcohol and not taking antihistamines doubles the rate that would be expected if their rates were independent. If they were independent, then doing both would increase the base rate by 3*6=18 times, but instead the base rate is increased by 3*6*2=36 times.

Finally, the mean of nsneeze_alpha is also quite close to its actual value of 10.

See also, bambi's negative binomial example <https://bambinos.github.io/bambi/master/notebooks/negative_binomial.html>__ for further reference.

:

%load_ext watermark
%watermark -n -u -v -iv -w -p theano,xarray

Last updated: Mon Aug 02 2021

Python implementation: CPython
Python version       : 3.8.10
IPython version      : 7.25.0

theano: 1.1.2
xarray: 0.17.0

arviz     : 0.11.2
re        : 2.2.1
numpy     : 1.21.0
pandas    : 1.2.1
bambi     : 0.5.0
seaborn   : 0.11.1
pymc3     : 3.11.2
scipy     : 1.6.0
matplotlib: 3.3.4

Watermark: 2.2.0

`