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

ln⁡(p‘1−p‘)=β0+β1x1+β2x2+⋯+βkxk\ln\left(\frac{p}{`1-p`}\right) = \beta_0 + \beta_1 x_1 + \beta_2 x_2 + \dots + \beta_k x_k

Here pp is the probability that a customer responds, p1−p\frac{p}{1-p} is the odds, ln⁡\ln is the natural logarithm, x1x_1 to xkx_k are the six columns of the customer file, β0\beta_0 is the intercept and each βj\beta_j is the change in the log odds for one unit more of xjx_j, 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)
VariableCoefficientStd. errorOdds ratio95% interval
Interceptminus 3.4050.1570.0330.024 to 0.045
Months since last orderminus 0.0930.0050.9110.903 to 0.920
Orders in the last 24 months0.2840.0351.3281.240 to 1.423
Gift buyer0.5580.0751.7471.508 to 2.024
Corporate account0.3700.1101.4481.168 to 1.796
Clicked last spring's email0.7920.0872.2071.861 to 2.618
Average order value, per £100.0560.0221.0581.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 0.91112=0.330.911^{12} = 0.33 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

VIFj=11−Rj2\text{VIF}_j = \frac{1}{1 - R_j^2}

Here VIFj\text{VIF}_j is the variance inflation factor of column jj, and Rj2R_j^2 is the share of the variation in xjx_j explained by regressing it on all the other columns. A VIF of 1 means xjx_j 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)
Columnstatsmodelsscikit learn, no penaltyscikit learn, default
Interceptminus 3.363minus 3.365minus 3.359
Months since last orderminus 0.094minus 0.094minus 0.094
Orders in 24 months0.2940.2940.294
Gift buyer0.4910.4920.488
Corporate0.3800.3760.370
Clicked last spring0.8500.8500.841
Order value per £100.0510.0510.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.

Liftd=rdrˉ\text{Lift}_d = \frac{r_d}{\bar{r}}

Here Liftd\text{Lift}_d is the lift of decile dd, rdr_d the response rate within that decile and rˉ\bar{r} 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))
DecileCustomersRespondersPredicted rateObserved rateLiftShare of responders so far
16008815.1%14.7%3.7337%
2600467.7%7.7%1.9557%
3600215.3%3.5%0.8966%
4600373.7%6.2%1.5781%
5600132.6%2.2%0.5587%
660071.9%1.2%0.3090%
7600101.3%1.7%0.4294%
8600100.9%1.7%0.4298%
960030.6%0.5%0.1399.6%
1060010.3%0.2%0.04100%

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.

Mailing the top 10% of test customers by score captures 37% of all responders, the top 20% captures 57%, the top 40% captures 81% and the top 60% captures 90%. Random selection captures the same share of responders as the share of customers mailed. Tap or click to enlarge

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 cc, £1.20 here, and each response brings a contribution margin mm of about £38 on an average spring order of £68.

πd=nd(rd m−c)r∗=cm\pi_d = n_d \left( r_d \, m - c \right) \qquad r^* = \frac{c}{m}

Here πd\pi_d is the profit from mailing decile dd, ndn_d the number of customers in it, rdr_d its response rate, mm the margin per response and cc the cost per brochure. r∗r^* is the breakeven rate: any decile responding above it pays for its brochures. For Priya, r∗=1.20/38=3.16%r^* = 1.20 / 38 = 3.16\%. 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))
DecilePredicted rateDecile profit £Cumulative profit £Profit at observed rate £
115.1%9,0529,0528,747
27.7%3,42212,4753,427
35.3%1,63114,106260
43.7%44314,5492,287
52.6%minus 40014,149minus 753
61.9%minus 98813,161minus 1,513
71.3%minus 1,41711,743minus 1,133
80.9%minus 1,73210,011minus 1,133
90.6%minus 1,9608,051minus 2,020
100.3%minus 2,1425,910minus 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.

Cumulative campaign profit, using the predicted response rate of each decile scaled to 2,000 customers, rises from £9,052 after decile 1 to a peak of £14,549 after decile 4, then falls to £5,910 when all ten deciles are mailed. Tap or click to enlarge

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 0.062×0.938/600=0.0098\sqrt{0.062 \times 0.938 / 600} = 0.0098. 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 c/mc / m, 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

δ=ln⁡[(1−ττ)(yˉ1−yˉ)]\delta = \ln\left[\left(\frac{1-\tau}{\tau}\right)\left(\frac{\bar{y}}{1-\bar{y}}\right)\right]

Here δ\delta is the amount to subtract from the log odds, τ\tau is the true share of responders and yˉ\bar{y} the share the model was trained to see, which "balanced" sets to 0.5. With τ=0.0394\tau = 0.0394 that is ln⁡(24.4)=3.19\ln(24.4) = 3.19. 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.

Tap or click to enlarge

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

supp(B)=nBN,conf(A→B)=nABnA,lift(A→B)=conf(A→B)supp(B)\text{supp}(B) = \frac{n_B}{N}, \qquad \text{conf}(A \to B) = \frac{n_{AB}}{n_A}, \qquad \text{lift}(A \to B) = \frac{\text{conf}(A \to B)}{\text{supp}(B)}

Here NN is the number of orders, nBn_B the number containing BB, nAn_A the number containing AA and nABn_{AB} the number containing both. supp(B)\text{supp}(B), the support, is the share of all orders with BB. conf(A→B)\text{conf}(A \to B), the confidence, is the share of AA orders that also contain BB. lift(A→B)\text{lift}(A \to B) divides the confidence by the support, so a lift of 1 means BB turns up with AA no more often than in any order. The Marketing Analytics chapter also uses the interest, conf(A→B)−supp(B)\text{conf}(A \to B) - \text{supp}(B), 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 hasThenSupportConfidenceLift
cheesewine0.0310.3492.45
winecheese0.0310.2182.45
wineprosecco0.0120.0881.66
proseccowine0.0120.2361.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.

P(cheese∣basket)=11+e−(β0+βwinexwine+βchocxchoc+βcorpxcorp+βnxn)P(\text{cheese} \mid \text{basket}) = \frac{1}{1 + e^{-(\beta_0 + \beta_{\text{wine}} x_{\text{wine}} + \beta_{\text{choc}} x_{\text{choc}} + \beta_{\text{corp}} x_{\text{corp}} + \beta_{n} x_{n})}}

Here P(cheese∣basket)P(\text{cheese} \mid \text{basket}) is the probability that the order contains the cheese hamper, xwinex_{\text{wine}}, xchocx_{\text{choc}} and xcorpx_{\text{corp}} are 1 or 0 for the wine hamper, the chocolate hamper and a corporate buyer, xnx_n counts the other hampers in the basket, ee is Euler's number and each β\beta 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
PredictorCoefficientOdds ratioReading
Interceptminus 2.8220.059base odds of cheese
Wine hamper in basket1.0872.97roughly triples the odds
Chocolate hamper in basketminus 0.4470.64a substitute, not a complement
Corporate buyer0.6942.00offices build sets
Each other hamper in basket0.1861.20bigger 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.

For wine and cheese, the raw odds ratio from counting is 3.84 and the model odds ratio holding buyer type and basket size constant is 2.97. For wine and prosecco, counting gives a lift of 1.66 and a raw odds ratio of 1.94, while the model odds ratio is 0.94, no effect once corporate buyers are accounted for. Tap or click to enlarge

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.

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

CheckCodeWhat a pass looks like
Response flag net of refunds, staff and test ordersgroupby("customer_id")["total"].sum() on a filtered exportrefunded customers are not responders
Window in local time, across clock changespd.DateOffset, tz_convertthe window ends at local midnight
Collinearityvariance_inflation_factorevery VIF under about 5
Penalty is a choice, not a defaultLogisticRegression(C=np.inf)statsmodels and scikit learn agree
Ranking on fresh customersroc_auc_score on the test settest AUC within a point or two of training
Leakagelist each column with its dateno AUC far above about 0.9
Equal deciles despite tiesrank(method="first") before qcutexactly one tenth per decile
Calibrationpredicted against observed per decileaverages agree, no class_weight
Depthcumulative profitmail to the peak, not to the revenue peak
Control groupsrandom unmailed control and mailed exploration sampleboth exist before the brochure goes out
Basket pairslogistic model with buyer typepairs 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.

If you have a customer file and a campaign coming up, bring both to the free workshop: we agree what to model and where the decile table should draw the line, and the first two weeks of work are on me.

Sources

  1. 1.

    pandas development team, What's new in 3.0.0 (January 21, 2026): dedicated string data type by default, consistent copy and view behaviour with Copy on Write, pandas documentation, 2026, https://pandas.pydata.org/docs/whatsnew/v3.0.0.html

  2. 2.

    scikit learn developers, sklearn.linear_model.LogisticRegression, scikit learn 1.8 documentation, 2025, https://scikit-learn.org/1.8/modules/generated/sklearn.linear_model.LogisticRegression.html

  3. 3.

    Wes McKinney, Python for Data Analysis, 3rd edition, O'Reilly, 2022, chapter 12, Introduction to Modeling Libraries in Python, https://wesmckinney.com/book/modeling.html

  4. 4.

    Apple, Mail Privacy Protection and privacy, Apple Legal, https://www.apple.com/legal/privacy/data/en/mail-privacy-protection/

  5. 5.

    pandas development team, pandas.tseries.offsets.DateOffset, pandas documentation, https://pandas.pydata.org/docs/reference/api/pandas.tseries.offsets.DateOffset.html

  6. 6.

    UCLA Office of Advanced Research Computing, FAQ: How do I interpret odds ratios in logistic regression?, https://stats.oarc.ucla.edu/other/mult-pkg/faq/general/faq-how-do-i-interpret-odds-ratios-in-logistic-regression/

  7. 7.

    statsmodels developers, statsmodels.discrete.discrete_model.Logit, statsmodels 0.14 documentation, https://www.statsmodels.org/stable/generated/statsmodels.discrete.discrete_model.Logit.html

  8. 8.

    statsmodels developers, statsmodels.stats.outliers_influence.variance_inflation_factor, statsmodels 0.14 documentation, https://www.statsmodels.org/stable/generated/statsmodels.stats.outliers_influence.variance_inflation_factor.html, and Penn State Eberly College of Science, STAT 462 Applied Regression Analysis, 10.7 Detecting Multicollinearity Using Variance Inflation Factors, https://online.stat.psu.edu/stat462/node/180/

  9. 9.

    scikit learn developers, sklearn.model_selection.train_test_split, scikit learn 1.8 documentation, 2025, https://scikit-learn.org/1.8/modules/generated/sklearn.model_selection.train_test_split.html

  10. 10.

    Tom Fawcett, An introduction to ROC analysis, Pattern Recognition Letters, volume 27, issue 8, 2006, pages 861 to 874, https://doi.org/10.1016/j.patrec.2005.10.010, and scikit learn developers, sklearn.metrics.roc_auc_score, scikit learn 1.8 documentation, https://scikit-learn.org/1.8/modules/generated/sklearn.metrics.roc_auc_score.html

  11. 11.

    pandas development team, pandas.qcut, pandas documentation, https://pandas.pydata.org/docs/reference/api/pandas.qcut.html

  12. 12.

    scikit learn developers, Probability calibration, scikit learn 1.8 user guide, 2025, https://scikit-learn.org/1.8/modules/calibration.html

  13. 13.

    Gary King and Langche Zeng, Logistic Regression in Rare Events Data, Political Analysis, volume 9, issue 2, 2001, https://gking.harvard.edu/files/0s.pdf

  14. 14.

    Pierre Gutierrez and Jean Yves Gérardy, Causal Inference and Uplift Modelling: A Review of the Literature, Proceedings of Machine Learning Research, volume 67, 2017, https://proceedings.mlr.press/v67/gutierrez17a.html

  15. 15.

    pandas development team, pandas.crosstab, pandas documentation, https://pandas.pydata.org/docs/reference/api/pandas.crosstab.html

  16. 16.

    Sebastian Raschka, association_rules: association rules generation from frequent itemsets, mlxtend user guide, citing Agrawal, Imielinski and Swami, SIGMOD 1993, for support and confidence, and Brin, Motwani, Ullman and Tsur, 1997, for lift, https://rasbt.github.io/mlxtend/user_guide/frequent_patterns/association_rules/

  17. 17.

    Sebastian Raschka, apriori: frequent itemsets via the Apriori algorithm, and association_rules, mlxtend user guide, https://rasbt.github.io/mlxtend/user_guide/frequent_patterns/apriori/

  18. 18.

    Sebastian Raschka, mlxtend release notes, versions 0.23.2 (5 November 2024), 0.23.4 (25 November 2024) and 0.24.0 (13 December 2025), https://rasbt.github.io/mlxtend/CHANGELOG/

Shelter

I’m running the London Marathon for Shelter. Sunday 25 April 2027

My personal fundraiser. Shelter, the National Campaign for Homeless People Limited, registered charity 263710 (England and Wales) and SC002327 (Scotland), registered with the Fundraising Regulator.

Donate to Shelter