Statistical modeling with Python · Lesson 14 of 16
Poisson regression for count data in Python
Model counts with a Poisson GLM in statsmodels: rate ratios, exposure and offsets for different time periods, predictions and the overdispersion check.
Some outcomes are counts: visits to a doctor, accidents at a crossing, complaints per shop. They are whole numbers, never negative, and often small. Linear regression can predict −1.3 visits; Poisson regression, a GLM with a Poisson family and a log link, cannot.
The data: 80 patients of a clinic, with age, whether they smoke, whether they have a chronic illness (1 = yes), how many months they have been registered, and how many visits they made in that time.
import numpy as np
import pandas as pd
import statsmodels.api as sm
import statsmodels.formula.api as smf
df = pd.read_csv("clinic.csv")
print(df.head())
print(f"mean visits: {df['visits'].mean():.2f}, variance: {df['visits'].var():.2f}")
df["per_month"] = df["visits"] / df["months"]
print(df.groupby("chronic")["per_month"].mean().round(3))age smoker chronic months visits 0 77 yes 0 8 11 1 21 yes 1 4 3 2 73 yes 0 6 4 3 42 no 0 3 1 4 29 yes 1 11 13 mean visits: 5.56, variance: 21.46 chronic 0 0.625 1 1.069 Name: per_month, dtype: float64
Exposure: counts over different periods
A patient registered for 12 months has more time to visit than one registered for 3. What we really model is the rate: visits per month. Pass the time as exposure=df["months"]; statsmodels then adds log(months) to the model with a fixed coefficient of 1 (an offset). The same thing written by hand is offset=np.log(df["months"]).
import numpy as np
import pandas as pd
import statsmodels.api as sm
import statsmodels.formula.api as smf
df = pd.read_csv("clinic.csv")
model = smf.glm("visits ~ age + C(smoker) + chronic", data=df,
family=sm.families.Poisson(), exposure=df["months"]).fit()
print(model.params.round(4))
def show_p(p):
return "< 0.001" if p < 0.001 else f"{p:.3f}"
for name, p in model.pvalues.items():
print(f"{name:<17} p {show_p(p)}")Intercept -1.4675 C(smoker)[T.yes] 0.2418 age 0.0174 chronic 0.6883 dtype: float64 Intercept p < 0.001 C(smoker)[T.yes] p 0.030 age p < 0.001 chronic p < 0.001
How to read the coefficients. With a log link, np.exp(coefficient) is a rate ratio (also called an incidence rate ratio): the factor by which the expected count is multiplied for one more unit of the predictor, others fixed.
import numpy as np
import pandas as pd
import statsmodels.api as sm
import statsmodels.formula.api as smf
df = pd.read_csv("clinic.csv")
model = smf.glm("visits ~ age + C(smoker) + chronic", data=df,
family=sm.families.Poisson(), exposure=df["months"]).fit()
table = pd.DataFrame({
"rate_ratio": np.exp(model.params),
"ci_low": np.exp(model.conf_int()[0]),
"ci_high": np.exp(model.conf_int()[1]),
})
print(table.round(3))rate_ratio ci_low ci_high Intercept 0.230 0.161 0.329 C(smoker)[T.yes] 1.274 1.023 1.585 age 1.018 1.012 1.023 chronic 1.990 1.642 2.412
- chronic, 1.99: patients with a chronic illness visit about twice as often (1.99 times the rate), at the same age and smoking status.
- C(smoker)[T.yes], 1.27: smokers visit about 27% more often than non-smokers.
- age, 1.018: each extra year adds about 1.8% to the visit rate. Effects multiply: ten years means 1.018 ** 10 ≈ 1.19, that is about 19% more.
- Intercept: the rate (visits per month) for a non-smoker aged 0 without chronic illness; only useful as an anchor.
Predicting counts. Predict for new patients, giving their exposure too. With exposure=12 you get the expected visits in a year.
import numpy as np
import pandas as pd
import statsmodels.api as sm
import statsmodels.formula.api as smf
df = pd.read_csv("clinic.csv")
model = smf.glm("visits ~ age + C(smoker) + chronic", data=df,
family=sm.families.Poisson(), exposure=df["months"]).fit()
new = pd.DataFrame({"age": [30, 30, 70], "smoker": ["no", "yes", "no"],
"chronic": [0, 0, 1]})
new["visits_year"] = model.predict(new, exposure=np.full(len(new), 12)).round(2)
print(new)age smoker chronic visits_year 0 30 no 0 4.67 1 30 yes 0 5.94 2 70 no 1 18.65
Check for overdispersion
The Poisson distribution assumes the variance equals the mean. Real counts often vary more (overdispersion): a few people visit very often. Then the standard errors are too small and p-values look better than they are. The raw variance above (21.5 against a mean of 5.6) is not the test: patients differ in months, age and illness. What counts is the spread left after the model: the Pearson chi-square divided by the residual degrees of freedom should be close to 1.
import numpy as np
import pandas as pd
import statsmodels.api as sm
import statsmodels.formula.api as smf
df = pd.read_csv("clinic.csv")
model = smf.glm("visits ~ age + C(smoker) + chronic", data=df,
family=sm.families.Poisson(), exposure=df["months"]).fit()
ratio = model.pearson_chi2 / model.df_resid
print(f"dispersion ratio: {ratio:.2f}")
print("overdispersed" if ratio > 1.5 else "Poisson looks fine")dispersion ratio: 0.85 Poisson looks fine
Here the ratio is about 0.85, close to 1, so the Poisson model is fine. If it were 2 or more, the usual fixes are a negative binomial model, which adds a parameter for the extra spread, or keeping the Poisson coefficients and scaling the standard errors with fit(scale="X2").
nb = smf.negativebinomial("visits ~ age + C(smoker) + chronic", data=df,
exposure=df["months"]).fit(disp=0)
print(nb.params.round(4)) # the last line, alpha, measures the extra spreadNegative binomial regression for overdispersed counts. alpha near 0 means the Poisson model was enough.
✎ Exercise
Fit a Poisson model of visits on chronic only, still with exposure=df["months"], and print the rate ratio for chronic with 3 decimals.
Hint: smf.glm("visits ~ chronic", data=df, family=sm.families.Poisson(), exposure=df["months"]).fit(), then np.exp of the coefficient.
import numpy as np
import pandas as pd
import statsmodels.api as sm
import statsmodels.formula.api as smf
df = pd.read_csv("clinic.csv")
# your code here
Expected output:
rate ratio for chronic: 1.839
Show a solution
import numpy as np
import pandas as pd
import statsmodels.api as sm
import statsmodels.formula.api as smf
df = pd.read_csv("clinic.csv")
model = smf.glm("visits ~ chronic", data=df, family=sm.families.Poisson(),
exposure=df["months"]).fit()
print(f"rate ratio for chronic: {np.exp(model.params['chronic']):.3f}")rate ratio for chronic: 1.839
Check yourself
1. A Poisson model gives a rate ratio of 1.5 for smokers. What does it mean?
With a log link, exponentiated coefficients multiply the expected count.
2. Why give exposure=df["months"]?
Exposure adds log(time) as an offset, so the coefficients describe rates.
3. The Pearson chi-square / df ratio is 3.2. What do you do?
A ratio far above 1 means more spread than Poisson allows, so standard errors are too small.