Logistic regression, lift charts and basket analysis in Python
TL;DR
Difficulty: Intermediate
Fitting a logistic regression takes three lines. Whether the mailing makes money is decided by what surrounds them.
- Build the response flag net of refunds, staff and test orders, in local time.
- Explain with statsmodels (odds ratios, intervals, VIF), score with scikit learn, and switch its default penalty off with C=np.inf.
- Ignore accuracy: judge the ranking with AUC on a test set, then cut deciles with rank and qcut and mail to the peak of the cumulative profit.
- For baskets, count pairs with a crosstab, then let a logistic model hold the buyer type constant: some pairs vanish.
Who should get the spring brochure, how far down the list should it go, and what should the shop suggest next to the wine hamper? I build the response model, the decile lift table and the basket analysis from the Marketing Analytics chapter in Python, step by step, on data you can generate and run yourself.
Who to mail, how deep, and what goes with what
Priya runs Northgate Hampers, an invented online hamper shop in Leeds at northgatehampers.example. Every March she faces the same two questions. The spring brochure costs about £1.20 per household, and 20,000 people on the customer file have bought at least once: who gets one, and how far down the list does she go? And on the website: when someone puts the wine hamper in the basket, what should the shop suggest next?
Both questions end in a yes or a no. Will this customer respond? Will this basket get the cheese hamper? Logistic regression is the model built for that kind of outcome, the lift chart turns its scores into a mailing decision, and basket analysis turns the same thinking onto the order lines. The concepts are explained in Logistic regression, lift charts and market basket analysis, chapter 7 of my Marketing Analytics series. This chapter builds it in Python, line by line, on data you can generate and run yourself.
Here is the idea I want you to take away before any code. Fitting the model takes three lines. Whether the mailing makes money is decided by three things around those lines: the date at which every column was measured, a test set the model never saw, and a decile table with a profit column instead of an accuracy score. A model that predicts "no" for every customer is 96% accurate on Priya's file and worth nothing. A model with a modest score that is ranked, priced and checked on fresh customers can double the campaign profit. This chapter spends its effort where the money is.
Northgate Hampers, Priya and every number here are invented, and the data is generated in code to resemble the example in the Marketing Analytics chapter, so the two chapters read as a pair.
If you only read one section
For the person who commissions this work and will never open a Notebook, these are the points to hold your analyst to.
- Ask for a decile table with money in it. Ten rows, best customers first, with the response rate, the cost and the profit of each tenth of the file. The right mailing depth is where the cumulative profit peaks. In this example that is the top four deciles, 8,000 people instead of 20,000, and the profit roughly doubles.
- Ask which customers the table was measured on. The answer must be "a test set the model never saw". A table built on the training data flatters the model every time.
- Ignore accuracy. When 4% of people respond, a model that says "nobody responds" is 96% accurate. Ask for the area under the curve (AUC) and the gains chart instead, and expect a marketing response model to land somewhere between about 0.65 and 0.85. If someone shows you 0.97, assume a column leaked information from after the mailing until they prove otherwise.
- Ask for two control groups. A few hundred random customers from the deep deciles who get the brochure anyway, so next year's model still learns about them, and a slice of the top deciles who do not get it, so you can measure what the brochure actually caused.
- For product recommendations, ask whether the pairs survive the buyer type. Counting pairs says wine buyers often add prosecco. In this example that is entirely because offices buy both. The logistic basket model shows it in one line.
What you need, as of March 2026
Everything here runs on the current versions at the time of writing: Python 3.14, pandas 3.0, NumPy 2.4, statsmodels 0.14.6, scikit learn 1.8 and, for one optional section, mlxtend 0.24. If you followed why Python for data analysis and how to set it up, install the libraries into your project's environment:
python -m pip install "pandas==3.0.*" "numpy==2.4.*" "statsmodels==0.14.6" "scikit-learn==1.8.*" "mlxtend==0.24.*"
Two version notes matter for this chapter. pandas 3.0, released in January 2026, made Copy on Write the only behaviour, so assigning a new column to a DataFrame you got from a split or a filter no longer produces the old SettingWithCopyWarning, and defensive .copy() calls are no longer needed.1 And scikit learn 1.8 deprecated the penalty argument of LogisticRegression: you now switch the penalty off with C=np.inf.2 Older tutorials, including the modelling chapter of Wes McKinney's Python for Data Analysis, call LogisticRegression() with its defaults,3 and I come back to why that default deserves a second look.
The statistical model behind both libraries is the one from statistical models in Python with statsmodels and scikit learn. If smf.logit and fit and predict are new to you, read that first. Within this series, this chapter follows descriptive statistics for marketers in Python, price elasticity with regression in Python, distributed lags in Python and Poisson regression in Python. Poisson counted how many times customers do something. Logistic regression asks whether they do it at all.
Step 1: build the customer file
A response model needs one row per customer, measured as of the day the brochure went out, plus one column that says whether they responded. Priya's model is fitted on last spring: 20,000 customers mailed on 3 March 2025, 788 responders.
Example: Priya's 20,000 customers in code
The block below generates that file. Recent buyers order more often, and bigger spenders tend to be frequent buyers, so a little overlap between the columns is built in on purpose. The response itself is drawn from the same equation the Marketing Analytics chapter uses.
import numpy as np
import pandas as pd
rng = np.random.default_rng(575)
n = 20_000
customers = pd.DataFrame({"customer_id": np.arange(1, n + 1)})
customers["months_since_last"] = rng.integers(1, 37, n) # 1 to 36 months
recency = np.exp(0.42 - 0.02 * customers["months_since_last"].to_numpy())
customers["orders_24m"] = rng.poisson(recency, n) + 1 # recent buyers order more often
customers["gift_buyer"] = rng.binomial(1, 0.35, n)
customers["corporate"] = rng.binomial(1, 0.10, n)
customers["clicked_last_spring"] = rng.binomial(1, 0.15, n)
customers["aov_per_10"] = (rng.gamma(8.0, 0.6, n)
+ 0.9 * customers["orders_24m"]).round(1) # order value in tens of pounds
# the response, drawn from the equation in the Marketing Analytics chapter
score = (-3.40 - 0.09 * customers["months_since_last"]
+ 0.28 * customers["orders_24m"] + 0.55 * customers["gift_buyer"]
+ 0.42 * customers["corporate"] + 0.78 * customers["clicked_last_spring"]
+ 0.06 * customers["aov_per_10"])
customers["responded"] = rng.binomial(1, 1 / (1 + np.exp(-score)))
print(len(customers), customers["responded"].sum(), round(customers["responded"].mean(), 4))
# 20000 788 0.0394
788 responders out of 20,000 is a base rate of 3.94%, the same as in the Marketing Analytics chapter. The email column is "clicked", not "opened": Apple's Mail Privacy Protection loads the tracking image that records an open in the background, whether or not anyone reads the message, so opens are inflated and make a weak predictor.4
The response flag is where real projects go wrong
In the generated file the responded column is simply there. In a real shop you build it from the order export, and that is where most first attempts quietly go wrong. The cleaning rules come from cleaning data in pandas and the time zone rules from time series in pandas. Here they decide who counts as a responder.
A response, for this campaign, is an order with the spring code, placed within six weeks of the mailing, by a real customer, that was not fully refunded. Four traps hide in that sentence: refunds arrive as separate rows with a negative total, staff and test orders sit in the same export, the export stores time in UTC while the campaign ran on UK time, and the clocks went forward on 30 March 2025, in the middle of the window.
Example: six orders, one real responder
orders = pd.DataFrame({
"order_id": ["S1001", "S1002", "S1003", "S1004", "S1005", "S1006"],
"customer_id": [17, 17, 230, 501, 990, 1204],
"created_utc": pd.to_datetime(["2025-03-04 09:12", "2025-03-04 09:15",
"2025-03-29 23:40", "2025-04-13 23:30",
"2025-03-10 14:05", "2025-03-12 11:30"], utc=True),
"code": ["SPRING25"] * 6,
"total": [68.0, -68.0, 49.0, 72.0, 55.0, 0.0], # S1002 refunds S1001 in full
"email": ["a@x.example", "a@x.example", "b@x.example", "c@x.example",
"staff@northgatehampers.example", "test@northgatehampers.example"],
})
mailed = pd.Timestamp("2025-03-03", tz="Europe/London")
window_end = mailed + pd.DateOffset(weeks=6) # midnight at the start of 14 April, UK time
local_time = orders["created_utc"].dt.tz_convert("Europe/London")
is_customer = ~orders["email"].str.endswith("@northgatehampers.example")
in_window = (local_time >= mailed) & (local_time < window_end)
net = (orders[is_customer & in_window & (orders["code"] == "SPRING25")]
.groupby("customer_id")["total"].sum())
responders = net[net > 0].index.tolist()
print(net.to_dict(), responders)
# {17: 0.0, 230: 49.0} [230]
Customer 17 ordered and got a full refund, so the net is zero and they are not a responder. The staff and test orders drop out on the email domain. Customer 501 ordered at 23:30 UTC on 13 April, which is 00:30 on 14 April in the UK, half an hour after the code expired. Only customer 230 is a real responder.
The subtle one is the window. Six weeks across a clock change is not 42 times 24 hours:
print(mailed + pd.Timedelta(weeks=6)) # 2025-04-14 01:00:00+01:00, an hour too late
print(window_end) # 2025-04-14 00:00:00+01:00
pd.Timedelta adds elapsed time, so the window ends at 1am, and customer 501 would have counted. pd.DateOffset adds calendar time and ends at midnight, as the brochure promised.5 One customer is nothing. Across a file of 20,000 and every campaign that crosses the end of March or October, it is a quiet bias in the very column the model learns from.
statsmodels explains: odds ratios with honest intervals
The model is the logit from the Marketing Analytics chapter. It does not model the probability directly. It models the log of the odds, which can take any value, and that keeps every prediction between 0 and 1:6
Here is the probability that a customer responds, is the odds, is the natural logarithm, to are the six columns of the customer file, is the intercept and each is the change in the log odds for one unit more of , with the other columns held constant. Foundations: probability
I use statsmodels when the question is "what drives response, and how sure can I be", because it reports standard errors, confidence intervals and p values in one table.7 The formula interface reads like the equation.
Example: fitting Priya's response model
import statsmodels.formula.api as smf
formula = ("responded ~ months_since_last + orders_24m + gift_buyer"
" + corporate + clicked_last_spring + aov_per_10")
logit = smf.logit(formula, data=customers).fit(disp=0)
table = pd.DataFrame({
"coef": logit.params,
"std_err": logit.bse,
"odds_ratio": np.exp(logit.params),
"or_low": np.exp(logit.conf_int()[0]),
"or_high": np.exp(logit.conf_int()[1]),
}).round(3)
print(table)
| Variable | Coefficient | Std. error | Odds ratio | 95% interval |
|---|---|---|---|---|
| Intercept | minus 3.405 | 0.157 | 0.033 | 0.024 to 0.045 |
| Months since last order | minus 0.093 | 0.005 | 0.911 | 0.903 to 0.920 |
| Orders in the last 24 months | 0.284 | 0.035 | 1.328 | 1.240 to 1.423 |
| Gift buyer | 0.558 | 0.075 | 1.747 | 1.508 to 2.024 |
| Corporate account | 0.370 | 0.110 | 1.448 | 1.168 to 1.796 |
| Clicked last spring's email | 0.792 | 0.087 | 2.207 | 1.861 to 2.618 |
| Average order value, per £10 | 0.056 | 0.022 | 1.058 | 1.014 to 1.104 |
Set this beside the table in the Marketing Analytics chapter and you will recognise it: minus 3.40 against minus 3.405, 0.55 against 0.558 for gift buyers, 0.78 against 0.792 for the email click. The differences are sampling noise, and the intervals tell you how big that noise is. The corporate flag is the least certain: its interval runs from 1.17 to 1.80. It clears 1, so it belongs in the model, but nobody should quote "corporate accounts are 45% more likely to respond" as a precise fact.
Reading it the way Priya would. Each month since the last order multiplies the odds by 0.911. A customer who last bought 12 months ago has times the odds of someone who bought last month. A click on last spring's email more than doubles the odds. Each £10 of average order value adds about 6%.
Turning an odds ratio into a probability
An odds ratio is not a probability ratio, and the difference grows with the base rate. A two line function makes it concrete:
def shift_probability(p, odds_ratio):
"""Probability after multiplying the odds of p by odds_ratio."""
odds = p / (1 - p) * odds_ratio
return odds / (1 + odds)
print(round(shift_probability(0.03, 1.73), 3)) # 0.051
print(round(shift_probability(0.20, 1.73), 3)) # 0.302
At a 3% starting point the gift buyer odds ratio of about 1.73 takes the probability to 5.1%, which is close to 1.73 times. At 20% it takes it to 30.2%, which is only 1.5 times. For a 4% response campaign the shortcut "odds ratio roughly equals probability ratio" is fine. For the basket model later, where probabilities run to 20% and 30%, it is not.
Check collinearity before anyone reads a coefficient
If two columns carry nearly the same information, the model cannot tell them apart, the standard errors swell and signs can flip. The variance inflation factor (VIF) measures it for each column:8
Here is the variance inflation factor of column , and is the share of the variation in explained by regressing it on all the other columns. A VIF of 1 means shares nothing with the others. Penn State's regression course treats values above 4 as worth a look and above 10 as serious.8 Foundations: ratios and rates
Example: the VIFs of Priya's six columns
statsmodels computes it from the design matrix the model already built, so the intercept is included as it should be:
from statsmodels.stats.outliers_influence import variance_inflation_factor
X = logit.model.exog
names = logit.model.exog_names
vif = pd.Series([variance_inflation_factor(X, i) for i in range(1, X.shape[1])],
index=names[1:]).round(2)
print(vif)
# months_since_last 1.04
# orders_24m 1.36
# gift_buyer 1.00
# corporate 1.00
# clicked_last_spring 1.00
# aov_per_10 1.32
Order count and order value share a little information, which is what the code built into the data, and 1.36 is nowhere near trouble. The check takes five lines, and it belongs in every response model before the odds ratio table goes into a presentation. A classic sign of trouble is a coefficient with the "wrong" sign, such as frequent buyers responding less. Check the VIFs before anyone invents a story for it.
scikit learn scores: split first, and switch off the penalty you did not ask for
statsmodels explains. For scoring a file and checking the ranking on fresh customers, scikit learn is the tool most pipelines use, because its fit and predict_proba slot into the rest of a scoring job.2 The first step is a split. The model learns on 70% of the customers and is judged on the 30% it never saw.
Example: the split and the two fits side by side
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
features = ["months_since_last", "orders_24m", "gift_buyer",
"corporate", "clicked_last_spring", "aov_per_10"]
train, test = train_test_split(customers, test_size=0.3,
stratify=customers["responded"], random_state=575)
print(len(train), len(test), round(train["responded"].mean(), 4), round(test["responded"].mean(), 4))
# 14000 6000 0.0394 0.0393
stratify keeps the share of responders the same in both parts.9 With a 4% outcome and no stratification, a test set can easily end up with noticeably more or fewer responders than the file, and every number you compute on it inherits that luck.
Now the trap. LogisticRegression() with its defaults is not the model statsmodels fits. It adds an L2 penalty with C=1.0, which pulls every coefficient towards zero.2 That is useful for prediction with many columns. It is a surprise when you compare the two libraries and the numbers disagree. In scikit learn 1.8 the documented way to fit the plain model is C=np.inf:
scorer = LogisticRegression(C=np.inf, max_iter=1000) # no penalty, the plain logit
scorer.fit(train[features], train["responded"])
default = LogisticRegression(max_iter=1000).fit(train[features], train["responded"])
sm_train = smf.logit(formula, data=train).fit(disp=0)
comparison = pd.DataFrame({
"statsmodels": sm_train.params.to_numpy(),
"sklearn_no_penalty": np.r_[scorer.intercept_, scorer.coef_[0]],
"sklearn_default": np.r_[default.intercept_, default.coef_[0]],
}, index=["Intercept"] + features).round(3)
print(comparison)
| Column | statsmodels | scikit learn, no penalty | scikit learn, default |
|---|---|---|---|
| Intercept | minus 3.363 | minus 3.365 | minus 3.359 |
| Months since last order | minus 0.094 | minus 0.094 | minus 0.094 |
| Orders in 24 months | 0.294 | 0.294 | 0.294 |
| Gift buyer | 0.491 | 0.492 | 0.488 |
| Corporate | 0.380 | 0.376 | 0.370 |
| Clicked last spring | 0.850 | 0.850 | 0.841 |
| Order value per £10 | 0.051 | 0.051 | 0.051 |
With 14,000 customers the penalty barely matters: the default shrinks the email click from 0.850 to 0.841. Two practical notes. scikit learn 1.8.0 prints a UserWarning saying that C will be ignored when you pass C=np.inf. It is a side effect of the new deprecation, and the fit is the unpenalised one, as the matching columns show. And the penalty depends on the scale of each column, so the same C shrinks a column measured in pounds differently from one measured in tens of pounds.
The penalty starts to matter on small files. Fit the same two models on 2,000 customers instead of 14,000:
small = train.sample(2_000, random_state=1)
s_plain = LogisticRegression(C=np.inf, max_iter=1000).fit(small[features], small["responded"])
s_default = LogisticRegression(max_iter=1000).fit(small[features], small["responded"])
print(small["responded"].sum()) # 81
print(round(s_plain.coef_[0][4], 3), round(s_default.coef_[0][4], 3)) # 0.731 0.676
With 81 responders, the default shrinks the email click coefficient by about 8% and the gift buyer coefficient by about 7%. Neither is wrong. But if you report odds ratios from a penalised fit as if they were the plain model, you understate every effect without knowing it. My rule: explain with statsmodels, score with scikit learn, and say in the code which penalty you chose.
Accuracy is the wrong number, AUC is a ranking number
The first number most tutorials print for a classifier is accuracy, the share of correct yes or no predictions. For a 4% outcome it is useless.
Example: a 96% accurate model that mails nobody
from sklearn.metrics import accuracy_score, roc_auc_score
test["p_hat"] = scorer.predict_proba(test[features])[:, 1]
print(round(accuracy_score(test["responded"], scorer.predict(test[features])), 4)) # 0.9607
print(round(accuracy_score(test["responded"], np.zeros(len(test))), 4)) # 0.9607
print(scorer.predict(test[features]).sum()) # 0
predict turns each probability into a yes only above 50%. No customer in Priya's file gets there, so the model predicts "no" for everyone and scores exactly the same 96.07% as a line of code that says "nobody responds". The campaign question was never "yes or no at 50%". It is "in what order, and how deep".
The number that answers "in what order" is the area under the ROC curve, AUC for short. It has a plain meaning: pick one responder and one non responder at random, and the AUC is the probability that the model scores the responder higher.10 0.5 is a coin flip, 1.0 is a perfect ranking.
auc_test = roc_auc_score(test["responded"], test["p_hat"])
auc_train = roc_auc_score(train["responded"], scorer.predict_proba(train[features])[:, 1])
print(round(auc_test, 3), round(auc_train, 3)) # 0.776 0.788
# the same number, measured as a share of random pairs
yes = test.loc[test["responded"] == 1, "p_hat"].to_numpy()
no = test.loc[test["responded"] == 0, "p_hat"].to_numpy()
print(round((rng.choice(yes, 200_000) > rng.choice(no, 200_000)).mean(), 3)) # 0.777
0.776 on customers the model never saw, 0.788 on the ones it learned from. The small gap is healthy: the model has learned about customers, not memorised last spring. Drawing 200,000 random pairs and counting how often the responder wins gives 0.777, the same number by brute force, which is a good way to make AUC feel real to someone who distrusts it.
AUC has one weakness for this decision. It treats every pair the same, while the money is made in the top few deciles. Two models with the same AUC can have very different profits at a depth of 40%. That is why the decision itself comes from the decile table.
The decile table with pandas qcut
Sort the test customers from highest to lowest score, cut them into 10 equal groups and compare each group's response rate with the average. That is the lift table, and pandas builds it with qcut and a groupby, as in group by and pivot tables in pandas.
Here is the lift of decile , the response rate within that decile and the response rate across all test customers. A lift of 3 means those customers respond three times as often as a random pick. Foundations: indexing and base rates
Example: Priya's lift table on 6,000 test customers
test["decile"] = pd.qcut(test["p_hat"].rank(method="first", ascending=False),
10, labels=range(1, 11)) # decile 1 = best scores
lift = (test.groupby("decile", observed=True)
.agg(customers=("responded", "size"),
responders=("responded", "sum"),
predicted=("p_hat", "mean")))
base = test["responded"].mean()
lift["observed"] = lift["responders"] / lift["customers"]
lift["lift"] = lift["observed"] / base
lift["gain"] = lift["responders"].cumsum() / lift["responders"].sum()
print(lift.round(3))
| Decile | Customers | Responders | Predicted rate | Observed rate | Lift | Share of responders so far |
|---|---|---|---|---|---|---|
| 1 | 600 | 88 | 15.1% | 14.7% | 3.73 | 37% |
| 2 | 600 | 46 | 7.7% | 7.7% | 1.95 | 57% |
| 3 | 600 | 21 | 5.3% | 3.5% | 0.89 | 66% |
| 4 | 600 | 37 | 3.7% | 6.2% | 1.57 | 81% |
| 5 | 600 | 13 | 2.6% | 2.2% | 0.55 | 87% |
| 6 | 600 | 7 | 1.9% | 1.2% | 0.30 | 90% |
| 7 | 600 | 10 | 1.3% | 1.7% | 0.42 | 94% |
| 8 | 600 | 10 | 0.9% | 1.7% | 0.42 | 98% |
| 9 | 600 | 3 | 0.6% | 0.5% | 0.13 | 99.6% |
| 10 | 600 | 1 | 0.3% | 0.2% | 0.04 | 100% |
Why rank(method="first") and not qcut on the scores directly? Customers with identical columns get identical scores, and real files have lots of them: everyone who bought once, 14 months ago, as a private self buyer with no click, ties. If the tie sits on a decile boundary, qcut either fails with "Bin edges must be unique" or quietly builds unequal groups when you pass duplicates="drop".11 Ranking first breaks the ties by position, so every decile gets exactly 600. The observed=True in the groupby keeps only the deciles that exist, which here is all ten, and passing it explicitly means the code does not depend on a default that has changed between pandas versions.
The top decile responds at 14.7%, 3.73 times the average, and holds 37% of all responders. The top four hold 81%. Notice the bumps: decile 3 responds at only 3.5% and decile 4 at 6.2%. With 600 customers and a handful of responders per decile, the observed rates are noisy. The predicted column falls smoothly, and as the calibration section shows, it tracks the observed rates well overall. That is why I make the depth decision on the predicted rates and use the observed ones as the check.
The gains chart puts the last column on a picture. The model's curve should bow above the diagonal, which is what random selection would capture.
The horizontal axis is the share of the file mailed, best scores first. The vertical axis is the share of all responders those customers contain. The height of the model line above the random one in the first deciles is where the money is. To draw it yourself, lift["gain"] plotted against the decile with matplotlib is enough, as in charts in Python. For how to annotate a chart like this so the depth decision jumps out, see focus attention on what matters.
Put money in the table: breakeven and depth
A lift table says who responds. The decision needs what each decile earns. Each brochure costs , £1.20 here, and each response brings a contribution margin of about £38 on an average spring order of £68.
Here is the profit from mailing decile , the number of customers in it, its response rate, the margin per response and the cost per brochure. is the breakeven rate: any decile responding above it pays for its brochures. For Priya, . Foundations: expected value and Foundations: marginal versus average
Example: from the lift table to a mailing depth
The test set has 600 customers per decile. The real file has 2,000, so the profit is scaled to the file:
cost, margin, per_decile = 1.20, 38.0, 2_000
breakeven = cost / margin
lift["profit"] = per_decile * (lift["predicted"] * margin - cost)
lift["profit_observed"] = per_decile * (lift["observed"] * margin - cost)
lift["cum_profit"] = lift["profit"].cumsum()
best_depth = int(lift["cum_profit"].idxmax())
print(round(breakeven, 4), best_depth) # 0.0316 4
print(lift[["predicted", "profit", "cum_profit", "profit_observed"]].round(3))
| Decile | Predicted rate | Decile profit £ | Cumulative profit £ | Profit at observed rate £ |
|---|---|---|---|---|
| 1 | 15.1% | 9,052 | 9,052 | 8,747 |
| 2 | 7.7% | 3,422 | 12,475 | 3,427 |
| 3 | 5.3% | 1,631 | 14,106 | 260 |
| 4 | 3.7% | 443 | 14,549 | 2,287 |
| 5 | 2.6% | minus 400 | 14,149 | minus 753 |
| 6 | 1.9% | minus 988 | 13,161 | minus 1,513 |
| 7 | 1.3% | minus 1,417 | 11,743 | minus 1,133 |
| 8 | 0.9% | minus 1,732 | 10,011 | minus 1,133 |
| 9 | 0.6% | minus 1,960 | 8,051 | minus 2,020 |
| 10 | 0.3% | minus 2,142 | 5,910 | minus 2,273 |
Decile 4 is predicted at 3.7%, just above the 3.16% breakeven, and adds £443. Decile 5 at 2.6% is below it and loses £400. The cumulative profit peaks after four deciles at £14,549, against £5,910 for mailing everyone. Both columns, predicted and observed, peak at the same depth. Mail 8,000 people, not 20,000: £14,400 less in print and postage, about two and a half times the profit. The Marketing Analytics chapter reached the same depth with £13,200 against £5,944, and the pair of results is the point: the same decision survives a fresh sample.
Each bar is the total profit if Priya mails every decile down to that one. Everything to the right of the peak is money spent to lose money.
How sure is the depth? The observed rate in decile 4 is 37 out of 600, with a standard error of . A 95% interval runs from about 4.2% to 8.1% on the observed rate, and decile 3's runs below the breakeven. Foundations: confidence intervals With 600 customers per decile the observed rates cannot settle the marginal decile on their own. That is the honest reason to decide on the predicted rates of a model whose calibration you have checked, which is the next step.
Calibration: the depth decision needs honest probabilities
Ranking only needs the order of the scores to be right. The breakeven rule compares an absolute probability with , so the probabilities themselves must be right too. A model is well calibrated when, among customers it scores at about 4%, about 4% respond. Unpenalised logistic regression tends to be well calibrated on its own, because of how its loss and its link function fit together.12
Example: predicted against observed, and the setting that breaks it
The decile table already holds the check: the predicted and observed columns.
print(lift[["predicted", "observed"]].round(3))
print(round(lift["predicted"].mean(), 4), round(base, 4)) # 0.0394 0.0393
Decile by decile the two columns wander around each other, as 600 customer samples do, and on average they agree almost exactly: 3.94% predicted against 3.93% observed. scikit learn's calibration_curve draws the same comparison as a chart if you want one.12
Now the setting that breaks it. Search for "imbalanced classes" and you will be told to pass class_weight="balanced". Here is what it does to the probabilities:
balanced = LogisticRegression(C=np.inf, class_weight="balanced", max_iter=1000)
balanced.fit(train[features], train["responded"])
p_bal = balanced.predict_proba(test[features])[:, 1]
print(round(p_bal.mean(), 3), round(roc_auc_score(test["responded"], p_bal), 3)) # 0.387 0.777
The AUC is unchanged at 0.777, because the ranking is the same. But the average predicted probability is now 38.7% on a file where 3.9% respond. Feed that into the breakeven rule and every decile clears 3.16%: you mail all 20,000 and lose the £8,600 the depth decision was meant to save. Weighting the classes moves every score up by the same amount on the log odds scale, and King and Zeng give the correction, which you subtract from each score:13
Here is the amount to subtract from the log odds, is the true share of responders and the share the model was trained to see, which "balanced" sets to 0.5. With that is . Foundations: probability
tau, y_bar = train["responded"].mean(), 0.5
delta = np.log(((1 - tau) / tau) * (y_bar / (1 - y_bar)))
p_fixed = 1 / (1 + np.exp(-(balanced.decision_function(test[features]) - delta)))
print(round(p_fixed.mean(), 4)) # 0.0389
Corrected, the average is back at 3.9%. My advice is simpler: with 552 responders in the training data, a logistic model does not need rebalancing. Leave class_weight alone and keep the probabilities honest.
A leakage test you can run in one line
The most expensive mistake in response modelling is a column that was measured after the mailing. A "customer status" field that the shop sets to active when someone orders looks innocent in the export. It is the outcome in disguise.
Example: what a leaking column does to the AUC
leaky = customers.copy()
leaky["status_active"] = np.where(leaky["responded"] == 1, 1, rng.binomial(1, 0.10, n))
tr, te = train_test_split(leaky, test_size=0.3, stratify=leaky["responded"], random_state=575)
cols = features + ["status_active"]
lk = LogisticRegression(C=np.inf, max_iter=1000).fit(tr[cols], tr["responded"])
print(round(roc_auc_score(te["responded"], lk.predict_proba(te[cols])[:, 1]), 3)) # 0.977
From 0.776 to 0.977 with one column, on a test set, so the split does not protect you. Leakage passes every holdout check because the leak is in the test set too. It only fails in the field, when the brochure goes out and the column is not yet filled in.
My rule of thumb: for a marketing response model, an AUC above about 0.9 is a reason to hunt for leakage before anyone celebrates. Then list every column with the date its value became known, and drop anything dated after the mailing. "Clicked the spring email" is fine if it means last spring's, and a leak if it means this spring's.
Score the file and keep two control groups
The checks passed, so the model is refitted on all 20,000 customers and scores the whole file. Then come two random groups that make next year possible. If this becomes a monthly job rather than a one off, put the code in a script with tests, as in a reproducible Python analysis workflow.
Read it top to bottom. A failed check goes back to the columns, never forward to the printer.
Example: the final mailing file
final = LogisticRegression(C=np.inf, max_iter=1000).fit(customers[features], customers["responded"])
customers["p_hat"] = final.predict_proba(customers[features])[:, 1]
customers["decile"] = pd.qcut(customers["p_hat"].rank(method="first", ascending=False),
10, labels=range(1, 11)).astype(int)
in_target = customers["decile"] <= best_depth
lottery = np.random.default_rng(2026).random(len(customers))
customers["group"] = "not mailed"
customers.loc[in_target, "group"] = "mailed"
customers.loc[in_target & (lottery < 0.10), "group"] = "control, not mailed"
customers.loc[~in_target & (lottery < 0.04), "group"] = "explore, mailed"
print(customers["group"].value_counts())
not mailed 11568
mailed 7193
control, not mailed 807
explore, mailed 432
Of the 8,000 customers in the top four deciles, 7,193 get the brochure and 807 are held back as an unmailed control. From the 12,000 in the deep deciles, 432 are mailed anyway as an exploration sample. That is 7,625 brochures, about £9,150 in print and postage.
Both groups exist for a reason the response model cannot see. The exploration sample keeps next year honest: if Priya only ever mails the top four deciles, next year's data contains responses only from them, and the model can never learn that deciles 5 to 10 have changed. The unmailed control answers a different question. A response model predicts who will order with the code. Some of those customers would have ordered anyway, brochure or not. The gap between the mailed group and the control in the same deciles is what the brochure caused, the incremental effect, and modelling that gap directly is called uplift modelling.14 The statistics of comparing those two groups are the subject of a later chapter of this series on A/B tests.
From order lines to a basket matrix
Now the second question, on the website. The shop's order export has one row per order line, not one row per basket. The reshape from long to wide is the one from joining and reshaping data, and the trap is again in the export: checkout tests are real orders in the data, and they always contain the products the developer was testing.
Example: 14,000 orders, 30 test orders and a crosstab
The block generates 14,000 real orders with seven hampers, in which offices buy more wine and more prosecco, cheese depends on wine, chocolate and basket size, and some customers buy two of the same hamper. Then it adds 30 test orders, each with wine and cheese.
rng_b = np.random.default_rng(700)
n_orders = 14_000
orders_b = pd.DataFrame({"order_id": np.arange(50_001, 50_001 + n_orders)})
orders_b["corporate"] = rng_b.binomial(1, 0.15, n_orders)
flags = pd.DataFrame({"order_id": orders_b["order_id"]})
flags["wine"] = rng_b.binomial(1, 0.068 + 0.5 * orders_b["corporate"])
flags["chocolate"] = rng_b.binomial(1, 0.13, n_orders)
flags["tea"] = rng_b.binomial(1, 0.06, n_orders)
flags["prosecco"] = rng_b.binomial(1, 0.04 + 0.08 * orders_b["corporate"])
flags["biscuits"] = rng_b.binomial(1, 0.08, n_orders)
nothing_yet = flags[["wine", "chocolate", "tea", "prosecco", "biscuits"]].sum(axis=1) == 0
flags["classic"] = np.where(nothing_yet, 1, rng_b.binomial(1, 0.05, n_orders))
n_other = flags[["tea", "prosecco", "biscuits", "classic"]].sum(axis=1)
cheese_score = (-2.80 + 1.10 * flags["wine"] - 0.45 * flags["chocolate"]
+ 0.60 * orders_b["corporate"] + 0.20 * n_other)
flags["cheese"] = rng_b.binomial(1, 1 / (1 + np.exp(-cheese_score)))
# from one column per hamper to one row per order line, like the shop export
lines = (flags.melt(id_vars="order_id", var_name="product", value_name="in_basket")
.query("in_basket == 1").drop(columns="in_basket"))
lines["quantity"] = 1 + rng_b.binomial(1, 0.08, len(lines)) # some buy two of the same
# 30 checkout tests, each with wine and cheese, from the shop's own address
test_ids = np.arange(90_001, 90_031)
lines = pd.concat([lines, pd.DataFrame({"order_id": np.repeat(test_ids, 2),
"product": ["wine", "cheese"] * 30, "quantity": 1})],
ignore_index=True)
orders_b = pd.concat([orders_b, pd.DataFrame({"order_id": test_ids, "corporate": 0})],
ignore_index=True)
orders_b["email_domain"] = np.where(orders_b["order_id"] >= 90_001,
"northgatehampers.example", "customer.example")
Building the basket matrix is two lines once the test orders are gone. pd.crosstab counts lines per order and product, and .gt(0) turns any count into "in the basket", so the quantity never inflates a pair:15
real_ids = orders_b.loc[orders_b["email_domain"] != "northgatehampers.example", "order_id"]
clean = lines[lines["order_id"].isin(real_ids)]
basket = pd.crosstab(clean["order_id"], clean["product"]).gt(0)
print(basket.shape) # (14000, 7)
print(basket[["wine", "cheese"]].sum().to_dict()) # {'wine': 1997, 'cheese': 1250}
print((basket["wine"] & basket["cheese"]).sum()) # 436
14,000 orders, wine in 1,997, cheese in 1,250, both in 436: the Marketing Analytics example had 2,000, 1,260 and 440. Leave the test orders in and cheese rises to 1,280 and the pair to 466, a 7% inflation of exactly the pair you were about to recommend. Test orders are never random. They cluster on whatever was being tested.
Support, confidence and lift in pandas
Association rules describe a pair "if A, then B" with three numbers.16
Here is the number of orders, the number containing , the number containing and the number containing both. , the support, is the share of all orders with . , the confidence, is the share of orders that also contain . divides the confidence by the support, so a lift of 1 means turns up with no more often than in any order. The Marketing Analytics chapter also uses the interest, , the same comparison as a difference. Foundations: probability
Example: wine and cheese, then every pair at once
N = len(basket)
both = (basket["wine"] & basket["cheese"]).sum()
support_cheese = basket["cheese"].mean()
confidence = both / basket["wine"].sum()
print(round(support_cheese, 4), round(confidence, 4),
round(confidence / support_cheese, 2), round(confidence - support_cheese, 3))
# 0.0893 0.2183 2.45 0.129
Cheese is in 8.9% of all orders and in 21.8% of wine orders, a lift of 2.45 and an interest of 0.129. The Marketing Analytics chapter had 9%, 22% and 2.44.
For every pair at once, one matrix product does it. With the basket as 0 and 1, B.T @ B counts, for each pair of products, the orders containing both, and its diagonal holds each product's own count:
B = basket.astype(int)
pair_counts = B.T @ B
support = pair_counts / N
conf = pair_counts.div(pd.Series(np.diag(pair_counts), index=B.columns), axis=0)
lift_pairs = conf.div(pd.Series(np.diag(support), index=B.columns), axis=1)
rules = (pd.DataFrame({"support": support.stack(), "confidence": conf.stack(),
"lift": lift_pairs.stack()})
.rename_axis(["antecedent", "consequent"]).reset_index()
.query("antecedent != consequent"))
print(rules.sort_values("lift", ascending=False).head(4).round(3))
| If the basket has | Then | Support | Confidence | Lift |
|---|---|---|---|---|
| cheese | wine | 0.031 | 0.349 | 2.45 |
| wine | cheese | 0.031 | 0.218 | 2.45 |
| wine | prosecco | 0.012 | 0.088 | 1.66 |
| prosecco | wine | 0.012 | 0.236 | 1.66 |
Lift is symmetric, confidence is not: 35% of cheese baskets contain wine, but only 22% of wine baskets contain cheese, because wine is the more popular hamper. And the counting says wine and prosecco also go together, with a lift of 1.66. Keep that pair in mind.
The same with mlxtend
If you prefer a library, mlxtend's apriori and association_rules produce the same table.17 mlxtend is maintained by Sebastian Raschka and widely used for this, and its version 0.24.0 came out in December 2025.18 One change trips up older tutorials: version 0.23.2 added a num_itemsets argument, the number of transactions, which broke calls without it until version 0.23.4 made it optional again.18 I pass it explicitly, so the code runs on any recent version.
from mlxtend.frequent_patterns import apriori, association_rules
itemsets = apriori(basket, min_support=0.01, use_colnames=True)
ml_rules = association_rules(itemsets, num_itemsets=len(basket),
metric="lift", min_threshold=1.0)
print(ml_rules[["antecedents", "consequents", "support", "confidence", "lift"]]
.sort_values("lift", ascending=False).head(4).round(3))
The top rows match the pandas table to the third decimal: cheese and wine at 2.445, wine and prosecco at 1.656. For seven hampers the matrix product is all you need. For thousands of products, apriori and its min_support threshold earn their place by never counting the pairs that are too rare to matter.
The logistic basket model holds the rest constant
Counting looks at one pair at a time. It cannot tell whether wine drives cheese or whether offices simply buy both. Logistic regression can: make the presence of cheese the outcome, and the rest of the basket plus the buyer type the predictors. This is the move the Marketing Analytics chapter makes, and in pandas the data is already in shape.
Here is the probability that the order contains the cheese hamper, , and are 1 or 0 for the wine hamper, the chocolate hamper and a corporate buyer, counts the other hampers in the basket, is Euler's number and each is the matching coefficient. Foundations: probability
Example: the cheese model on 14,000 orders
model_data = basket.astype(int).join(orders_b.set_index("order_id")["corporate"])
model_data["n_other"] = model_data[["tea", "prosecco", "biscuits", "classic"]].sum(axis=1)
cheese_model = smf.logit("cheese ~ wine + chocolate + corporate + n_other",
data=model_data).fit(disp=0)
print(pd.DataFrame({"coef": cheese_model.params,
"odds_ratio": np.exp(cheese_model.params)}).round(3))
ct = pd.crosstab(model_data["wine"], model_data["cheese"])
raw_or = (ct.loc[1, 1] / ct.loc[1, 0]) / (ct.loc[0, 1] / ct.loc[0, 0])
print(round(raw_or, 2), round(np.exp(cheese_model.params["wine"]), 2)) # 3.84 2.97
| Predictor | Coefficient | Odds ratio | Reading |
|---|---|---|---|
| Intercept | minus 2.822 | 0.059 | base odds of cheese |
| Wine hamper in basket | 1.087 | 2.97 | roughly triples the odds |
| Chocolate hamper in basket | minus 0.447 | 0.64 | a substitute, not a complement |
| Corporate buyer | 0.694 | 2.00 | offices build sets |
| Each other hamper in basket | 0.186 | 1.20 | bigger baskets get bigger |
The intercept here is lower than the Marketing Analytics chapter's minus 2.55, because in this generated shop almost every basket has at least one other hamper, so the "nothing else in the basket" case the intercept describes is rare. The other four lines read the same as there.
The comparison that matters is the raw odds ratio against the adjusted one. Counted straight from the crosstab, wine baskets have 3.84 times the odds of cheese. Holding the buyer type and the basket size constant, the model says 2.97. Part of "wine implies cheese" is offices buying both. The Marketing Analytics chapter found the same gap, 3.85 against 3.00.
Example: the pair that counting gets wrong
Now fit the same kind of model for prosecco, the pair with a lift of 1.66:
prosecco_model = smf.logit("prosecco ~ wine + cheese + chocolate + tea + biscuits + corporate",
data=model_data).fit(disp=0)
print(np.exp(prosecco_model.params[["wine", "corporate"]]).round(2).to_dict())
# {'wine': 0.94, 'corporate': 3.22}
Once the buyer type is in the model, wine's odds ratio for prosecco is 0.94, which is no effect at all. Corporate buyers have 3.22 times the odds of prosecco, and they also buy more wine, so the two hampers meet in office orders and nowhere else. A recommendation engine built on the lift of 1.66 would push prosecco at every private wine buyer for no reason.
The left pair survives the model, a little smaller. The right pair disappears. That is the whole case for the logistic basket model in one picture.
Turning the model into a recommendation
A recommendation needs a probability for each product not yet in the basket. Fit one model per product you might recommend, score the live basket, and show the best one or two. I add one rule beyond the Marketing Analytics chapter's floor of 12%: the probability must also clearly beat the product's own base rate, otherwise you are recommending a hamper because it is popular, which the bestseller list already does.
Example: what a wine basket gets recommended
products = ["wine", "cheese", "chocolate", "tea", "prosecco", "biscuits"]
models = {"cheese": cheese_model}
for product in ["prosecco", "chocolate", "tea"]:
others = " + ".join(p for p in products if p != product)
models[product] = smf.logit(f"{product} ~ {others} + corporate", data=model_data).fit(disp=0)
base_rate = basket.mean()
def recommend(row, models, floor=0.12, min_ratio=1.2, k=2):
"""Products not in the basket, above the floor and clearly above their base rate."""
picks = []
for product, m in models.items():
if row.get(product, 0) == 1:
continue
p = float(m.predict(pd.DataFrame([row])).iloc[0])
if p >= floor and p / base_rate[product] >= min_ratio:
picks.append((product, round(p, 3)))
return sorted(picks, key=lambda t: t[1], reverse=True)[:k]
office_wine = {"wine": 1, "cheese": 0, "chocolate": 0, "tea": 0, "prosecco": 0,
"biscuits": 0, "corporate": 1, "n_other": 0}
print(recommend(office_wine, models)) # [('cheese', 0.261)]
An office buyer with the wine hamper gets the cheese hamper suggested, at 26%. Chocolate would have scored 13.8% and cleared the 12% floor, but its base rate is 12.9%, so the wine basket tells you nothing about chocolate and the ratio rule drops it. Prosecco scores 11.1% for this office buyer, twice its base rate of 5.3%, because offices buy prosecco, wine or no wine, and it just misses the floor. Change corporate to 0 and the same wine basket scores prosecco at 3.7%, below its base rate. A rule built on the lift of 1.66 would have shown prosecco to both buyers. The model shows it to neither, and if prosecco ever does make the cut, it will be because of the office, not the wine.
Two cautions. The model says which hampers are bought together, not that showing cheese sells more cheese. The recommendation is a hypothesis, and a test on the checkout is the proof, which the later chapter on A/B tests covers. And with seven hampers, one model per product is exactly right. With hundreds of products you would move to methods built for large catalogues. The engineering of wiring a model like this into a shop is in building custom AI recommendations in Solidus.
The checks in one table
| Check | Code | What a pass looks like |
|---|---|---|
| Response flag net of refunds, staff and test orders | groupby("customer_id")["total"].sum() on a filtered export | refunded customers are not responders |
| Window in local time, across clock changes | pd.DateOffset, tz_convert | the window ends at local midnight |
| Collinearity | variance_inflation_factor | every VIF under about 5 |
| Penalty is a choice, not a default | LogisticRegression(C=np.inf) | statsmodels and scikit learn agree |
| Ranking on fresh customers | roc_auc_score on the test set | test AUC within a point or two of training |
| Leakage | list each column with its date | no AUC far above about 0.9 |
| Equal deciles despite ties | rank(method="first") before qcut | exactly one tenth per decile |
| Calibration | predicted against observed per decile | averages agree, no class_weight |
| Depth | cumulative profit | mail to the peak, not to the revenue peak |
| Control groups | random unmailed control and mailed exploration sample | both exist before the brochure goes out |
| Basket pairs | logistic model with buyer type | pairs that survive the model, not raw lift |
My view
My view: for a customer file of this size, logistic regression is the right first model, and often the last one. Gradient boosted trees can add a little lift by finding interactions on their own, but Priya's 788 responders are not much to learn from, and the odds ratio table is a conversation she can have with her accountant. I would only move to a more complex model when its gains chart on the test set beats this one by enough money to pay for the extra effort.
What I would not compromise on is everything around the model. The response flag built net of refunds and test orders, in local time. The test set. The profit column. The two control groups. Those are where response models fail in practice, and none of them needs a better algorithm. Data storytelling, analytics dashboards and Data Science are a core part of my work for clients, and if you want this built on your own shop data, the free workshop is where we agree what to model and what a good decision looks like. My prices are published on the pricing page, and the code, the accounts and the data stay yours.
Conclusion
Logistic regression in Python is two libraries with two jobs. statsmodels explains: odds ratios with intervals and a VIF check. scikit learn scores: a stratified split, an explicitly unpenalised fit, an AUC on customers the model never saw. pandas turns the scores into a decision, with rank and qcut for clean deciles and a profit column that shows where the next brochure stops paying. For Priya that is the top four deciles, 8,000 people, and about two and a half times the profit of mailing everyone.
The basket side uses the same tools. A crosstab and one matrix product give support, confidence and lift for every pair, and mlxtend does the same with one function call. The logistic basket model then shows which pairs survive the buyer type: wine and cheese do, wine and prosecco do not.
The next chapter of this series adds time: not whether a customer responds, but how long they stay, with survival analysis and customer lifetime value.
