Statistical models in Python: statsmodels to explain, scikit learn to predict

TL;DR

Difficulty: Intermediate

statsmodels and scikit learn fit the same equations but answer different questions. Ask whether the decision is about a lever (change something for everyone) or about a row (act on each customer or order).

  • Lever: statsmodels. Name the reference, read each effect with its interval, use robust standard errors, and know that every variable you add changes what the others mean.
  • Row: scikit learn. Split by time, choose with cross validation, report the error in money against a baseline, keep preparation in a pipeline.
  • The timestamp test: drop any column that becomes known after the moment of prediction.
  • In the example, discount codes cost about €1.55 per order, and order value cannot usefully be predicted at arrival: the best model beats the average by about 4%, while two leaky models look about 48% better.

Python has two libraries that both fit a regression, and the difference between them is not the maths. statsmodels is built to explain, scikit learn to predict. This chapter takes both through one question from an example shop, with every line of code, and shows how to read a regression table honestly and how to catch overfitting and data leakage before they reach a decision.

Two libraries, because there are two questions

Python has two libraries that both fit a regression, and beginners reasonably ask why. statsmodels and scikit learn can produce the very same coefficients from the very same data. The difference is not the maths. It is the question each one is built to answer.

  • statsmodels explains. It tells you how much order value changes when one thing changes, how sure you can be, and whether the model's assumptions hold. Its main output is a table you read.
  • scikit learn predicts. It tells you how close a model's guesses come on data it has never seen. Its main output is an error you measure.

Leo Breiman called these the two cultures of statistical modelling: one assumes a model of how the data came about and studies it, the other treats the mechanism as unknown and judges a model only by how well it predicts1. Galit Shmueli later showed that explaining and predicting need different choices at almost every step, from which variables to include to how you judge success2.

Here is the rule of thumb I use to pick, and it is the strongest idea in this chapter:

Is the decision about a lever or about a row? A lever is something you change for everyone: the discount policy, the channel budget, the price of a range. To pull a lever well you need an effect and its uncertainty, so you need statsmodels. A row is one customer, one order, one day: who gets the email, which order to check for fraud, how much stock to order for Tuesday. To act on rows well you need an error measured honestly on new rows, so you need scikit learn.

And one check that saves more marketing models than any algorithm: the timestamp test. For every column, write down the moment it becomes known. If that moment is after the moment you want to predict, the column goes, however much it helps the score.

This chapter takes both libraries through one question from the example shop, end to end, with every line of code. It builds on group by and pivot tables in pandas, because a model is a group by with more than one grouping at a time.

Example: Áine's question, and Darragh's two answers

The example is invented, and it is the one this whole series uses. Ardmore Home is an online homeware shop in Sligo (ardmorehome.example) selling candles, ceramics and textiles: about 1,200 products, about 48,000 orders a year from about 21,000 customers, an average order value of €66 and a gross margin of 52%. Áine founded it. Darragh is the analyst.

Áine asks: "What drives order value? And can we tell, when someone lands on the site, what their order will be worth?"

That is two questions in one sentence, and Darragh answers them separately:

  1. What drives order value? That is about levers. Do discount codes raise or lower the basket? Do paid social customers really spend less, or are they just newer? Darragh answers it with statsmodels.
  2. What will this visitor's order be worth? That is about rows. If a model could guess each visitor's order value on arrival, the shop could show a different homepage or a different offer. Darragh answers it with scikit learn, and measures how good the guess really is.
Tap or click to enlarge

If you only read one section

For the person who commissions this kind of work and will never run the code, here is the whole chapter in five points.

  • Ask which question the model answers. An explanation model gives you effects ("discount orders are €1.55 lower, give or take a euro"). A prediction model gives you an error ("our guess is off by €31 on average"). A report that mixes the two is usually wrong about both.
  • An effect needs its interval. "Paid social orders are €14.39 lower" means little until you add "between €13.06 and €15.72". If the interval includes zero, the honest summary is "no clear difference".
  • What else is in the model changes what a number means. In the example, the discount effect is minus €1.55 when the model ignores basket size and minus €11.18 when it holds basket size fixed. Both are correct. They answer different questions.
  • A prediction needs a baseline. In the example the best honest model beats "guess the average" by about 4%. That is the truth about order value at the moment of arrival, and it is worth knowing before anyone builds a personalised homepage on it.
  • A score that looks too good is usually leakage. Add one column from the customer export and the same model "improves" by 48%. It is using the future. The timestamp test catches it in a minute.

Setting up: the versions this chapter uses

This chapter is written as of October 2025. Python 3.14 came out on 7 October 20253. I ran every block on Python 3.13 with pandas 2.3.3, NumPy 2.3.4, statsmodels 0.14.5 and scikit learn 1.7.2, the current releases at the time, and all four publish installers for 3.14 as well4. If you set up your environment as in the first chapter of this series, install the two modelling libraries like this:

python -m pip install "pandas==2.3.3" "numpy==2.3.4" "statsmodels==0.14.5" "scikit-learn==1.7.2"

Pinning the versions is not pedantry. A model's numbers should not change because a library changed underneath it, and the closing chapter of this series, on a reproducible workflow, builds on exactly this habit.

Wes McKinney's Python for Data Analysis covers this ground in its chapter 12, a short introduction to both libraries5. Like this series, the third edition already seeds its examples with NumPy's default_rng, the approach NumPy recommends for new code6 and the one explained in the NumPy chapter. One thing has moved on since the book: it builds design matrices with the Patsy library directly. statsmodels 0.14 still uses Patsy under the hood for its formulas7, but Patsy itself is no longer actively developed and names Formulaic as its successor8. For you that changes nothing today: write formulas through statsmodels and let it handle the translation.

The example data: a year of orders

The data comes first, generated in code so every number in this chapter can be reproduced. It is one row per order, already cleaned the way the cleaning chapter describes: no test orders, no staff orders, refunds handled. Order times are stored in UTC and converted to the shop's local time only where a date matters, as in the time series chapter.

Read the code once for its structure. It is split into what the shop knows when a visitor arrives (channel, device, discount code in the link, customer history) and what only happens at checkout (how many items go in the basket). That split will matter later.

import numpy as np
import pandas as pd

rng = np.random.default_rng(11)

# Customers, and how many orders each places in the year
n_customers = 21_000
orders_per_customer = rng.geometric(p=1 / 2.29, size=n_customers)
spend_level = rng.lognormal(mean=0.0, sigma=0.25, size=n_customers)  # some spend more

customer_id = np.repeat(np.arange(1, n_customers + 1), orders_per_customer)
n = customer_id.size

# Order times in UTC, 1 October 2024 to 30 September 2025, busier in winter
days = pd.date_range("2024-10-01", periods=365, freq="D", tz="UTC")
month_weight = {10: 0.9, 11: 1.3, 12: 1.6, 1: 0.8, 2: 0.8, 3: 0.9,
                4: 0.9, 5: 0.9, 6: 0.9, 7: 0.85, 8: 0.85, 9: 0.9}
w = np.array([month_weight[d.month] for d in days])
day = rng.choice(days, size=n, p=w / w.sum())
order_time = pd.DatetimeIndex(day) + pd.to_timedelta(rng.integers(0, 86_400, n), unit="s")

orders = (pd.DataFrame({"customer_id": customer_id, "order_time": order_time})
          .sort_values("order_time", ignore_index=True))

# What the shop knows when a visitor arrives
orders["prior_orders"] = orders.groupby("customer_id").cumcount()
orders["returning"] = (orders["prior_orders"] > 0).astype(int)

channels = ["organic search", "paid search", "paid social", "email", "direct", "referral"]
p_new = [0.32, 0.27, 0.22, 0.03, 0.10, 0.06]   # first orders
p_ret = [0.28, 0.17, 0.08, 0.24, 0.18, 0.05]   # repeat orders
u = rng.random(n)
idx = np.where(orders["returning"] == 1,
               np.searchsorted(np.cumsum(p_ret), u),
               np.searchsorted(np.cumsum(p_new), u))
orders["channel"] = np.array(channels)[np.minimum(idx, 5)]

orders["mobile"] = (rng.random(n) < 0.62).astype(int)
orders["discount"] = (rng.random(n) < np.where(orders["channel"] == "email", 0.35, 0.12)).astype(int)
orders["category"] = rng.choice(["candles", "ceramics", "textiles"], size=n, p=[0.45, 0.30, 0.25])
local_time = orders["order_time"].dt.tz_convert("Europe/Dublin")
orders["december"] = (local_time.dt.month == 12).astype(int)

# What happens in the basket, known only at checkout
lam = (orders["category"].map({"candles": 1.3, "ceramics": 0.75, "textiles": 0.55})
       + 0.45 * orders["december"] + 0.35 * orders["discount"] + 0.25 * orders["returning"]
       - 0.35 * (orders["channel"] == "paid social") - 0.15 * orders["mobile"])
orders["items"] = 1 + rng.poisson(np.clip(lam, 0.05, None))

price = orders["category"].map({"candles": 23.9, "ceramics": 37.55, "textiles": 46.1})
orders["order_value"] = (orders["items"] * price
                         * spend_level[orders["customer_id"] - 1]
                         * np.where(orders["discount"] == 1, 0.85, 1.0)
                         * np.where(orders["channel"] == "paid social", 0.95, 1.0)
                         * rng.lognormal(-0.03, 0.25, n)).round(2)

print(len(orders), orders["customer_id"].nunique(), round(orders["order_value"].mean(), 2))
# 47710 21000 66.2

That is 47,710 orders from 21,000 customers with an average order value of €66.20. The category column is the category of the page the visitor landed on, so it is known on arrival.

Because this is simulated, I know the truth that generated it, which real data never tells you. That is the point of simulating: you can check whether a method finds what is really there. In the simulation, a discount takes 15% off each item but nudges people to add items. Paid social visitors put fewer items in the basket and pay about 5% less per item. Returning customers and December add items. Keep those facts in mind, and watch which method recovers them.

Example: the first look, before any model

Before any model, a plain group by, exactly as in the group by chapter:

print(orders.groupby("channel")["order_value"].agg(orders="size", aov="mean").round(2))
#                 orders    aov
# direct            6826  68.97
# email             7070  70.70
# organic search   14162  68.54
# paid search      10275  67.12
# paid social       6786  51.75
# referral          2591  68.08

Paid social orders average €51.75, about €17 below the rest. Áine's instinct is to conclude that paid social brings poorer customers. But paid social also brings mostly first time buyers, and first orders are smaller everywhere. A table by one variable cannot separate those two stories. A regression can, because it compares like with like on several variables at once.

statsmodels: a model you can read

statsmodels is a library for estimating statistical models and testing hypotheses about them. Its formula interface lets you write a model the way you would say it: "order value depends on channel, category, discount, returning, device and December".

Example: the first regression, in one formula

import statsmodels.api as sm
import statsmodels.formula.api as smf

formula = ('order_value ~ C(channel, Treatment("direct")) + C(category)'
           ' + discount + returning + mobile + december')
explain = smf.ols(formula, data=orders).fit(cov_type="HC3")
print(explain.summary())

Each part of that formula does one job:

  • order_value ~ ... puts the outcome on the left and the explanations on the right.
  • C(channel, Treatment("direct")) turns the text column into dummy variables, one 0 or 1 column per channel, and makes direct the reference. Every channel effect is then "compared with direct".
  • C(category) does the same for category, with candles as the reference (the first in alphabetical order, the default).
  • discount, returning, mobile and december are already 0 or 1, so their effect reads as "the difference when this is true".
  • smf.ols is ordinary least squares, the classic linear regression. fit(cov_type="HC3") asks for robust standard errors. I explain why in a moment.

The summary prints a long table. Here is the part that matters, rounded, with the reference categories named:

TermEffect on order value95% interval
Intercept (direct, candles, no discount, new, desktop, not December)€56.15€54.81 to €57.49
Email (against direct)€0.41 higher€1.11 lower to €1.93 higher
Organic search€0.65 higher€0.64 lower to €1.94 higher
Paid search€0.12 lower€1.48 lower to €1.24 higher
Paid social€14.39 lower€13.06 to €15.72 lower
Referral€0.02 lower€2.00 lower to €1.95 higher
Ceramics (against candles)€12.15 higher€11.26 to €13.05 higher
Textiles€17.64 higher€16.65 to €18.63 higher
Discount code used€1.55 lower€0.48 to €2.61 lower
Returning customer€8.62 higher€7.79 to €9.44 higher
Mobile€4.69 lower€3.89 to €5.48 lower
December€15.26 higher€13.98 to €16.55 higher

Above the table, the summary also reports 47,710 observations and an R squared of 0.071.

The equation behind the table

What statsmodels estimated is this equation, one line per order (Foundations: the mean):

yi=β0+β1x1i+β2x2i+⋯+βkxki+εiy_i = \beta_0 + \beta_1 x_{1i} + \beta_2 x_{2i} + \dots + \beta_k x_{ki} + \varepsilon_i

where yiy_i is the value of order ii in euro, β0\beta_0 is the intercept (the expected value when every xx is 0, so a new desktop customer from direct, landing on candles, without a code, outside December), x1ix_{1i} to xkix_{ki} are the 0 or 1 columns for order ii, β1\beta_1 to βk\beta_k are the effects in euro that least squares chooses so that the squared gaps between actual and fitted values are as small as possible, and εi\varepsilon_i is everything the model does not know about order ii.

Example: one order, worked through

Take a returning customer who clicks an email in December, lands on ceramics, uses a discount code and orders on a laptop. Add up the effects that apply:

y^=56.15+0.41+12.15−1.55+8.62+15.26=91.04\hat{y} = 56.15 + 0.41 + 12.15 - 1.55 + 8.62 + 15.26 = 91.04

where y^\hat{y} is the model's expected order value in euro for that kind of order, 56.1556.15 the intercept, 0.410.41 email, 12.1512.15 ceramics, −1.55-1.55 the discount, 8.628.62 returning and 15.2615.26 December. Mobile is 0, so it adds nothing. statsmodels works with the unrounded coefficients and gets €91.05. The cent between them is rounding.

statsmodels does the same sum, and adds two kinds of uncertainty:

table = pd.concat([explain.params, explain.conf_int()], axis=1)
table.columns = ["effect", "low", "high"]
print(table.round(2))   # the table above

aine = pd.DataFrame({"channel": ["email"], "category": ["ceramics"], "discount": [1],
                      "returning": [1], "mobile": [0], "december": [1]})
print(explain.get_prediction(aine).summary_frame(alpha=0.05).round(2))
#     mean  mean_se  mean_ci_lower  mean_ci_upper  obs_ci_lower  obs_ci_upper
# 0  91.05     0.99          89.12          92.98          7.68        174.42

Read those two intervals side by side, because they are the bridge between the two cultures. The average order of this kind is €91.05, and statsmodels is quite sure of it: €89.12 to €92.98. A single order of this kind could be anything from about €8 to €174. The model knows the average well and the individual order hardly at all. Hold on to that: it is exactly what scikit learn will measure later from the other side.

Reading a regression table honestly

A regression table looks authoritative, which is why it is so easy to misread. I read every one with five questions.

Question 1: compared with what?

Every effect of a category is a comparison with the reference. "Paid social: €14.39 lower" means lower than direct, for orders that are otherwise alike. Change the reference to paid search and every channel number changes, while the model stays the same. So name the reference in every chart and sentence. That is why the formula spells out Treatment("direct") instead of trusting the alphabet.

Question 2: how big, and how sure?

Read the effect and its interval before the p value. The p value answers a narrow question: if the true effect were zero, how surprising would this estimate be? With 47,710 orders, almost any difference is "significant". The useful question is whether the effect is big enough to matter, and the interval answers it (Foundations: confidence intervals):

β^±1.96×SE(β^)\hat{\beta} \pm 1.96 \times \mathrm{SE}(\hat{\beta})

where β^\hat{\beta} is the estimated effect, SE(β^)\mathrm{SE}(\hat{\beta}) its standard error (how much the estimate would wobble from sample to sample) and 1.961.96 the multiplier for a 95% interval under a normal approximation.

Example: the paid social interval. The estimate is −14.39-14.39 with a standard error of 0.6790.679:

−14.39±1.96×0.679=−14.39±1.33-14.39 \pm 1.96 \times 0.679 = -14.39 \pm 1.33

which gives −15.72-15.72 to −13.06-13.06: clearly below zero, and clearly large. Compare email: €0.41, with an interval from €1.11 lower to €1.93 higher. That interval includes zero, so the honest sentence is "no clear difference between email and direct once the other factors are held equal", not "email is €0.41 better". For more on why significance alone misleads, see statistical significance and error margins in performance and growth marketing.

Question 3: are the standard errors right?

Ordinary least squares assumes the scatter around the line is the same size everywhere. Order values break that: big baskets vary far more than small ones. When the scatter is uneven (statisticians say heteroscedastic), the usual standard errors are too optimistic or too pessimistic, and so are the intervals and p values. The fix is robust standard errors. cov_type="HC3" uses the version MacKinnon and White recommended for its behaviour in finite samples9. The effects stay identical. Only the intervals change, and they become trustworthy.

Example: checking the assumptions

from statsmodels.stats.diagnostic import het_breuschpagan

plain = smf.ols(formula, data=orders).fit()          # the same model, classic errors
print(round(plain.resid.skew(), 2))                  # 1.87
lm_stat, lm_p, f_stat, f_p = het_breuschpagan(plain.resid, plain.model.exog)
print(f"{lm_p:.1e}")                                 # 1.9e-148

The residuals (actual minus fitted) are skewed to the right, 1.87, because a good few large orders sit far above the line. The Breusch Pagan test asks whether the scatter grows with the explanatory variables10. A p value of 1.9×10−1481.9 \times 10^{-148} is an emphatic yes. So HC3 was the right call, and Darragh states it in the report. A histogram of the residuals tells the same story at a glance. The chapter on showing distributions covers how to draw it honestly.

Question 4: is the scale the right one?

Order values are positive and skewed, and effects on them are often proportional: December does not add a fixed €15 to every order, it makes baskets bigger. A generalised linear model (GLM) handles this. With a Gamma distribution and a log link, the model works on the logarithm of the expected value, so each effect becomes a percentage11. In code:

gamma = smf.glm(formula, data=orders,
                family=sm.families.Gamma(link=sm.families.links.Log())).fit()
percent = (np.exp(gamma.params) - 1) * 100
print(percent.drop("Intercept").round(1))
# paid social  -21.6   ceramics  20.3   textiles  29.6   discount  -2.5
# returning     13.9   mobile    -6.7   december  24.3   (other channels within 1)

The percentage for each term is (eβ−1)×100(e^{\beta} - 1) \times 100, where β\beta is the GLM coefficient and ee the base of the natural logarithm (Foundations: percentages). Paid social orders are about 22% smaller, December orders about 24% larger. The story agrees with OLS. For a report to Áine, "December baskets are about a quarter larger" travels better than "€15.26 higher", and it stays true when prices rise. Note the spelling links.Log() with a capital L: the lower case aliases are deprecated in statsmodels 0.14.

Question 5: what else is in the model?

This is the question most reports skip, and it changes the answer more than any other.

Controls change the question

Every effect in a regression is "holding the other variables in the model fixed". So adding a variable does not just add a row to the table. It changes what every other row means.

Example: the same discount, two answers

Darragh adds the number of items in the basket to the model:

with_items = smf.ols(formula + " + items", data=orders).fit(cov_type="HC3")
compare = pd.DataFrame({"without items": explain.params,
                        "with items": with_items.params}).round(2)
print(compare.loc[['C(channel, Treatment("direct"))[T.paid social]', "discount",
                   "returning", "december", "items"]])
print(round(explain.rsquared, 3), round(with_items.rsquared, 3))   # 0.071 0.578
TermWithout itemsWith items
Paid social€14.39 lower€3.59 lower
Discount code€1.55 lower€11.18 lower
Returning customer€8.62 higher€1.04 higher
December€15.26 higher€1.78 higher
Each extra itemnot in the model€30.56 higher
R squared0.0710.578

Both columns are correct. They answer different questions.

  • Without items, the discount effect is the total effect: what happens to order value when a code is used, including the extra items people add to make the code worthwhile. Minus €1.55.
  • With items, it is the effect at a fixed basket size: the pure price cut. Minus €11.18, close to 15% of what a discounted basket would cost at full price, which is the price cut the simulation built in.

Basket size is a mediator, the route through which discounts, December and returning customers do most of their work. Holding it fixed switches that route off. For Áine's question ("should we keep discount codes?") the total effect is the right one: codes cost about €1.55 of order value per order, and the margin they give away is a separate calculation. For a question about pricing per item, the direct effect is the right one.

Paid social tells the same kind of story. Of its €14.39 gap, most runs through smaller baskets. At the same basket size, paid social orders are only about €3.60 lower. That points Áine towards bundles and basket building on paid social landing pages, not towards cutting the channel.

The R squared jumps from 0.071 to 0.578, and a beginner might conclude the second model is "better". It is not better at Áine's question. It explains more of the variation because item count is nearly the order value itself. The intercept tells the same tale: with items in the model it becomes minus €14.98, the value of an order with zero items, which means nothing. A high R squared is not the goal of an explanation model. The right variables for the question are.

My rule: before adding a variable, ask whether it happens before or after the thing whose effect you want. Something that happens before (season, device, landing page) is a fair control. Something that happens after and because of it (basket size after a discount) swallows the effect you are trying to measure.

scikit learn: a model you can test

scikit learn is a library for machine learning: models that learn from examples to make predictions. Every model in it, from a straight line to a forest of trees, shares one small interface. You create an estimator, call fit(X, y) on training data, and call predict(X) on new data. That uniformity is its great strength: swapping one model for another is one line.

Example: the same regression, the same numbers

First, proof that the two libraries agree when asked the same thing:

from sklearn.compose import ColumnTransformer
from sklearn.preprocessing import OneHotEncoder
from sklearn.pipeline import make_pipeline
from sklearn.linear_model import LinearRegression

categorical = ["channel", "category"]
flags = ["discount", "returning", "mobile", "december"]
encode = ColumnTransformer(
    [("cat", OneHotEncoder(drop=["direct", "candles"], handle_unknown="ignore"), categorical)],
    remainder="passthrough")
same = make_pipeline(encode, LinearRegression())
same.fit(orders[categorical + flags], orders["order_value"])
coefs = pd.Series(same[-1].coef_, index=same[0].get_feature_names_out())
print(coefs.round(2))
# cat__channel_paid social  -14.39   cat__category_ceramics  12.15
# remainder__discount        -1.55   remainder__december     15.26   (and so on)

Every coefficient matches the statsmodels table to the penny. What differs is everything around it. scikit learn printed no standard errors, no intervals, no p values. That is not an omission. Its documentation describes LinearRegression as ordinary least squares and leaves inference to other tools, because its culture judges a model by its predictions, not its coefficients12.

Three new pieces appeared in that code:

  • OneHotEncoder does what C() did in the formula: one 0 or 1 column per category. drop=["direct", "candles"] names the references, and handle_unknown="ignore" stops a new channel in next month's data from crashing the model.
  • ColumnTransformer applies the encoder to the text columns and passes the rest through untouched.
  • make_pipeline chains preparation and model into one object. That matters more than it looks, and the section on leakage shows why13.

Predicting honestly: split by time, not at random

A prediction model is only as good as its error on data it has not seen. So you hold some data back. With orders, the held back data must be later than the training data, because the model will always be used on the future. A random split lets the model learn from September to predict July, which it will never be able to do in real life.

Before splitting, Darragh builds the one feature that carries customer history, using only information from before each order. This is the group by and cumulative sum pattern from the group by chapter:

# Average value of the customer's EARLIER orders only (0 for a first order)
running_total = orders.groupby("customer_id")["order_value"].cumsum() - orders["order_value"]
orders["prior_avg_value"] = (running_total / orders["prior_orders"]).where(orders["prior_orders"] > 0, 0.0)

at_arrival = categorical + flags + ["prior_orders", "prior_avg_value"]

cutoff = pd.Timestamp("2025-07-01", tz="UTC")
train = orders[orders["order_time"] < cutoff]
test = orders[orders["order_time"] >= cutoff]
X_train, y_train = train[at_arrival], train["order_value"]
X_test, y_test = test[at_arrival], test["order_value"]
print(len(train), len(test))   # 36951 10759

Nine months train the model (October to June). The last three months (July to September) are the test, touched exactly once, at the end.

Cross validation: many small tests inside the training data

Choosing between models on the test set would quietly turn it into training data. So the choice happens inside the training months with cross validation: split the training data into folds, train on some, score on the next, repeat, and average14. For time ordered data, TimeSeriesSplit always trains on the past and scores on the period right after it.

The score here is the mean absolute error (MAE), the average size of a miss in euro (Foundations: spread):

MAE=1n∑i=1n∣yi−y^i∣\mathrm{MAE} = \frac{1}{n} \sum_{i=1}^{n} \lvert y_i - \hat{y}_i \rvert

where nn is the number of orders scored, yiy_i the actual value of order ii, y^i\hat{y}_i the predicted value and ∣⋅∣\lvert \cdot \rvert the absolute value, so misses above and below count the same. I prefer it to R squared for business readers because it is in euro: "the model is €31 off on a typical order" needs no translation.

Three models compete. The baseline always predicts the training average. It is the model to beat, and every prediction report should show it. The linear model is the regression from before. Boosting (HistGradientBoostingRegressor) builds hundreds of small decision trees, each correcting the last, and can find curves and interactions a straight line cannot15.

Example: three models, five folds

from sklearn.dummy import DummyRegressor
from sklearn.ensemble import HistGradientBoostingRegressor
from sklearn.model_selection import TimeSeriesSplit, cross_validate
from sklearn.base import clone

models = {
    "baseline": DummyRegressor(strategy="mean"),
    "linear": make_pipeline(clone(encode), LinearRegression()),
    "boosting": make_pipeline(clone(encode), HistGradientBoostingRegressor(
        max_iter=300, learning_rate=0.05, random_state=11)),
}
folds = TimeSeriesSplit(n_splits=5)
for name, model in models.items():
    scores = cross_validate(model, X_train, y_train, cv=folds,
                            scoring="neg_mean_absolute_error")
    mae = -scores["test_score"]
    print(f"{name:9} MAE {mae.mean():.2f} (spread {mae.std():.2f})")
# baseline  MAE 32.83 (spread 0.87)
# linear    MAE 31.48 (spread 1.37)
# boosting  MAE 31.77 (spread 1.61)

clone(encode) gives each pipeline its own fresh copy of the encoder, so fitting one model never changes another. scikit learn reports errors as negative numbers (neg_mean_absolute_error) because it always maximises a score, hence the minus sign to turn them back.

The linear model wins in cross validation, narrowly. Then, once, the test:

from sklearn.metrics import mean_absolute_error, r2_score

for name, model in models.items():
    model.fit(X_train, y_train)
    pred = model.predict(X_test)
    print(f"{name:9} MAE {mean_absolute_error(y_test, pred):.2f}  R2 {r2_score(y_test, pred):.3f}")
# baseline  MAE 32.29  R2 -0.000
# linear    MAE 30.91  R2 0.089
# boosting  MAE 30.84  R2 0.092

The honest answer to Áine's second question: on arrival, the best model misses a typical order by about €31, against €32.29 for simply guessing the average. That is an improvement of about 4%.

That is not a failed analysis. It is a finding. Most of what decides an order's value (which items, how many) happens after arrival, and no model can see it at that moment. A personalised homepage built on this prediction would be personalised on noise, and Darragh has saved Áine from building it. Fair play to him.

Boosting and the linear model are level, within a few pence on the test and the other way round in cross validation. When a flexible model cannot beat a straight line, I keep the straight line: it is faster, it can be explained in one table, and it fails in ways people can understand.

Example: what the predictions look like

Scatter of 40 test orders from July to September 2025: predicted order value from the boosting model on the horizontal axis, actual order value on the vertical axis, in euro. Predictions range only from about 44 to 93 euro, while actual values range from 18 to 290 euro. The points form a vertical band, not a diagonal line, which is what a test MAE of about 31 euro against 32.29 euro for the average looks like. Tap or click to enlarge

A predicted versus actual chart is the quickest honest picture of a prediction model. A good model puts the points along the diagonal. This one makes a tall column: the predictions huddle between about €44 and €93 while real orders run from €18 to €290. It is the same message as statsmodels' prediction interval of €8 to €174 for a single order, seen from the other culture. The chapter on showing relationships explains how to read and draw scatter plots like this, and the charts chapter of this series shows how to build one in matplotlib.

Overfitting: a perfect memory is a bad model

Overfitting means a model has learned the training data, noise included, instead of the pattern behind it. It looks excellent on the data it has seen and poor on anything new. A single decision tree with no limit on its depth is the classic way to watch it happen.

Example: the tree that memorised nine months

from sklearn.tree import DecisionTreeRegressor

for depth in [None, 5]:
    tree = make_pipeline(clone(encode), DecisionTreeRegressor(max_depth=depth, random_state=11))
    tree.fit(X_train, y_train)
    print(depth,
          round(mean_absolute_error(y_train, tree.predict(X_train)), 2),
          round(mean_absolute_error(y_test, tree.predict(X_test)), 2))
# None 14.45 41.32
# 5 30.79 31.16
TreeError on training monthsError on test months
No depth limit€14.45€41.32
At most 5 levels€30.79€31.16
For comparison: guess the average€32.29

The unlimited tree is off by only €14.45 on the orders it has seen and by €41.32 on new ones, far worse than guessing the average. It memorised individual customers' past values. The tree limited to five levels has nearly the same error on both, which is what a model that learned something general looks like. The gap between training error and test error is the overfitting alarm. If a report only gives you the training error, it has not told you anything yet.

statsmodels users overfit too, just more quietly: a regression with 40 variables for 300 rows will fit beautifully and generalise badly. The protection is the same, a held back test, or fewer variables chosen for a reason.

Data leakage: the timestamp test

Data leakage happens when a model is trained with information that will not be available at the moment it is used. The scikit learn documentation describes the result plainly: the performance estimates come out overly optimistic, and the model does worse on genuinely new data16. Kaufman and colleagues gave leakage a formal definition and set out ways to detect and avoid it17.

Marketing data leaks in particular ways, because exports are pulled today and describe the past with today's knowledge. The timestamp test catches nearly all of it. Here it is on Darragh's columns:

ColumnWhen it becomes knownUse for a prediction at arrival?
Channel, device, landing categoryWhen the visitor arrivesYes
Discount code in the linkWhen the visitor arrivesYes
Prior orders, average of prior ordersBefore the visit, computed from earlier orders onlyYes
Number of itemsAt checkoutNo
Customer's average order value from the customer exportOn the day of the export, includes later ordersNo
Refund statusDays or weeks after the orderNo

Example: the customer export that knows the future

Darragh is tempted by the customer export, which has a ready made average order value per customer. It was pulled on 30 September 2025, so it includes every order of the year, including the one being predicted and those after it.

from sklearn.model_selection import train_test_split

# The customer export, pulled on 30 September 2025
customers = orders.groupby("customer_id")["order_value"].agg(total_spent="sum", order_count="size")
customers["avg_order_value"] = customers["total_spent"] / customers["order_count"]
leaky = orders.merge(customers[["avg_order_value"]], left_on="customer_id",
                     right_index=True, how="left", validate="many_to_one")

cols = at_arrival + ["avg_order_value"]
Xa, Xb, ya, yb = train_test_split(leaky[cols], leaky["order_value"],
                                  test_size=0.25, random_state=11)
too_good = clone(models["boosting"]).fit(Xa, ya)
pred = too_good.predict(Xb)
print(f"MAE {mean_absolute_error(yb, pred):.2f}  R2 {r2_score(yb, pred):.3f}")
# MAE 16.73  R2 0.641

The error halves, from about €31 to €16.73, and R squared leaps from 0.09 to 0.64. It looks like a breakthrough. It is a leak. For the 9,305 customers who ordered once, the "average order value" is the order value itself, so the model is reading the answer. The validate="many_to_one" check from the joining chapter made sure the merge did not duplicate orders. It could not tell that the column comes from the future. Only the timestamp test can.

The random split made it worse: it let the model train on orders from after the ones it was tested on. Leaks and random splits travel together.

Example: the basket that has not been filled yet

The second leak is subtler, because the column is genuine and measured correctly. It is just measured too late:

cols = at_arrival + ["items"]
basket = clone(models["boosting"]).fit(train[cols], y_train)
pred = basket.predict(test[cols])
print(f"MAE {mean_absolute_error(y_test, pred):.2f}  R2 {r2_score(y_test, pred):.3f}")
# MAE 17.24  R2 0.664

This model is trained and tested properly by time, and it is still useless for Áine's purpose: at arrival the basket is empty. The same column that was a legitimate (if question changing) control in the explanation model is a leak in the prediction model. Whether a column leaks depends on the moment of prediction, not on the column.

Mean absolute error in euro on held back orders, lower is better. Guess the average 32.29, linear model 30.91, boosting 30.84. With the customer export's average order value, random split, 16.73. With the number of items, known only at checkout, 17.24. The two leaky models look about 48 and 47 percent better but cannot be used at the moment of arrival. Tap or click to enlarge

Example: the leak inside the preparation

The third kind of leak comes from preparation, not from columns. If you scale, fill in missing values or select features on the whole dataset before splitting, the test rows have already shaped the training. The scikit learn documentation's rule is to split first and fit every preparation step on the training data only16.

A pipeline does that for you. Inside cross_validate, the OneHotEncoder in each pipeline is fitted on the training folds alone, every time. Had Darragh encoded or scaled the whole table first and handed the result to cross validation, nothing would have warned him. That is the main reason I put every preparation step inside the pipeline, even the ones that seem harmless.

Typical leaks in marketing data, all caught by the timestamp test:

  • Customer exports with lifetime totals, segments or "VIP" flags computed today.
  • Attributed conversions from an ad platform, which arrive days later and are revised within the attribution window.
  • Refunds and returns, known weeks after the order.
  • Rolling averages computed with a centred window instead of a trailing one (see the time series chapter).
  • Targets hidden in features: "points earned" that is simply order value in disguise, or a "shipping band" chosen by basket value.

statsmodels or scikit learn: the comparison

statsmodelsscikit learn
Built forExplaining: effects, uncertainty, testsPredicting: accuracy on new data
Main outputA summary table with effects, standard errors, intervalsPredictions and an error score
How you specify a modelFormulas (y ~ a + C(b)) or arraysArrays and DataFrames, preparation in pipelines
CategoriesC() in the formula, reference chosenOneHotEncoder, reference via drop
Judging the modelIntervals, diagnostics, residuals, information criteriaTrain and test split, cross validation, metrics
Typical modelsOLS, GLM (logistic, Poisson, Gamma), time series, panel and mixed modelsLinear and logistic models, trees, boosting, forests, clustering, PCA
Guards againstWrong standard errors, misread effectsOverfitting, leakage through preparation
Weak spotNo built in train and test workflowNo standard errors or p values
Use it whenThe decision is about a leverThe decision is about a row

In practice you use both, often on the same project: statsmodels to understand what drives a number, scikit learn to check that a model generalises, and the overlap (the same OLS in both) as a cross check.

How the later chapters use both

A second series in this programme, on marketing analytics in Python, builds one model per chapter on these foundations, starting in the new year. In words, since none of it is published yet:

  • Explanation with statsmodels: price elasticity with regression, distributed lags for how long marketing keeps working, Poisson regression for counts, logistic regression, forecasting with seasonality and autocorrelation, and A/B tests with sample sizes.
  • Prediction with scikit learn: lift charts for logistic models, principal components and customer segmentation with k means.
  • Specialist libraries that follow the statsmodels culture: lifelines for survival analysis and lifetime value, and linearmodels for panel regression and two stage least squares.
  • Both together in media mix modelling, where the question is a lever (where the next euro goes) but the model must also predict well out of sample before anyone trusts its levers.

Each of those chapters starts with the same question this one asks: lever or row?

For the person who commissions this

You do not need to read code to hold a model to account. Ask these questions of any model someone brings you, including mine:

QuestionA good answer sounds like
Does this model explain or predict?"It explains: here is the effect of discounts and how sure the estimate is."
Compared with what?"Against direct traffic, landing on candles, without a code."
What is the interval?"Between €0.48 and €2.61 lower."
What else is in the model, and why?"Season and device, not basket size, because basket size is how discounts work."
What is the error on unseen, later data?"€30.91 on July to September, trained on October to June."
How much better than guessing the average?"About 4%."
When is each column known?"All at arrival. We removed the export's lifetime values."

If the answers are vague, the model is not ready for a decision. Building models that survive these questions, and the dashboards that keep them honest over time, is a core part of my Data Science work.

My view

My view: most marketing teams need explanation far more often than prediction, and they reach for prediction first because it sounds more advanced. The decisions on a marketing calendar are mostly levers: how much budget, which discount, which range to push in December. Those need an effect with an honest interval, from a model whose every row someone can read. statsmodels gives you that, and with the formula interface it is barely harder than a pivot table.

Prediction earns its place when there are many rows to act on and the cost of a wrong guess is small for each: scoring customers for an email, ordering stock per product per week. Then scikit learn's discipline (a time based split, cross validation, a baseline, a pipeline) is not optional. It is the difference between a model and a story.

And whichever library you use, the most valuable line in the analysis is often not code at all. It is the sentence "this is about as well as anyone can do at this moment", said early, before someone builds a system on a 4% improvement.

Conclusion

statsmodels and scikit learn fit the same equations and answer different questions. Ask first whether the decision is about a lever or about a row. For a lever, use statsmodels: name the reference, read the effect with its interval, use robust standard errors when the scatter is uneven, and remember that every variable you add changes the meaning of the others. For a row, use scikit learn: split by time, choose with cross validation, report the error in money against a baseline, keep preparation inside a pipeline, and put every column through the timestamp test. In the Ardmore Home example, that turned one vague question into two clear answers: discount codes cost about €1.55 per order once their extra items are counted, and an order's value cannot usefully be predicted at arrival. The closing chapter of this series turns analyses like this into a workflow someone else can rerun next month.

If you want to know what a model could honestly do with your shop's data, the free workshop is the place to start.

If you want to know what a model can honestly tell you about your shop, book the free workshop: we sort your questions into levers and rows together, no bother, and the first two weeks of work are on me.

Sources

  1. 1.

    Leo Breiman, Statistical Modeling: The Two Cultures (with comments and a rejoinder by the author), Statistical Science 16(3), 199 to 231, 2001, https://doi.org/10.1214/ss/1009213726

  2. 2.

    Galit Shmueli, To Explain or to Predict?, Statistical Science 25(3), 289 to 310, 2010, https://doi.org/10.1214/10-STS330

  3. 3.

    Python Software Foundation, Python 3.14.0, release date 7 October 2025, https://www.python.org/downloads/release/python-3140/

  4. 4.

    Python Package Index, release histories and files: pandas 2.3.3 (29 September 2025), https://pypi.org/project/pandas/2.3.3/. NumPy 2.3.4 (15 October 2025), https://pypi.org/project/numpy/2.3.4/. statsmodels 0.14.5 (7 July 2025), https://pypi.org/project/statsmodels/0.14.5/. scikit learn 1.7.2 (9 September 2025), https://pypi.org/project/scikit-learn/1.7.2/

  5. 5.

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

  6. 6.

    NumPy developers, Random sampling (numpy.random), NumPy 2.3 documentation, https://numpy.org/doc/2.3/reference/random/index.html

  7. 7.

    statsmodels developers, Fitting models using R style formulas, statsmodels 0.14 documentation, https://www.statsmodels.org/v0.14.4/example_formulas.html

  8. 8.

    Patsy project description, Python Package Index, https://pypi.org/project/patsy/

  9. 9.

    James G. MacKinnon and Halbert White, Some heteroskedasticity-consistent covariance matrix estimators with improved finite sample properties, Journal of Econometrics 29(3), 305 to 325, 1985, https://doi.org/10.1016/0304-4076%2885%2990158-7

  10. 10.

    Trevor S. Breusch and Adrian R. Pagan, A Simple Test for Heteroscedasticity and Random Coefficient Variation, Econometrica 47(5), 1287 to 1294, 1979, https://doi.org/10.2307/1911963. statsmodels developers, Regression diagnostics and specification tests, https://www.statsmodels.org/v0.14.4/diagnostic.html

  11. 11.

    statsmodels developers, Generalized Linear Models, statsmodels 0.14 documentation, https://www.statsmodels.org/v0.14.4/glm.html

  12. 12.

    scikit learn developers, Linear Models, scikit learn 1.7 user guide, https://scikit-learn.org/1.7/modules/linear_model.html

  13. 13.

    scikit learn developers, Pipelines and composite estimators, scikit learn 1.7 user guide, https://scikit-learn.org/1.7/modules/compose.html

  14. 14.

    scikit learn developers, Cross validation: evaluating estimator performance, scikit learn 1.7 user guide, https://scikit-learn.org/1.7/modules/cross_validation.html

  15. 15.

    scikit learn developers, HistGradientBoostingRegressor, scikit learn 1.7 API reference, https://scikit-learn.org/1.7/modules/generated/sklearn.ensemble.HistGradientBoostingRegressor.html

  16. 16.

    scikit learn developers, Common pitfalls and recommended practices: data leakage, scikit learn 1.7 user guide, https://scikit-learn.org/1.7/common_pitfalls.html

  17. 17.

    Shachar Kaufman, Saharon Rosset, Claudia Perlich and Ori Stitelman, Leakage in data mining: formulation, detection, and avoidance, ACM Transactions on Knowledge Discovery from Data 6(4), 1 to 21, 2012, https://doi.org/10.1145/2382577.2382579

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