Poisson regression in Python: modelling how many times customers buy
TL;DR
Difficulty: Intermediate
Orders per customer are counts: whole numbers, a floor at zero, a variance that grows with the mean. Least squares gets them wrong.
- Build the count from cleaned orders (no refund rows, test or staff orders) on the shop's own clock, and give every customer an exposure.
- Fit a Poisson GLM with smf.glm and exposure=, read the incidence rate ratios, then check the Pearson dispersion.
- Above about 1.5, fit smf.negativebinomial, which estimates alpha. Never trust the GLM family's default alpha of 1.
- Sum the tail probabilities to see how many heavy buyers the model already expects before anyone builds a segment.
- Blend the model with each customer's own history for a ranking that beats both, and check it on a later period.
Orders, visits, tickets: most of what customers do is counted, and ordinary regression handles counts badly. This chapter builds the Marketing Analytics chapter's Poisson regression in Python, step by step, on data you generate yourself, from the order export to a scored customer list. The Edinburgh customer with seven orders gets a proper answer.
The customer who ordered seven times, now in code
Every December the same conversation happens at Northgate Hampers, the invented gift hamper shop in Leeds that Priya runs. Someone spots a customer in Edinburgh who has placed seven orders in two years, gets excited, and wants a VIP programme built around people like her. Her first hamper was a £75 gift for a colleague, she opens the emails, and she has never bought anything for herself. Is she remarkable, or is she what happens when a few thousand customers are counted for long enough?
That question, and the model that answers it, are explained in full in the Marketing Analytics chapter Poisson regression: modelling how many times customers do things. Read it for the concepts. This chapter builds it, line by line, in Python: the counts, the exposure offset, the Poisson model, the incidence rate ratios, the dispersion check, the negative binomial, the zero inflation question and the three lists that make the model worth having. The data is generated to resemble the example in that chapter, with the same 4,180 customers and the same drivers, so the numbers you get will be close to the ones you read there, not identical.
This chapter builds on statistical models in Python with statsmodels and scikit learn, where the formula interface and the idea of a fitted result object are introduced. If a regression table is new to you, read that first. If pandas is new, start at pandas Series and DataFrames.
If you only read one section
For the person who commissions this work and will never run the code, here is what matters, in the order it matters.
Ask how many stars the model already expects. In the generated Northgate data, 136 customers placed seven or more orders. A plain Poisson model says you should expect about 82 such customers by chance, which makes the other 54 look like a hidden segment. A negative binomial model, the one that fits this data, expects about 148. There is no hidden segment. There is ordinary variety among customers. One line of code turns "look at these heavy buyers" into "this is about what any shop of this size produces", and I think it is the most useful single check in this whole chapter.
Combine the model with each customer's own history. The model tells you what a customer like her should do. Her own orders tell you something about her. In the generated data, ranking customers by the model alone predicts the next six months worse than ranking them by past orders. Blending the two, with a formula the negative binomial hands you for free, beats both: the top tenth of customers ranked this way placed 770 of the next half year's 2,756 orders, against 706 for past orders alone and 634 for the model alone.
Insist on an exposure offset. Customers who joined two years ago have had four times as long to order as customers who joined six months ago. Without the offset, the model concludes that tenure causes loyalty, and in this data it would report every extra year as multiplying orders by 2.5.
Check the dispersion before believing any star in the table. The Poisson model's standard errors here are too small by a factor of 1.35. A regional effect that looks significant under the Poisson stops being significant once that is corrected.
Get three lists, not a model file. Expected orders per customer, surprises worth a human look, and the customers where a lever such as email engagement is worth most.
Before you start: the versions this chapter uses
This chapter is written for Python 3.14, released in October 2025, with pandas 3.0, NumPy 2.4, statsmodels 0.14.6 and SciPy 1.17, the versions current in March 2026.1 If you set up your environment as described in why Python for data analysis, and how to set it up, install them with:
pip install "pandas>=3.0" "numpy>=2.4" "statsmodels>=0.14.6" "scipy>=1.17"
Two things changed since the books most people learnt from. Wes McKinney's Python for Data Analysis, third edition, introduces statsmodels and its formula interface in chapter 12, written against pandas 1.4.2 The formula interface is unchanged in statsmodels 0.14 and still uses the Patsy formula language the book describes. pandas 3.0, released in January 2026, made two changes you will notice: text columns now get a dedicated string data type by default instead of the generic object type, and copy on write is the only behaviour, so a filtered table always behaves like a copy and chained assignment such as df[mask]["col"] = 1 no longer changes df.3 Everything below is written for that behaviour.
Example: checking your versions
import numpy as np
import pandas as pd
import statsmodels.api as sm
import statsmodels.formula.api as smf
from scipy import stats
print(pd.__version__, np.__version__, sm.__version__)
# 3.0.1 2.4.3 0.14.6
If your numbers are older, the code will mostly still run, but the outputs printed in the comments come from exactly these versions.
Step one: the count has to be built, not exported
A count model needs one row per customer with three things: the count, the time over which it was counted, and the drivers as they were known at the start. No shop exports that. You build it from the order export, and the order export lies in three predictable ways.
Refunds are rows of their own. Most shop exports write a refund as a second row with a negative total and the same order number. Count rows and a refunded order counts twice.
Test and staff orders sit in the same file. The developer's test order and the founder's own order for the office look exactly like customer orders. They are also, very often, the heaviest "customers" in the file, which is precisely where a count model is most sensitive.
Time is in UTC. The export stores order times in Coordinated Universal Time. Your counting window, a financial year from 1 April, say, is in the shop's own clock. An order placed at half past midnight on 1 April British Summer Time is stamped 23:30 on 31 March in UTC and falls into the wrong year.
None of these is exotic. Loading such exports is covered in loading business data into pandas, and the cleaning steps in cleaning data in pandas. What matters for this chapter is that every one of them changes the count, and the count is the thing the whole model explains.
Example: one customer, six rows, two orders
Here is a tiny slice of the Northgate export: one customer, Sam, plus a test order and a staff order. The question is how many orders Sam placed in the financial year from 1 April 2025.
export = pd.DataFrame({
"order_id": ["N1001", "N1002", "N1003", "N1003", "N1004", "N1005"],
"email": ["sam@example.com", "sam@example.com", "sam@example.com",
"sam@example.com", "test@northgatehampers.example",
"priya@northgatehampers.example"],
"created_at": pd.to_datetime([
"2025-03-31 23:30", "2025-11-30 19:02", "2026-02-14 08:15",
"2026-02-20 10:40", "2025-06-01 12:00", "2025-12-20 16:30"], utc=True),
"total": [42.0, 75.0, 58.0, -58.0, 1.0, 96.0],
})
# The naive count: every row for Sam inside the financial year, read in UTC
start, end = pd.Timestamp("2025-04-01", tz="UTC"), pd.Timestamp("2026-04-01", tz="UTC")
naive = export[(export["email"] == "sam@example.com")
& export["created_at"].between(start, end, inclusive="left")]
print("naive:", len(naive))
# naive: 3
Three. Now the honest version: drop refund rows, drop orders that were refunded, drop the shop's own addresses, and read the time on the shop's clock.
refunded = export.loc[export["total"] < 0, "order_id"]
kept = export[(export["total"] > 0) # refund rows out
& ~export["order_id"].isin(refunded) # refunded orders out
& ~export["email"].str.endswith("@northgatehampers.example")] # test and staff out
local = kept["created_at"].dt.tz_convert("Europe/London") # the shop's own clock
start_l = pd.Timestamp("2025-04-01", tz="Europe/London")
end_l = pd.Timestamp("2026-04-01", tz="Europe/London")
in_year = kept[local.between(start_l, end_l, inclusive="left")]
print("honest:", in_year.groupby("email")["order_id"].nunique().to_dict())
# honest: {'sam@example.com': 2}
Two. The naive count kept the February order that was refunded, counted its refund row as a third order, and lost the order placed just after midnight on 1 April. Multiply that by a few thousand customers and the tail of your distribution, the part a count model is most sensitive to, is made of bookkeeping. The aggregation itself, one row per customer, is the group by you met in group by and pivot tables in pandas.
Step two: the Northgate customers, generated
For the rest of the chapter, the customer table is generated so you can run every line. The recipe follows the Marketing Analytics chapter: 4,180 customers, each observed for between six months and two years, with five drivers known at their first order. The true yearly rate uses that chapter's coefficients. On top of it sits a hidden loyalty factor, because real customers differ in ways no export records, and that hidden variety is exactly what the rest of the chapter has to cope with.
Example: generating the table
rng = np.random.default_rng(33)
n = 4_180
# What the shop knew about each customer at their first order
first_value = rng.lognormal(np.log(60), 0.45, n) # first basket in £
corporate = rng.binomial(1, 0.06, n) # 1 = corporate account
first_value = np.where(corporate == 1, first_value * 1.5, first_value)
first_value = first_value.clip(max=400).round(2)
gift = rng.binomial(1, 0.40, n) # 1 = first order was a gift
email_open = rng.binomial(1, 0.55, n) # 1 = opened an email in 90 days
scotland = rng.binomial(1, 0.07, n) # 1 = Scottish delivery address
years_observed = rng.uniform(0.5, 2.0, n).round(2) # exposure: years since first order
# The true yearly rate, on the log scale (the Marketing Analytics chapter's coefficients)
log_rate = (-0.15 + 0.045 * (first_value - 40) / 10 - 0.36 * gift
+ 0.53 * email_open - 0.15 * scotland + 0.88 * corporate)
# Hidden loyalty: some customers simply like the shop more than their profile says
loyalty = rng.gamma(shape=1 / 0.48, scale=0.48, size=n) # mean 1, variance 0.48
orders = rng.poisson(np.exp(log_rate) * years_observed * loyalty)
# The next six months, kept aside for the honesty check at the end
next_half_year = rng.poisson(np.exp(log_rate) * 0.5 * loyalty)
customers = pd.DataFrame({
"customer_id": np.arange(1, n + 1),
"first_value": first_value,
"gift": gift,
"email_open": email_open,
"scotland": scotland,
"corporate": corporate,
"years_observed": years_observed,
"orders": orders,
})
customers["first_value_10"] = (customers["first_value"] - 40) / 10
The last line rescales the first order value the way the Marketing Analytics chapter does: steps of £10 above a £40 reference, so a coefficient reads as "per extra £10 in the first basket". The drivers are frozen at the first order on purpose. Use lifetime email opens instead and you leak the outcome into the inputs, because customers who order more also receive and open more email.
Step three: look at the counts before you model them
Before any model, look at the distribution. A count variable has a floor at zero, most of its mass near the bottom and a thin tail to the right. The Poisson distribution describes counts of events that arrive independently at a steady average rate:4
Here is the count, (mu) the expected number of events in the window, the count you observe, Euler's number (about 2.718), and is factorial, , with . Its one parameter is both its mean and its variance. Probability from scratch is in Foundations: probability, and distributions in Foundations: distributions.
Example: what a Poisson with the shop's average rate predicts
Northgate customers place 1.34 orders per customer year. For a customer observed for exactly one year with , the chance of no orders at all is , and the chance of exactly two is . A perfectly ordinary customer has a one in four chance of a silent year. A zero is not proof that someone has left.
Now compare the whole table against a Poisson with the same mean:
y = customers["orders"]
print(f"mean {y.mean():.2f}, variance {y.var():.2f}, zeros {(y == 0).mean():.1%}")
print(f"orders per customer year: {y.sum() / customers['years_observed'].sum():.2f}")
# mean 1.67, variance 5.84, zeros 36.5%
# orders per customer year: 1.34
observed = y.clip(upper=8).value_counts().sort_index()
k = np.arange(8)
poisson_same_mean = np.append(stats.poisson.pmf(k, y.mean()),
stats.poisson.sf(7, y.mean())) * n
print(pd.DataFrame({"observed": observed.values, "poisson": poisson_same_mean.round()},
index=[*map(str, k), "8+"]).astype(int).T)
# 0 1 2 3 4 5 6 7 8+
# observed 1524 1047 634 379 251 129 80 46 90
# poisson 784 1312 1098 612 256 86 24 6 1
stats.poisson.sf(7, mu) is the survival function, the probability of more than seven, which gives the "8 or more" bucket. The variance, 5.84, is three and a half times the mean, 1.67. A Poisson would need them equal.
Twice the zeros a Poisson expects, too few in the middle, and 90 customers with eight or more where a Poisson expects one. This is the signature of overdispersion, and you should see it before you fit anything. Part of it is simply exposure, because customers were watched for different lengths of time, and part is the drivers. The model has to tell you how much is left once both are accounted for. How to draw distributions like this honestly is the subject of showing distributions with histograms, box plots and density.
Step four: why ordinary regression is the wrong tool
Ordinary least squares, the regression from modelling demand and price elasticity with regression and its Python build in price elasticity with regression in Python, assumes the outcome can move freely in both directions with the same spread everywhere. Counts have a floor, and their spread grows with their mean. The quickest way to see the problem is to fit it anyway, the way most first attempts do, with tenure thrown in as one more driver.
Example: least squares predicts negative orders
formula = "orders ~ first_value_10 + gift + email_open + scotland + corporate"
ols = smf.ols(formula + " + years_observed", data=customers).fit()
print((ols.fittedvalues < 0).sum(), "negative predictions, lowest", round(ols.fittedvalues.min(), 2))
# 219 negative predictions, lowest -1.06
219 customers are predicted to place a negative number of orders, the lowest at minus 1.06. You can clip them to zero, but then you are no longer using the model you fitted. The standard errors have a quieter problem: least squares weighs a noisy corporate account exactly like a quiet occasional buyer, so its intervals are wrong in both directions at once.
Step five: the tenure trap, and the exposure offset that fixes it
The regression above also contains the most common error in count modelling. Put the time a customer has been observed in as an ordinary driver and the model learns that tenure causes orders. Of course older customers have more orders. They have had longer to place them.
Example: tenure posing as loyalty
naive = smf.glm(formula + " + years_observed", data=customers,
family=sm.families.Poisson()).fit()
print(np.exp(naive.params["years_observed"]).round(2))
# 2.51
The model reports that every extra year multiplies orders by 2.51. That is not loyalty. That is arithmetic.
The fix is to model the rate rather than the count. Poisson regression uses a log link, so each customer's expected count is the exponential of a sum, which is always positive. The exposure enters as the log of the observed time, with its coefficient fixed at exactly one:5
Here is the expected count for customer , the exposure (the years customer has been observed), the intercept, to that customer's drivers, and to the coefficients the model estimates. Moving to the left gives , the log of the yearly rate, which is the thing you actually want to explain. Rates are explained in Foundations: ratios and rates and the log rule in Foundations: logarithms.
In statsmodels you do not take the log yourself. The exposure argument of glm takes the raw time and adds its log with a coefficient of one. The alternative, offset, takes an already logged value.6 Use one or the other, never both.
Example: two customers with three orders each
Two Northgate customers each have three orders. One has been a customer for two years, the other for 0.6 years. Without an offset they are identical. With it:
Here the numerators, in both cases, are the orders and the denominators, and , the years observed. The first orders one and a half times a year, the second five times. Same count, more than three times the rate.
Step six: fit the Poisson model and read the rate ratios
Now the model itself. smf.glm fits a generalised linear model, the family of models that ordinary regression, Poisson regression and the logistic regression of the next chapter all belong to.
Example: the Poisson fit with exposure
poisson = smf.glm(formula, data=customers, family=sm.families.Poisson(),
exposure=customers["years_observed"]).fit()
def irr_table(result):
"""Coefficients, standard errors and incidence rate ratios with 95% intervals."""
ci = np.exp(result.conf_int())
table = pd.DataFrame({
"coef": result.params, "se": result.bse, "irr": np.exp(result.params),
"lower": ci[0], "upper": ci[1],
})
return table.drop(index="alpha", errors="ignore").round(3)
print(irr_table(poisson))
# coef se irr lower upper
# Intercept -0.176 0.025 0.839 0.798 0.881
# first_value_10 0.055 0.003 1.056 1.050 1.062
# gift -0.383 0.026 0.682 0.648 0.717
# email_open 0.552 0.026 1.736 1.651 1.826
# scotland -0.132 0.051 0.877 0.794 0.969
# corporate 0.907 0.035 2.477 2.315 2.651
The helper irr_table is worth keeping. It works on every count model in this chapter, and the drop(index="alpha", errors="ignore") line quietly removes the extra dispersion parameter that the negative binomial adds later.
The coefficients live on the log scale. Exponentiate one and you get the incidence rate ratio, IRR, the factor by which the expected rate changes when that driver goes up by one unit:5
Here is the incidence rate ratio for driver and its coefficient. An IRR of 1.74 means 74% more orders per year. An IRR of 0.68 means 32% fewer. Multiplying percentages is set out in Foundations: percentages.
Example: reading the Poisson table
The intercept, exponentiated, is 0.839: the reference customer (a self buyer in England or Wales with a £40 first order, no early email opens, no corporate account) orders 0.84 times a year. Each extra £10 in the first basket lifts the rate by 5.6%. Gift buyers come back at 68% of the self buyer rate. Early email engagement goes with a 74% higher rate. Scottish customers order about 12% less often, and the interval runs from 0.794 to 0.969, so under this model the effect looks real. Corporate accounts order about two and a half times as often.
These are close to the Marketing Analytics chapter's table, as they should be. The next step is where the Poisson's own numbers start to wobble.
Step seven: the dispersion check
The Poisson insists that the variance equals the mean. Hidden loyalty, the factor generated in step two, breaks that, and in real customer data something like it always does. After fitting, compute the Pearson dispersion statistic:5
Here (phi hat) is the estimated dispersion, the observed count for customer , the model's expected count for that customer, the number of customers, the number of estimated coefficients, and the sum runs over all customers. Each term measures how far a customer sits from the prediction in units of the variance the Poisson allows. If the Poisson is right, is close to 1. Variance, and why the divisor is , are in Foundations: spread.
statsmodels already computes the sum: it is pearson_chi2 on the result, and df_resid is .
Example: the dispersion and what it does to the Scotland effect
phi = poisson.pearson_chi2 / poisson.df_resid
print(f"dispersion {phi:.2f}, standard errors too small by a factor of {np.sqrt(phi):.2f}")
# dispersion 1.81, standard errors too small by a factor of 1.35
quasi = smf.glm(formula, data=customers, family=sm.families.Poisson(),
exposure=customers["years_observed"]).fit(scale="X2")
print(irr_table(quasi).loc[["scotland"]])
# coef se irr lower upper
# scotland -0.132 0.068 0.877 0.767 1.003
The dispersion is 1.81. The coefficients are still roughly right, but every standard error is too small by a factor of . Passing scale="X2" to fit gives the quasi Poisson correction, which scales the standard errors by exactly that factor.6 The Scotland interval now runs from 0.767 to 1.003. It crosses 1. The effect that looked solid a step ago is no longer distinguishable from nothing, and that is exactly the kind of effect people build a regional campaign around and then wonder why the campaign did nothing.
My working rule, the same as in the Marketing Analytics chapter: above about 1.3, stop trusting the Poisson standard errors. Above 1.5, change the model.
Step eight: the negative binomial
The negative binomial keeps the log link, the exposure and the IRR reading, so nothing above is wasted. It adds one parameter that lets the variance grow faster than the mean:7
Here is the variance of customer 's count, its expected value as before, and (alpha) the dispersion parameter, estimated from the data. With you are back at the Poisson. This form is called NB2. One way to read it, set out in Cameron and Trivedi's standard text on count data, is as a Poisson whose rate is multiplied by a hidden gamma distributed factor with mean 1 and variance , which is exactly how step two generated the data.8 Spread and variance are in Foundations: spread.
statsmodels has two ways to fit it, and the difference is a real trap.
Example: letting statsmodels estimate alpha
The discrete choice module estimates by maximum likelihood alongside the coefficients. Its formula function is smf.negativebinomial, and it accepts the same exposure argument:9
nb = smf.negativebinomial(formula, data=customers,
exposure=customers["years_observed"]).fit(disp=0)
alpha = nb.params["alpha"]
print(f"alpha {alpha:.3f}")
# alpha 0.495
print(irr_table(nb))
# coef se irr lower upper
# Intercept -0.165 0.034 0.848 0.793 0.906
# first_value_10 0.050 0.005 1.051 1.042 1.061
# gift -0.357 0.035 0.700 0.653 0.750
# email_open 0.540 0.035 1.717 1.603 1.839
# scotland -0.132 0.069 0.876 0.765 1.004
# corporate 0.880 0.060 2.410 2.142 2.712
print(f"AIC Poisson {poisson.aic:,.0f}, negative binomial {nb.aic:,.0f}")
# AIC Poisson 14,566, negative binomial 13,616
disp=0 only silences the optimiser's progress messages. The estimated is 0.495, close to the 0.48 used to generate the data and to the Marketing Analytics chapter's 0.48. The IRRs barely move from the Poisson's. The intervals widen honestly, and Scotland's runs from 0.765 to 1.004. The Akaike information criterion, AIC, a fit score that penalises extra parameters (lower is better), drops by about 950 points. The negative binomial is plainly the better description.
Example: the default that quietly sets alpha to one
There is also a negative binomial family for glm, and it looks like the obvious choice. It does not estimate . It uses whatever you pass, and if you pass nothing it uses 1.0.7
import warnings
with warnings.catch_warnings(record=True) as caught:
warnings.simplefilter("always")
wrong = smf.glm(formula, data=customers, family=sm.families.NegativeBinomial(),
exposure=customers["years_observed"]).fit()
print([str(w.message) for w in caught])
# ['Negative binomial dispersion parameter alpha not set. Using default value alpha=1.0.']
right = smf.glm(formula, data=customers, family=sm.families.NegativeBinomial(alpha=alpha),
exposure=customers["years_observed"]).fit()
print(irr_table(wrong).loc[["scotland"]]) # interval 0.745 to 1.030, too wide
print(irr_table(right).loc[["scotland"]]) # interval 0.765 to 1.004, matches nb
statsmodels 0.14 does warn, but in a notebook full of output a warning scrolls past. With instead of 0.495, the intervals are about 20% too wide and every tail probability you compute later is wrong. The pattern I use: estimate with smf.negativebinomial, then pass it explicitly to the glm family only if you need something the GLM result offers.
Step nine: how surprised to be by the Edinburgh customer
Now the question from the top. The Edinburgh customer is a Scottish gift buyer with a £75 first order who opens emails and has no corporate account, observed for two years.
Example: her expected count, and the predict trap
edinburgh = pd.DataFrame({"first_value_10": [(75 - 40) / 10], "gift": [1], "email_open": [1],
"scotland": [1], "corporate": [0]})
print(round(nb.predict(edinburgh).iloc[0], 2)) # forgot the exposure
# 1.06
mu = nb.predict(edinburgh, exposure=[2.0]).iloc[0] # two years observed
print(round(mu, 2))
# 2.13
mu_p = poisson.predict(edinburgh, exposure=[2.0]).iloc[0]
Here is the trap. When you predict for new rows, statsmodels does not remember the exposure from fitting. Leave it out and it assumes an exposure of one, so you get the yearly rate, 1.06, and nothing warns you. Pass exposure=[2.0] and you get the expected count over her two years, 2.13. Every scoring script needs that argument on every predict call.
By hand, with the negative binomial IRRs: orders a year. The intercept is 0.848, the first order value contributes for 3.5 steps of £10, then the gift, email and Scotland ratios. Over two years, 2.13. She placed seven.
Example: the tail probability under each model
SciPy's negative binomial uses a different parametrisation from statsmodels, a number of successes and a probability. The translation from mean and is and .10 A small helper keeps that in one place:
def nb_dist(mu, alpha):
"""scipy's negative binomial with mean mu and NB2 dispersion alpha."""
size = 1 / alpha
return stats.nbinom(size, size / (size + mu))
print(f"P(7 or more), Poisson: {stats.poisson.sf(6, mu_p):.4f}")
print(f"P(7 or more), negative binomial: {nb_dist(mu, alpha).sf(6):.4f}")
# P(7 or more), Poisson: 0.0060
# P(7 or more), negative binomial: 0.0421
Under the Poisson, seven or more orders happens to about one customer like her in 167. She looks like a star. Under the negative binomial her variance is , about double, and the chance becomes 0.042, about one in 24. A good customer who deserves a thank you note, not the founding member of a segment.
Step ten: count the stars the model already expects
This is the check I would put in front of anyone who wants to build a programme around heavy buyers. Instead of asking about one customer, add up the tail probability over every customer. The sum of probabilities is the expected number of customers above the threshold, the expected value from Foundations: expected value.
Example: 136 heavy buyers, and how many each model expects
mu_pois = poisson.fittedvalues
mu_nb = nb.predict(customers, exposure=customers["years_observed"])
for k_min in (7, 10):
print(k_min, "or more:",
f"Poisson expects {stats.poisson.sf(k_min - 1, mu_pois).sum():.0f},",
f"negative binomial expects {nb_dist(mu_nb, alpha).sf(k_min - 1).sum():.0f},",
f"observed {(y >= k_min).sum()}")
# 7 or more: Poisson expects 82, negative binomial expects 148, observed 136
# 10 or more: Poisson expects 21, negative binomial expects 49, observed 51
poisson.fittedvalues already includes each customer's exposure. For the negative binomial, pass it again, for the reason in the predict trap above.
Under the Poisson, 54 of the 136 heavy buyers are "unexplained", which is the kind of number that starts a VIP project. Under the negative binomial, the shop has slightly fewer heavy buyers than ordinary variety produces. The heavy buyers are real people and worth looking after. They are not evidence of a hidden kind of customer. If the observed count were well above the negative binomial's expectation, that would be worth a closer look, and the surprise list below is where you would start.
Step eleven: zeros, and whether zero inflation earns its place
Zero inflation is a different problem from overdispersion. It asks whether the zeros come from two populations: customers who will order again and simply have not yet, and customers who never will, whatever you do. A zero inflated model fits a logistic part for the probability of being a "never again" customer and a count part for everyone else.11 statsmodels has it as ZeroInflatedNegativeBinomialP, which takes arrays rather than a formula.12
Example: checking the zeros, then testing a never again driver
print(f"zeros: Poisson {stats.poisson.pmf(0, mu_pois).sum():,.0f}, "
f"negative binomial {nb_dist(mu_nb, alpha).pmf(0).sum():,.0f}, observed {(y == 0).sum():,}")
# zeros: Poisson 1,138, negative binomial 1,497, observed 1,524
from statsmodels.discrete.count_model import ZeroInflatedNegativeBinomialP
X = sm.add_constant(customers[["first_value_10", "gift", "email_open", "scotland", "corporate"]])
X_never = sm.add_constant(customers[["gift"]]) # candidate driver for "never again"
zinb = ZeroInflatedNegativeBinomialP(customers["orders"], X, exog_infl=X_never,
exposure=customers["years_observed"], p=2)
zinb_fit = zinb.fit(method="bfgs", maxiter=500, disp=0)
print(f"AIC negative binomial {nb.aic:,.1f}, zero inflated {zinb_fit.aic:,.1f}")
print(zinb_fit.params.round(2).loc[["inflate_const", "inflate_gift"]])
# AIC negative binomial 13,615.7, zero inflated 13,616.6
# inflate_const -3.33
# inflate_gift -0.05
The negative binomial predicts 1,497 zeros against 1,524 observed. Close. The zero inflated model, with "first order was a gift" as the candidate driver of never coming back, fits no better: its AIC is 0.9 higher, and the gift coefficient in the inflation part is minus 0.05, nothing. p=2 selects the NB2 form used throughout. The optimiser may warn about convergence here, which is itself a hint that the extra part has nothing to explain.
The decision path I follow is the same as in the Marketing Analytics chapter, now with the function at each step:
Add zero inflation when you can name the never again group and would treat it differently, for example corporate gifts shipped to a third party address, where the recipient never chose the shop. Do not add it because it fits a little better. With more parameters it almost always does.
Step twelve: from model to three lists
A count model earns its keep when it changes who you talk to. Three lists come out of the negative binomial with a few lines of pandas.
The expected value list. Every customer's expected yearly rate, which multiplied by the contribution per order is the honest basis for how much to spend keeping them.
The surprise list. How far each customer sits from what the model expected, standardised by the negative binomial's own variance, the Pearson residual:
Here is the residual for customer , the observed count, the expected count over that customer's own exposure, and the dispersion parameter. The denominator is the standard deviation from step eight. Standard deviation is in Foundations: spread.
The lever list. With an email IRR of 1.717, a customer who has not engaged yet would gain orders a year if a nudge worked fully, where is their expected yearly rate. It will not work fully, so treat the number as a ranking, not a forecast.
Example: building the scored table
scored = customers.assign(
expected_per_year=nb.predict(customers, exposure=np.ones(n)),
expected=mu_nb,
)
scored["residual"] = (scored["orders"] - scored["expected"]) / np.sqrt(
scored["expected"] + alpha * scored["expected"] ** 2)
email_irr = np.exp(nb.params["email_open"])
scored["email_gain"] = np.where(scored["email_open"] == 0,
scored["expected_per_year"] * (email_irr - 1), 0.0)
cols = ["customer_id", "first_value", "gift", "corporate", "years_observed",
"orders", "expected", "residual"]
print(scored.nlargest(5, "residual")[cols].round(2).to_string(index=False))
# customer_id first_value gift corporate years_observed orders expected residual
# 2113 86.95 1 0 1.85 17 2.38 6.41
# 2463 101.28 0 0 0.85 12 1.68 5.88
# 580 22.57 0 0 0.72 5 0.56 5.26
# 3917 77.58 1 1 1.36 14 2.35 5.17
# 727 36.33 0 0 1.85 15 2.64 5.00
print((scored["residual"] > 3).sum(), "customers more than 3 above")
# 58 customers more than 3 above
assign returns a new table, which under pandas 3.0's copy on write is the clean way to add columns without touching customers. The Edinburgh customer, with a residual of , does not make this list. Customer 2113 does: a gift buyer with 17 orders where 2.38 were expected. Customers like that deserve a phone call, not a discount code, because in real data a good share of them turn out to be small companies ordering under a personal address.
cols2 = ["customer_id", "first_value", "gift", "expected_per_year", "email_gain"]
print(scored[scored["corporate"] == 0].nlargest(5, "email_gain")[cols2].round(2).to_string(index=False))
# customer_id first_value gift expected_per_year email_gain
# 1180 253.05 0 2.47 1.77
# 1923 209.21 0 1.98 1.42
# 1970 204.44 0 1.93 1.39
# 2476 202.21 0 1.91 1.37
# 3129 257.42 1 1.76 1.27
The lever list leaves out corporate accounts, which have an account manager already. What is left is customers with a large first basket who have never opened an email. Most marketers would not look at them twice. The model puts them first.
Step thirteen: blend the model with each customer's own history
Here is the idea I would add to the Marketing Analytics chapter. The model's expected rate describes a typical customer with this profile. It ignores what this particular customer has done. Her raw history, seven orders in two years, is 3.5 a year, but raw history on its own is noisy: one lucky year and a customer looks like a star.
The negative binomial lets you combine the two properly. Because it is a Poisson with a hidden gamma loyalty factor, the expected loyalty of a customer, once you have seen her orders, has a closed form from Bayes' rule:8
Here is customer 's estimated loyalty factor (1 means exactly as the profile predicts), the weight of the model's view, the orders she placed, and the orders the model expected over her exposure. Her best guess yearly rate is . With little exposure, and are both small, dominates, and the estimate stays close to the model. With a long history, her own orders take over. Weighted averages and the mean are in Foundations: the mean.
Example: the Edinburgh customer's best guess
With , seven orders and 2.127 expected (to three decimals):
Here is , her orders and her expected count. Her best guess rate is orders a year: well above her profile's 1.06, well below her raw 3.5. In code, for every customer:
size = 1 / alpha
scored["loyalty"] = (size + scored["orders"]) / (size + scored["expected"])
scored["best_guess_per_year"] = scored["expected_per_year"] * scored["loyalty"]
edi_loyalty = (size + 7) / (size + mu)
print(round(edi_loyalty, 2), round(nb.predict(edinburgh).iloc[0] * edi_loyalty, 2))
# 2.18 2.31
That is the honest answer to the December conversation. She is not a segment. She is a customer who, on the evidence, likes the shop a little more than twice as much as her profile predicts, and the right number to plan her with is 2.3 orders a year, not 7 in two.
Step fourteen: check it on orders the model never saw
A model you have only scored on the data you fitted it to has not been tested. Step two kept aside each customer's next six months. In a real project, that is the most recent half year, cut off before fitting. Two checks: does the ranking hold, and do the predicted levels match.
Example: three rankings against the next half year
scored["next_half_year"] = next_half_year
for col in ["expected_per_year", "orders", "best_guess_per_year"]:
rho = stats.spearmanr(scored[col], scored["next_half_year"]).statistic
print(f"{col:>20}: rank correlation {rho:.2f}")
# expected_per_year: rank correlation 0.26
# orders: rank correlation 0.32
# best_guess_per_year: rank correlation 0.37
The Spearman rank correlation measures how well one ordering matches another, from minus 1 to 1. The model on its own ranks customers worse than their past order count. That surprises people, and it should not: the model only knows the five drivers, and a lot of what makes a customer come back is the hidden loyalty no export records. Past orders know some of that loyalty but are muddled by different exposure and by luck. The blend beats both.
The same story in business terms: take the top 418 customers, the top tenth, under each ranking, and count what they ordered in the following six months. The best guess ranking captures 770 of the 2,756 orders, past orders 706, and the model alone 634.
Example: are the levels right, decile by decile
scored["decile"] = pd.qcut(scored["best_guess_per_year"], 10, labels=False) + 1
check = scored.groupby("decile").agg(
predicted=("best_guess_per_year", lambda s: (s / 2).mean()),
actual=("next_half_year", "mean"))
print(check.round(2).T)
# decile 1 2 3 4 5 6 7 8 9 10
# predicted 0.24 0.30 0.35 0.41 0.48 0.55 0.64 0.79 1.01 1.90
# actual 0.21 0.28 0.36 0.40 0.53 0.57 0.64 0.81 0.95 1.84
pd.qcut cuts customers into ten equal groups by their best guess rate. Halving the yearly rate gives the expected orders in six months.
In every decile the prediction lands within about 0.06 orders of what happened. Generated data is kind, of course: the model's form is the form the data was made from. On real data expect the top decile to be the least accurate, and if the bars drift apart in the same direction everywhere, look for a change in the shop (a price rise, a new channel) between the fitting period and the check period. Making this check a script that runs every time, rather than a cell you ran once, is what a reproducible Python analysis workflow is about.
My view
My view: for customer counts in a shop, start with the negative binomial and let the dispersion check talk you back to the Poisson, not the other way round. A customer base whose orders are Poisson once the drivers are in would be a rare thing, because customers differ in ways no table records, and that hidden variety is precisely what the negative binomial models. The Poisson still earns a place as the first fit, because its dispersion statistic is the cleanest single measure of how much hidden variety there is.
The second part of my view matters more to the business. The model's coefficients answer "what kind of customer orders more?", which is a question for strategy. The blended best guess answers "which customers will order more?", which is a question for next month's email list. Teams that only report the first never get to act on it, and teams that only rank by past orders keep rewarding customers for having joined early. The negative binomial gives you both from one fit, and the blend is three lines of pandas.
What I would not do is reach for zero inflation, hurdle models or machine learning before the offset, the dispersion check and the holdout are in place. Most of the value in a count model is in counting the right thing over the right window. The rest is refinement.
Mistakes worth avoiding
Counting rows instead of orders. Refund rows, test orders and staff orders end up in the tail, where they move the dispersion and the surprise list the most. Clean before you count.
Passing exposure as a driver. It belongs in exposure= (raw time) or offset= (logged time), never in the formula.
Forgetting exposure at predict time. predict without exposure silently gives a rate per unit of time, not a count. Fine if that is what you want, a quiet bug if not.
Using sm.families.NegativeBinomial() without an alpha. It uses 1.0. Estimate alpha with smf.negativebinomial and pass it on.
Reading IRRs as additive. An IRR of 1.717 on a baseline of 0.3 orders a year is extra orders. On a baseline of five it is 3.6. Multiply through to the customer's own rate before promising anything.
Celebrating the tail. Before announcing a segment of heavy buyers, sum the negative binomial tail probabilities. Usually the model expects about as many as you found.
Measuring drivers inside the counting window. Freeze them at the start. Otherwise the model explains the past with the past.
For the person who commissions this
You do not need to read the code to judge the work. Ask for these, and the answers will tell you whether the model can be trusted:
| Question | A good answer sounds like |
|---|---|
| What exactly is counted, and over what window per customer? | Orders kept after refunds, test and staff orders removed, counted in the shop's own time zone, with exposure per customer |
| Is there an exposure offset? | Yes, the log of years observed, coefficient fixed at one |
| What was the Pearson dispersion of the Poisson fit? | A number, and what was done when it came out above 1.5 |
| How was alpha set? | Estimated from the data, not left at a default |
| How many heavy buyers does the model expect? | A sum of tail probabilities, compared with the observed count |
| Were the effects multiplied through to real customers? | Yes, with the expected gain per customer on the lever list |
| Was the ranking checked on a period the model never saw? | Yes, with a rank correlation and a decile table |
| Which list changed because of this work? | A named list, in the email tool, with an owner |
If the answers come back vague, the model is probably a regression table and nothing more. Data science, dashboards and data storytelling are a core part of the work I do for clients, and this kind of model is exactly where a careful build pays: the Data Science page describes how I work. I publish my prices at transparent pricing, and you own the code, the accounts and the data from day one.
Conclusion
A count model in Python is short. The data preparation is not. Build the count from cleaned orders on the shop's own clock, give every customer an exposure, fit the Poisson with smf.glm, read the IRRs, and check the dispersion. When it is well above one, and in customer data it will be, move to smf.negativebinomial, let it estimate alpha, and never trust a default. Then use what the negative binomial gives you beyond the table: tail probabilities that tell you how surprised to be, the expected number of heavy buyers before anyone builds a programme around them, and a best guess per customer that blends the model with their own history. Check it on a later period, and turn it into three lists people will actually work through.
In the next chapter of this series, logistic regression, lift charts and basket analysis in Python, the outcome becomes a simple yes or no, and the same glm function does the work with a different family.
