Skip to content

Count Regression, Poisson & Negative Binomial

Across 120 sequenced tumors, does the treated arm carry more somatic variants than the control arm? The outcome is a count, so the answer is a rate ratio. The samples were also sequenced to unequal depth, and the model has to account for that before it says anything about biology. This page fits a Poisson model, measures how far it understates its uncertainty, and replaces it with a negative binomial model, in R and Python.

Use count regression when the outcome is a non-negative integer that comes from counting: variants per sample, reads per gene, colonies per plate, cells per field, adverse events per patient-year.

Start with the Poisson model. It assumes that the variance equals the mean. Biological counts usually vary more than that, so check the assumption after the fit. When the variance exceeds the mean, move to the negative binomial model, which adds a dispersion parameter and widens the intervals to match.

Do not run a t-test on counts that are small or skewed. Do not take logs to force normality when the counts include zeros, because log(0) is undefined and log(x + 1) distorts the low counts.

Download variant_counts.csv into your working directory. The invented table has 120 rows, one per tumor sample, and four columns: sample_id, arm, coverage and n_variants. There are 60 control and 60 treated samples. coverage is the sequencing depth of the sample and n_variants is its somatic variant count.

The counts come from a simulation with known answers. They follow a negative binomial distribution with a dispersion parameter theta of 4, and the log rate ratio of treated against control is 0.45. Coverage varies about threefold across the cohort, in both arms alike. A deeper sample finds more variants for no biological reason.

library(MASS)
library(ggplot2)
tumors <- read.csv("variant_counts.csv")
tumors$arm <- factor(tumors$arm, levels = c("control", "treated"))
dir.create("outputs", showWarnings = FALSE)
#' Print the coefficient table of a count model.
#'
#' @param fit A model from glm() or glm.nb().
#' @return Invisibly, the coefficient matrix of the model.
PrintCoefficients <- function(fit) {
estimates <- coef(summary(fit))
cat(sprintf("%-11s %8s %7s %7s %8s\n", "term", "estimate", "SE", "z", "p"))
cat(sprintf("%-11s %8.4f %7.4f %7.2f %8.2g\n", rownames(estimates),
estimates[, 1], estimates[, 2], estimates[, 3],
estimates[, 4]), sep = "")
invisible(estimates)
}
cat(sprintf("Coverage from %.1f to %.1f\n", min(tumors$coverage),
max(tumors$coverage)))
for (arm in levels(tumors$arm)) {
rows <- tumors[tumors$arm == arm, ]
cat(sprintf("%-8s n = %d, mean = %.2f, variance = %.2f, rate = %.4f\n",
arm, nrow(rows), mean(rows$n_variants), var(rows$n_variants),
sum(rows$n_variants) / sum(rows$coverage)))
}
Coverage from 30.1 to 89.4
control n = 60, mean = 16.60, variance = 131.57, rate = 0.2753
treated n = 60, mean = 25.62, variance = 358.27, rate = 0.4249

Coverage runs from 30.1 to 89.4. The treated arm has the higher mean count, 25.62 against 16.60. In the control arm the variance is 131.57 for a mean of 16.60, about eight times the mean. Part of that spread comes from coverage, so the raw variance alone does not show that a Poisson model fails.

The rate column divides the total variants of an arm by its total coverage. The control arm has 0.2753 variants per unit of coverage and the treated arm has 0.4249.

Coverage enters the model as an offset and not as an ordinary predictor. An offset is a term whose coefficient is fixed at 1. With log(coverage) as the offset, twice the depth means twice the expected count, and the other coefficients describe a rate per unit of coverage. R takes the offset inside the formula, and statsmodels takes it as an argument.

pois <- glm(n_variants ~ arm + offset(log(coverage)), family = poisson,
data = tumors)
PrintCoefficients(pois)
term estimate SE z p
(Intercept) -1.2899 0.0317 -40.71 0
armtreated 0.4340 0.0407 10.67 1.4e-26

The arm coefficient, armtreated in R and arm[T.treated] in statsmodels, is the log rate ratio of treated against control: 0.4340 with a standard error of 0.0407. The intercept is the log of the control rate, and exp(-1.2899) returns the 0.2753 of the first output. The p-value of 1.4e-26 rests on that standard error, so do not read it before the dispersion check.

The Poisson model assumes that the variance equals the mean. The check is the Pearson chi-squared statistic divided by the residual degrees of freedom. A ratio near 1 agrees with the assumption. A ratio well above 1 is overdispersion, and it means that every standard error in the Poisson table is too small.

pearson <- sum(residuals(pois, type = "pearson")^2)
dispersion <- pearson / df.residual(pois)
cat(sprintf("Pearson chi-squared = %.1f on %d df\n", pearson,
df.residual(pois)))
cat(sprintf("Dispersion = %.2f\n", dispersion))
Pearson chi-squared = 963.6 on 118 df
Dispersion = 8.17

The dispersion is 8.17. The counts vary about eight times more than the Poisson model allows, with coverage and arm already accounted for. The Poisson standard errors and p-values above cannot be used.

The negative binomial model keeps the same mean structure and the same offset. It adds one parameter, theta, and sets the variance to the mean plus the squared mean divided by theta. As theta grows, the model approaches the Poisson model. glm.nb() from MASS reports theta. statsmodels estimates alpha, which is 1 divided by theta, and lists it as a row of the coefficient table.

nb <- glm.nb(n_variants ~ arm + offset(log(coverage)), data = tumors)
PrintCoefficients(nb)
cat(sprintf("theta = %.2f (SE %.2f)\n", nb$theta, nb$SE.theta))
term estimate SE z p
(Intercept) -1.2941 0.0737 -17.55 6e-69
armtreated 0.4352 0.1026 4.24 2.2e-05
theta = 3.80 (SE 0.57)

The log rate ratio barely moves, from 0.4340 to 0.4352, because the Poisson estimate of a rate ratio stays consistent under overdispersion. The standard error is what changes, from 0.0407 to 0.1026. The z statistic falls from 10.67 to 4.24, and the p-value rises from 1.4e-26 to 2.2e-05. The Poisson p-value came from a standard error that was too small, and it overstated the evidence against a rate ratio of 1 by 21 orders of magnitude.

The estimated theta is 3.80, against the 4 of the simulation, and the estimated log rate ratio of 0.4352 is close to the simulated 0.45. glm.nb() computes the standard errors of the coefficients with theta held at its estimate, and statsmodels computes them together with alpha. The two tabs differ in the last digit of the intercept’s z statistic for that reason.

Exponentiate the coefficient of the arm to get the rate ratio, and exponentiate the limits of its confidence interval. Both tabs use the Wald interval, which is confint.default() in R and conf_int() in statsmodels. The logistic regression page compares the Wald interval with the profile likelihood interval.

models <- list("Poisson" = pois, "Negative binomial" = nb)
for (name in names(models)) {
wald_ci <- exp(confint.default(models[[name]])["armtreated", ])
cat(sprintf("%-17s rate ratio %.3f, 95%% CI %.3f to %.3f\n", name,
exp(coef(models[[name]])[["armtreated"]]), wald_ci[1],
wald_ci[2]))
}
se_ratio <- coef(summary(nb))["armtreated", "Std. Error"] /
coef(summary(pois))["armtreated", "Std. Error"]
cat(sprintf("Standard error ratio = %.2f\n", se_ratio))
Poisson rate ratio 1.543, 95% CI 1.425 to 1.671
Negative binomial rate ratio 1.545, 95% CI 1.264 to 1.889
Standard error ratio = 2.52

Report the rate ratio and not its log. Treated tumors carry 1.545 times the variants of control tumors per unit of coverage, about 55% more. The 95% interval runs from 1.264 to 1.889, so increases from 26% to 89% are compatible with the data.

The Poisson interval, 1.425 to 1.671, claims a precision that the counts do not support. The negative binomial standard error is 2.52 times the Poisson standard error.

Both models are fitted by maximum likelihood on the same counts, so their AIC values are comparable. The lower value marks the model that describes the data better after a penalty for each parameter.

cat(sprintf("AIC: Poisson %.1f, negative binomial %.1f, difference %.1f\n",
AIC(pois), AIC(nb), AIC(pois) - AIC(nb)))
AIC: Poisson 1404.1, negative binomial 900.0, difference 504.1

The AIC falls from 1404.1 to 900.0, a difference of 504.1 for one extra parameter. The negative binomial model describes these counts far better than the Poisson model.

A figure shows the same failure without a test statistic. Sort the samples into five bins by fitted mean, and compute the mean and the variance of the observed counts in each bin. Under the Poisson model the variance equals the mean. Under the negative binomial model it follows the mean plus the squared mean divided by theta.

In statsmodels, take the fitted means from nb.predict(). The fittedvalues attribute of this model holds the linear predictor without the offset, and it cannot sort the samples by expected count.

tumors$fitted <- fitted(nb)
breaks <- quantile(tumors$fitted, probs = seq(0, 1, 0.2))
tumors$bin <- cut(tumors$fitted, breaks = breaks, include.lowest = TRUE)
binned <- data.frame(
mean = as.vector(tapply(tumors$n_variants, tumors$bin, mean)),
variance = as.vector(tapply(tumors$n_variants, tumors$bin, var))
)
binned$ratio <- binned$variance / binned$mean
binned$negative_binomial <- binned$mean + binned$mean^2 / nb$theta
print(round(binned, 1), row.names = FALSE)
model_lines <- data.frame(
mean = seq(min(binned$mean), max(binned$mean), length.out = 100)
)
model_lines$poisson <- model_lines$mean
model_lines$negative_binomial <- model_lines$mean +
model_lines$mean^2 / nb$theta
line_colors <- c("Poisson" = "#C1432B", "Negative binomial" = "#3B6DB3")
dispersion_plot <- ggplot(binned, aes(mean, variance)) +
geom_line(data = model_lines, aes(y = poisson, color = "Poisson"),
linewidth = 1) +
geom_line(data = model_lines,
aes(y = negative_binomial, color = "Negative binomial"),
linewidth = 1) +
geom_point(size = 3, color = "#1f4e5f") +
scale_color_manual(values = line_colors) +
labs(x = "Mean variants per sample in each bin",
y = "Variance of the counts", color = NULL) +
theme_minimal(base_size = 12) +
theme(legend.position = "bottom")
ggsave("outputs/dispersion-r.png", dispersion_plot, width = 5.6,
height = 4.4, dpi = 150, bg = "white")
mean variance ratio negative_binomial
11.3 24.7 2.2 44.8
16.5 149.3 9.0 88.1
19.0 143.3 7.5 114.3
26.2 155.1 5.9 207.4
32.5 601.0 18.5 309.4

Variance against mean for five bins of tumor samples, drawn with ggplot2. Every point lies above the Poisson line, and the points scatter around the negative binomial curve.

Every bin has a variance above its mean. The ratio column runs from 2.2 in the lowest bin to 18.5 in the highest, and under the Poisson model each ratio would be near 1.

The points scatter around the negative binomial curve and do not lie on it. Each bin holds 24 samples, a variance from 24 counts is imprecise, and the samples of one bin do not share one expected count. Five points cannot confirm the exact form of the negative binomial variance. They do show that the Poisson line is too low at every level of the mean.

  • The Poisson model never warns. It returns a clean table with standard errors that are far too small, and nothing in the output says that the assumption failed. Compute the dispersion after every Poisson fit.
  • An offset is not a covariate. With coverage as an ordinary predictor, the model estimates a coefficient for it, and the arm coefficient no longer describes a rate per unit of coverage. Use an offset when the count scales in proportion to the exposure.
  • RNA-seq tools use the negative binomial distribution for this reason. DESeq2 and edgeR model read counts with it, and much of each method concerns how to estimate the dispersion from few replicates.
  • Quasi-Poisson is the other common repair. It keeps the Poisson estimate and multiplies each standard error by the square root of the dispersion. It has no likelihood, so it gives no AIC to compare with another model.
  • A count outcome needs a count model, and its effect is a rate ratio.
  • After a Poisson fit, divide the Pearson chi-squared statistic by the residual degrees of freedom. A ratio well above 1 is overdispersion.
  • Overdispersion leaves the estimate almost unchanged and makes the Poisson standard error too small. Here the negative binomial standard error is 2.52 times the Poisson one.
  • An exposure such as sequencing depth belongs in an offset, with its coefficient fixed at 1.
  • The negative binomial model adds theta, and it approaches the Poisson model as theta grows.

Venables and Ripley, 2002, describe the MASS functions in Modern Applied Statistics with S.

The MASS negative binomial reference explains how glm.nb estimates theta and accepts an offset in the formula. The statsmodels count model guide lists the Poisson and negative binomial implementations used for the Python comparison.

The DESeq2 paper by Love, Huber, and Anders explains dispersion estimation for RNA sequencing counts. It provides context for count models with few replicates.