Statistical modeling with Python · Lesson 16 of 16
Project: predict which customers buy
An end-to-end logistic regression: explore 120 shoppers, fit a GLM, drop a weak predictor, read odds ratios, check AUC and chart the probability.
Time to put the course together. An online shop followed 120 visitors last month: their age, how many times they visitsed the site, the minutes of their last visit, the device they used, and whether they bought (1) or not (0). The question from the manager: who buys, and how sure are we?
import numpy as np
import pandas as pd
import statsmodels.api as sm
import statsmodels.formula.api as smf
df = pd.read_csv("customers.csv")
print(df.head())
print(f"rows: {len(df)}, bought: {df['bought'].mean():.1%}")
print(df.groupby("device")["bought"].mean().round(3))
print(df.groupby("bought")[["age", "visits", "minutes"]].mean().round(1)) age visits minutes device bought
0 47 7 24.3 mobile 1
1 68 4 10.7 mobile 0
2 33 1 22.2 mobile 0
3 29 1 3.5 desktop 0
4 50 1 19.6 desktop 0
rows: 120, bought: 45.0%
device
desktop 0.638
mobile 0.329
Name: bought, dtype: float64
age visits minutes
bought
0 40.6 3.6 14.4
1 44.8 6.7 17.9Step 1, explore. Buyers visited more often and stayed longer, desktop users buy about twice as often as mobile users, and buyers are a little older. These are raw comparisons; the model checks each one with the others held fixed.
Step 2: fit a logistic GLM
import numpy as np
import pandas as pd
import statsmodels.api as sm
import statsmodels.formula.api as smf
df = pd.read_csv("customers.csv")
model = smf.glm('bought ~ age + visits + minutes + C(device, Treatment("mobile"))',
data=df, family=sm.families.Binomial()).fit()
def show_p(p):
return "< 0.001" if p < 0.001 else f"{p:.3f}"
out = pd.DataFrame({"coef": model.params.round(3), "p": model.pvalues.map(show_p)})
out.index = ["Intercept", "desktop", "age", "visits", "minutes"]
print(out)
print(f"AIC: {model.aic:.1f}")coef p Intercept -5.172 < 0.001 desktop 1.711 < 0.001 age 0.019 0.217 visits 0.388 < 0.001 minutes 0.095 0.003 AIC: 124.6
Mobile is the most common device, so Treatment("mobile") makes it the reference level: the device coefficient compares desktop with mobile. Its long name is renamed to desktop to keep the table narrow.
Step 3: is age worth keeping?
import numpy as np
import pandas as pd
import statsmodels.api as sm
import statsmodels.formula.api as smf
df = pd.read_csv("customers.csv")
from scipy import stats
full = smf.glm('bought ~ age + visits + minutes + C(device, Treatment("mobile"))',
data=df, family=sm.families.Binomial()).fit()
small = smf.glm('bought ~ visits + minutes + C(device, Treatment("mobile"))',
data=df, family=sm.families.Binomial()).fit()
lr = 2 * (full.llf - small.llf)
print(f"LR = {lr:.2f}, p = {stats.chi2.sf(lr, 1):.3f}")
print(f"AIC with age: {full.aic:.1f}, without: {small.aic:.1f}")LR = 1.55, p = 0.213 AIC with age: 124.6, without: 124.2
Age has a large p-value. A likelihood-ratio test of the model with and without it settles the question.
p is far above 0.05 and the AIC even improves slightly without it (Comparing models: AIC and cross-validation): age adds nothing once visits, minutes and device are known. We keep the simpler model. (That does not prove age has no effect at all; this sample just cannot see one.)
Step 4: odds ratios in plain words
import numpy as np
import pandas as pd
import statsmodels.api as sm
import statsmodels.formula.api as smf
df = pd.read_csv("customers.csv")
model = smf.glm('bought ~ visits + minutes + C(device, Treatment("mobile"))',
data=df, family=sm.families.Binomial()).fit()
ci = np.exp(model.conf_int())
table = pd.DataFrame({"OR": np.exp(model.params), "low": ci[0], "high": ci[1]})
table.index = ["Intercept", "desktop", "visits", "minutes"]
print(table.round(2))OR low high Intercept 0.01 0.00 0.07 desktop 5.46 2.04 14.61 visits 1.47 1.25 1.72 minutes 1.10 1.03 1.17
- visits, OR 1.47: each extra visit multiplies the odds of buying by about 1.5 (47% higher odds). Five more visits: 1.47 ** 5 ≈ 6.9 times the odds.
- minutes, OR 1.10: each extra minute on the site raises the odds by about 10%; ten minutes more is about 1.1 ** 10 ≈ 2.6 times the odds.
- desktop, OR about 5: at the same visits and minutes, desktop visitors have roughly five times the odds of buying of mobile visitors. The interval is wide but far from 1: worth telling the mobile team.
Step 5: how good is it?
import numpy as np
import pandas as pd
import statsmodels.api as sm
import statsmodels.formula.api as smf
df = pd.read_csv("customers.csv")
model = smf.glm('bought ~ visits + minutes + C(device, Treatment("mobile"))',
data=df, family=sm.families.Binomial()).fit()
from sklearn.metrics import roc_auc_score, confusion_matrix, accuracy_score
prob = model.predict(df)
pred = (prob >= 0.5).astype("int64")
print(f"AUC: {roc_auc_score(df['bought'], prob):.3f}")
print(f"accuracy: {accuracy_score(df['bought'], pred):.3f}"
f" (baseline {max(df['bought'].mean(), 1 - df['bought'].mean()):.3f})")
print(confusion_matrix(df["bought"], pred))AUC: 0.846 accuracy: 0.808 (baseline 0.550) [[54 12] [11 43]]
An AUC around 0.85 means the model ranks buyers above non-buyers well, and the accuracy of 81% is far above the 55% baseline of always guessing the more common answer. These figures come from the training data; a cross-validated AUC would be a little lower.
Step 6: predictions and a chart for the manager
import numpy as np
import pandas as pd
import statsmodels.api as sm
import statsmodels.formula.api as smf
df = pd.read_csv("customers.csv")
model = smf.glm('bought ~ visits + minutes + C(device, Treatment("mobile"))',
data=df, family=sm.families.Binomial()).fit()
import matplotlib.pyplot as plt
grid = pd.DataFrame({"visits": np.arange(1, 13), "minutes": 15})
for device, color in [("mobile", "steelblue"), ("desktop", "darkorange")]:
p = model.predict(grid.assign(device=device))
plt.plot(grid["visits"], p, marker="o", color=color, label=device)
print(device, (p.iloc[[0, 4, 9]] * 100).round().astype("int64").tolist(), "% at 1, 5, 10 visits")
plt.title("Chance of buying (15-minute visits)")
plt.xlabel("Visits last month")
plt.ylabel("Probability of buying")
plt.ylim(0, 1)
plt.legend()
plt.show()mobile [7, 27, 71] % at 1, 5, 10 visits desktop [30, 67, 93] % at 1, 5, 10 visits

The story for the manager, in one paragraph: returning visitors are far more likely to buy, and desktop visitors buy much more than mobile visitors with the same behaviour. A mobile visitor who comes 5 times with 15-minute visits has roughly a one-in-four chance of buying (27%); on desktop it is about two in three (67%). The mobile checkout deserves a look, with one caveat: this is observational data, so desktop and mobile visitors may differ in other ways (why they came, what they want to buy). The model shows the gap, not its cause.
✎ Exercise
A new visitor uses mobile, has 6 visits and spent 20 minutes. Another uses desktop with 2 visits and 10 minutes. Print both predicted probabilities of buying, rounded to 3 decimals.
Hint: Build a DataFrame with the columns visits, minutes and device, then model.predict(new).round(3).
import numpy as np
import pandas as pd
import statsmodels.api as sm
import statsmodels.formula.api as smf
df = pd.read_csv("customers.csv")
model = smf.glm('bought ~ visits + minutes + C(device, Treatment("mobile"))',
data=df, family=sm.families.Binomial()).fit()
# your code here
Expected output:
0 0.462 1 0.282 dtype: float64
Show a solution
import numpy as np
import pandas as pd
import statsmodels.api as sm
import statsmodels.formula.api as smf
df = pd.read_csv("customers.csv")
model = smf.glm('bought ~ visits + minutes + C(device, Treatment("mobile"))',
data=df, family=sm.families.Binomial()).fit()
new = pd.DataFrame({"visits": [6, 2], "minutes": [20, 10],
"device": ["mobile", "desktop"]})
print(model.predict(new).round(3))0 0.462 1 0.282 dtype: float64
Check yourself
1. The odds ratio of visits is 1.47. Which sentence is right?
Odds ratios multiply odds; for probabilities, predict them as in step 6.
2. Why was age dropped?
A large LR-test p-value and an almost unchanged AIC mean the simpler model is as good.
3. The manager asks for 'the chance that a mobile visitor with 5 visits buys'. What do you give?
Predicted probabilities answer 'what is the chance' questions directly.