Marketing Mix Modeling in Python with PyMC-Marketing

Fit a Bayesian marketing mix model with PyMC-Marketing, check it, and chart channel contributions, return on ad spend, response curves and a reallocated budget.

A marketing mix model (MMM) estimates how much each advertising channel adds to sales from time series data alone, with no user tracking. In Python, PyMC-Marketing's MMM class fits one with a GeometricAdstock for carryover and a LogisticSaturation for diminishing returns. This post uses PyMC-Marketing 1.5.0 (pip install pymc-marketing) and the pymc_marketing.mmm import path.

Quick Example

Three years of weekly sales and spend on TV, search and social. The data is simulated, so we know what each channel truly contributed.

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from pymc_marketing.mmm import MMM, GeometricAdstock, LogisticSaturation

rng = np.random.default_rng(191)
n = 156
dates = pd.date_range("2023-01-02", periods=n, freq="W-MON")
X = pd.DataFrame({
    "date": dates,
    "tv": (rng.gamma(2, 10, n) * (rng.random(n) < 0.6)).round(1),  # in bursts
    "search": rng.gamma(6, 3, n).round(1),
    "social": rng.gamma(2, 6, n).round(1),
    "promo": rng.binomial(1, 0.15, n),
})

def adstock(spend, alpha, length=8):
    w = alpha ** np.arange(length)
    return np.convolve(spend, w / w.sum())[:len(spend)]

def saturate(x, lam):
    return (1 - np.exp(-lam * x)) / (1 + np.exp(-lam * x))

# Hidden truth: (carryover, saturation speed, maximum weekly sales added)
truth = {"tv": (0.6, 2.5, 90), "search": (0.1, 4, 60), "social": (0.3, 3, 25)}
true_contribution = pd.DataFrame({
    c: top * saturate(adstock(X[c] / X[c].max(), a), lam)
    for c, (a, lam, top) in truth.items()})
base = 200 + 25 * np.sin(2 * np.pi * dates.dayofyear / 365.25) + 30 * X.promo
y = (base + true_contribution.sum(axis=1) + rng.normal(0, 8, n)).round(1)
y.name = "y"                                       # sales, $ thousands

channels = ["tv", "search", "social"]
mmm = MMM(
    date_column="date", channel_columns=channels, control_columns=["promo"],
    adstock=GeometricAdstock(l_max=8), saturation=LogisticSaturation(),
    yearly_seasonality=2,
)
mmm.build_model(X, y)
# Also store contributions and predictions in sales units
mmm.add_original_scale_contribution_variable(var=["channel_contribution", "y"])
idata = mmm.fit(X, y, chains=4, tune=1000, draws=1000, target_accept=0.9,
                random_seed=0, progressbar=False)

# Total sales credited to each channel, one value per posterior draw
contribution = idata["posterior"]["channel_contribution_original_scale"]
totals = contribution.sum("date").stack(sample=("chain", "draw"))
mean = totals.mean("sample").to_series()[channels]
low = totals.quantile(0.03, "sample").to_series()[channels]
high = totals.quantile(0.97, "sample").to_series()[channels]

fig, ax = plt.subplots(figsize=(8, 4.5))
x = np.arange(3)
ax.bar(x - 0.2, mean, 0.4, color="#1f7a8c", label="Model (94% interval)",
       yerr=[mean - low, high - mean], capsize=4)
ax.bar(x + 0.2, true_contribution.sum()[channels], 0.4, color="#e1a140",
       label="Truth")
ax.set_xticks(x, ["TV", "Search", "Social"])
ax.set_ylabel("Sales added over 3 years ($ thousands)")
ax.legend()
plt.show()

Estimated sales contribution of TV, search and social with 94 percent intervals next to the true values; TV and search are close and social is overestimated

TV and search come out within a few percent of the truth. Social is overestimated: about $1,808k against a true $1,275k. Its interval, $916k to $3,120k, contains the truth but is very wide, because social is the smallest effect and is easy to confuse with noise.

Did the sampler converge?

Check this before reading any result. You want no divergences and r_hat values of about 1.00.

import arviz as az

print("divergences:", int(idata["sample_stats"]["diverging"].sum()))
summary = az.summary(idata, var_names=["adstock_alpha", "saturation_lam",
                                       "gamma_control"])
print(summary[["mean", "sd", "ess_bulk", "r_hat"]])
divergences: 0
                          mean      sd ess_bulk r_hat
adstock_alpha[tv]         0.57   0.041     4459  1.00
adstock_alpha[search]    0.117   0.063     1937  1.00
adstock_alpha[social]    0.386    0.13     2662  1.00
saturation_lam[tv]        1.37    0.73     2321  1.00
saturation_lam[search]    3.51    0.99      851  1.00
saturation_lam[social]     4.5    2.18     1292  1.00
gamma_control[promo]    0.0817  0.0045     4327  1.00

The carryover estimates (adstock_alpha) are near the true 0.6, 0.1 and 0.3, with TV pinned down best. The saturation parameters are much less certain. gamma_control is on the scaled target: multiply by the largest weekly sales to get dollars.

Does the model fit the data?

pred = mmm.sample_posterior_predictive(X, random_seed=0, progressbar=False)
draws = pred["y_original_scale"].transpose("sample", "date").values
band_low, band_high = np.percentile(draws, [3, 97], axis=0)

fig, ax = plt.subplots(figsize=(9, 4))
ax.fill_between(dates, band_low, band_high, color="#1f7a8c", alpha=0.25,
                label="94% predictive interval")
ax.plot(dates, draws.mean(axis=0), color="#1f7a8c", label="Predicted")
ax.plot(dates, y, "k.", ms=4, label="Actual")
ax.set_ylabel("Weekly sales ($ thousands)")
ax.legend(ncols=3, loc="upper center")
ax.set_ylim(top=y.max() * 1.15)
plt.show()

inside = np.mean((y >= band_low) & (y <= band_high))
print(f"{inside:.0%} of weeks fall inside the interval")
97% of weeks fall inside the interval

Actual weekly sales as dots over the model's predictions and a shaded predictive interval

A good fit is necessary but proves little about the channel split. Many splits between base sales and media can fit the same totals.

How do I plot return on ad spend (ROAS)?

Divide each draw's contribution by the channel's spend.

spend = X[channels].sum()
roas = totals / spend.to_xarray().rename(index="channel")
true_roas = true_contribution.sum() / spend

fig, ax = plt.subplots(figsize=(8, 3.8))
parts = ax.violinplot([roas.sel(channel=c).values for c in channels],
                      orientation="horizontal", showextrema=False,
                      widths=0.8)
for body in parts["bodies"]:
    body.set(facecolor="#1f7a8c", alpha=0.6)
ax.scatter(true_roas[channels], [1, 2, 3], marker="D", color="#c0392b",
           zorder=3, label="True ROAS")
ax.set_yticks([1, 2, 3], ["TV", "Search", "Social"])
ax.invert_yaxis()
ax.set_xlabel("Sales per dollar of spend")
ax.legend()
plt.show()

Distributions of return on ad spend by channel with the true values marked; search has a wide distribution and social's peak sits above its true value

The mean ROAS is 2.09 for TV (true 2.11), 2.32 for search (true 2.40) and 0.93 for social (true 0.65). The model gives a 65% probability that social returns less than a dollar per dollar. That's a more useful statement than a single number.

Response curves and diminishing returns

The saturation curve shows what a steady weekly spend would add. PyMC-Marketing fits it on spend and sales divided by their maximums, so scale back:

post = idata["posterior"].to_dataset().stack(sample=("chain", "draw"))
x_scale = X[channels].max()
y_scale = y.max()

def response(channel, weekly_spend):
    """Weekly sales added by a steady spend, for every posterior draw."""
    p = post.sel(channel=channel)
    lam, beta = p["saturation_lam"].values, p["saturation_beta"].values
    scaled = np.atleast_1d(weekly_spend)[:, None] / x_scale[channel]
    return beta * saturate(scaled, lam) * y_scale

fig, axes = plt.subplots(1, 3, figsize=(10, 3.4), sharey=True)
for ax, channel in zip(axes, channels):
    grid = np.linspace(0, X[channel].max(), 60)
    curves = response(channel, grid)
    ax.fill_between(grid, *np.percentile(curves, [3, 97], axis=1),
                    color="#1f7a8c", alpha=0.25)
    ax.plot(grid, curves.mean(axis=1), color="#1f7a8c", lw=2)
    a, lam, top = truth[channel]
    ax.plot(grid, top * saturate(grid / x_scale[channel], lam), "--",
            color="#c0392b")
    ax.axvline(X[channel].mean(), color="gray", ls=":")
    ax.set_title("TV" if channel == "tv" else channel.title())
    ax.set_xlabel("Weekly spend ($k)")
axes[0].set_ylabel("Weekly sales added ($k)")
plt.show()

Response curves for TV, search and social with uncertainty bands, true curves dashed and average spend marked with a dotted line

The dotted line marks average weekly spend. Bands widen where there is little data, so don't trust the curve far beyond what you have spent before.

Reallocate the budget

Keep total weekly spend fixed and move it to maximize predicted sales, limiting each channel to within 50% of its current average.

from scipy.optimize import minimize

current = X[channels].mean().to_numpy()
predicted = lambda s: sum(response(c, v).mean() for c, v in zip(channels, s))
actual = lambda s: sum(
    truth[c][2] * saturate(v / x_scale[c], truth[c][1])
    for c, v in zip(channels, s))

best = minimize(
    lambda s: -predicted(s), current, method="SLSQP",
    bounds=[(0.5 * v, 1.5 * v) for v in current],
    constraints={"type": "eq", "fun": lambda s: s.sum() - current.sum()},
).x

print(pd.DataFrame({"current": current, "suggested": best},
                   index=channels).round(1))
print(f"predicted gain: {predicted(best) - predicted(current):.1f} per week")
print(f"true gain:      {actual(best) - actual(current):.1f} per week")

fig, ax = plt.subplots(figsize=(8, 4))
ax.bar(x - 0.2, current, 0.4, color="#b8c2cc", label="Current")
ax.bar(x + 0.2, best, 0.4, color="#1f7a8c", label="Suggested")
ax.set_xticks(x, ["TV", "Search", "Social"])
ax.set_ylabel("Weekly spend ($ thousands)")
ax.legend()
plt.show()
        current  suggested
tv          9.7       14.5
search     17.9       19.3
social     12.5        6.3
predicted gain: 6.5 per week
true gain:      7.6 per week

Current and suggested weekly spend by channel for the same total budget

The model moves money from social to TV and, less, to search. TV and social both hit a limit of the 50% rule. Scored against the true curves, the new plan adds about $7,600 a week. PyMC-Marketing also has a budget_optimizer for this; the version here is written out so you can see the steps. It uses steady spend and the posterior mean, which ignores flighting and risk.

Can you trust an MMM?

An MMM is observational. It is open to the same problems as any regression:

  • Spend that rises when demand is expected to rise (search especially) looks more effective than it is.
  • Channels that always move together can't be separated.
  • Missing drivers such as price changes, stock-outs or competitors get credited to media.

Calibrate it with experiments. A geo-lift test measures one channel's effect directly, and mmm.add_lift_test_measurements() can feed that result into the model.

Practical tips

  • Use at least two years of weekly data and make sure spend varies. Flat budgets give the model nothing to learn from.
  • Put known drivers in control_columns.
  • Set l_max long enough to cover the carryover you believe in.
  • Look at priors with mmm.sample_prior_predictive() before fitting real data.
  • In a .py script, put the fit under if __name__ == "__main__":, since chains can run in separate processes.
  • Meridian, from Google, is another open-source Python MMM library. I didn't test it for this post.

Similar Topics