Lift Test Calibration#

Introduction#

You may have heard of the phrase “All models are wrong but some are useful.” This is true in many areas, and it’s likely that after the first attempt, you haven’t yet created a model that can accurately determine your true attribution. Even if you have, how can you be sure? We create models to understand the attribution of our marketing channels, but it appears that even then, we can’t always rely on what the models tell us.

In order to ensure that our models are decomposing correctly, we can use various testing methods to gather real-world data and compare it with our models. This will help us to identify any discrepancies and improve the decomposition accuracy of our models.

Today, we will explore a new way to integrate experiments into pymc-marketing. Lift-test evidence constrains a channel’s response curve, which can inform the estimated marginal return from additional spend (mROAS) and the resulting budget decision. The experiment measures an average return over its tested spend change; the MMM uses the response curve to infer the local return at a chosen operating spend.

The lift estimates in this notebook are simulated from known response curves; we do not run an experiment or a CausalPy analysis here. In practice, estimate lift and its uncertainty from an actual intervention, for example with CausalPy’s interrupted time series lift-test workflow.

When are lift tests useful?#

In some situations, all of the relevant experiment spend data is captured within historical data that you will include in your training set. In these cases, a valid approach could be to simply train your MMM on all available data (including experiment and non-experiment periods) in order to optimally inform you about model parameters and ultimately get better insights. However there are a number of situations when this approach will not be appropriate.

  1. Imagine your online advertising platform gave you additional credit. You decide to spend this credit by increasing activity on a digital ad channel and you want to use this as a way to evaluate the uplift. In this situation, you will have increased the level of advertising taking place, but this ‘increased spend’ is not charged to your invoice. So unless your data pipeline is really on point, your spend data will not accurately reflect the level of effective spend.

  2. You want to run a test on TV. In that case, you probably have to pay months before the test takes place or the commercial is aired. So, your spending may be in February and the action in March, but during the period of the experiment itself, there is no spending. Here, the spend may well be contained in your training data, but the time lag between the spend and the advertising takes place is very high. So the adstock function which accommodates short term lag effects may not adequately capture longer term lags such as this.

  3. You are experimenting with discounts or promotions. These might be quantifiable, but not show up in your traditional media spend channels and so your experimentation may not be captured by your MMM.

These are examples where lift tests can provide evidence that historical spend data misses. Calibrating the MMM with valid lift estimates can change its channel responses, but improvement in every parameter or mROAS estimate is not guaranteed.

Requirements#

Today, we won’t be discussing how to conduct lift tests, but instead, we will focus on their utilization. If you wish to acquire knowledge on how to generate results that are compatible with your MMM models, you can check out CausalPy for conducting experiments, such as using Interrupted Time Series for lift tests with no control groups.

Goal#

After reading this notebook, you will have gained the necessary expertise to incorporate the results (detected uplift from your experiments) into our regressive model.

This notebook will display using the add_lift_test_measurements method of MMM and its workflow:

  1. Build model: mmm.build_model(X, y)

  2. Add lift measurements: mmm.add_lift_test_measurements(df_lift_test)

  3. Sample posterior: mmm.fit(X, y)

This is a case study of two correlated channels to see how lift tests help distinguish the channel effects.

import warnings
from functools import partial

import arviz as az
import arviz_plots as azp
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import pymc as pm
import seaborn as sns
import xarray as xr
from IPython.display import display
from xarray import DataArray

from pymc_marketing.mmm import (
    MMM,
    FixedScaling,
    GeometricAdstock,
    LogisticSaturation,
    Scaling,
)
from pymc_marketing.mmm.transformers import logistic_saturation

FIG_WIDTH, FIG_HEIGHT = 12, 5
COLOR_MMM_UNCALIBRATED = "C0"
COLOR_MMM_CALIBRATED = "C2"
COLOR_MMM_MORE_TESTS = "C3"
COLOR_SIMULATED_TRUTH = "black"


warnings.filterwarnings("ignore")

az.style.use("arviz-darkgrid")
plt.rcParams["figure.figsize"] = [12, 7]
plt.rcParams["figure.dpi"] = 100
plt.rcParams["figure.facecolor"] = "white"

%config InlineBackend.figure_format = "retina"
seed = sum(map(ord, "Lift tests help distinguish channel effects"))
rng = np.random.default_rng(seed)

Generate Correlated Spends and Model Target#

First we’ll generate synthetic data for two channels with completely correlated spends.

n_dates = 52
dates = pd.date_range(start="2024-01-01", periods=n_dates, freq="W-MON")
spend_rv = pm.Uniform.dist(lower=0.1, upper=1, size=n_dates)
spend = pm.draw(spend_rv, random_seed=rng)
spend1 = spend / spend.max()
spend2 = spend - 0.05
spend2 /= spend2.max()
df = pd.DataFrame(
    {
        "date": dates,
        "channel 1": spend1,
        "channel 2": spend2,
    }
)

ax = df.set_index("date").plot(ylabel="Spend ($ millions/week)");

Note

For a compact simulation, spend and sales are expressed in $ millions per week. Lift rows and reported ROAS use those same business units.

Important

Keep scaling constants fixed across time and model refreshes. With data-derived max scaling, a new high spend or sales value changes the internal coordinate system. Numerical saturation parameters and the business-unit meaning of their priors then shift even if the underlying response has not. This example uses FixedScaling at one $ million per week for both spend and sales. For larger raw units, choose suitable positive constants once and reuse them for later history and lift tests.

We can double check that the to channels are perfectly correlated.

df.filter(regex="channel").corr()
channel 1 channel 2
channel 1 1.0 1.0
channel 2 1.0 1.0

We use the MMM class to specify our model just as usual.

# These inputs already use $ million units. Identity scaling fixes the
# coordinate system for future refreshes and additional lift studies.
unit_scaling = Scaling(
    channel=FixedScaling(
        dims=(), value={channel: 1.0 for channel in ["channel 1", "channel 2"]}
    ),
    target=FixedScaling(dims=(), value=1.0),
)
mmm = MMM(
    scaling=unit_scaling,
    date_column="date",
    target_column="y",
    channel_columns=["channel 1", "channel 2"],
    adstock=GeometricAdstock(l_max=6).set_dims_for_all_priors("channel"),
    saturation=LogisticSaturation().set_dims_for_all_priors("channel"),
)

We use pm.do to set the parameters of a model and draw synthetic sales. Because the model has fixed unit scaling, the planted saturation parameters are already in $ million business units. The same parameters define the dashed truth curves and the mROAS reference values below.

true_lam_c1 = 10
true_beta_c1 = 0.55

true_lam_c2 = 1.5
true_beta_c2 = 1.0

true_params = {
    "adstock_alpha": np.array([0.5, 0.5]),
    "saturation_lam": np.array([true_lam_c1, true_lam_c2]),
    "saturation_beta": np.array([true_beta_c1, true_beta_c2]),
    "intercept_contribution": 0.5,
    "y_sigma": 0.25,
}
df["y"] = np.ones(n_dates)

Hide code cell content

mmm.build_model(X=df.drop(columns=["y"]), y=df["y"])
fixed_model = pm.do(mmm.model, true_params)
df["y"] = pm.draw(fixed_model["y"], random_seed=rng)
del mmm.model
ax = df.set_index("date").plot(ylabel="", title="Channel spends and target variable")
ax.legend(bbox_to_anchor=(1.0, 1.05), title="column");
X = df.drop(columns=["y"])
y = df["y"]
mmm.build_model(X=X, y=y)
mmm.add_original_scale_contribution_variable(["channel_contribution"])
<pymc_marketing.mmm.mmm.MMM at 0x129b74260>

Indistinguishable Parameter Estimates#

In order to show the trouble that completely correlated channels provides, let’s fit the model

# With these perfectly correlated channels, 0.99 gave two divergences even
# with 2,000 tuning steps; 0.995 was the lowest tested target with none.
fit_kwargs = {
    "nuts_sampler": "numpyro",
    "target_accept": 0.995,
    "tune": 1_000,
    "random_seed": rng,
}

idata_without = mmm.fit(X, y, **fit_kwargs)
NUTS[numpyro]: [adstock_alpha, saturation_lam, saturation_beta, intercept_contribution, y_sigma]

Because the two historical spend series are highly correlated, the observational posterior cannot cleanly separate the channel responses. The forest plots below compare posterior parameters with planted truth after both are expressed in original $ million units.

Hide code cell content

def plot_true_value(
    value,
    channel: str,
    ax: plt.Axes,
    pc,
    var_name: str,
    label: str | None = None,
    pad: float = 0.1,
) -> plt.Axes:
    # The forest plot places each channel's rows at specific y positions. We
    # read those positions from the PlotCollection so the dashed true-value
    # line spans exactly that channel's rows, regardless of how many models
    # are being compared.
    y = pc.aes["y"][var_name].sel(channel=channel)
    ax.vlines(
        value,
        float(y.min()) - pad,
        float(y.max()) + pad,
        color="black",
        linestyle="dashed",
        linewidth=2,
        label=label,
    )
    return ax


def original_unit_parameter_idata(idata):
    """Copy posterior λ and β into original $ million units for forest plots."""
    scales = mmm.get_scales_as_xarray()
    result = idata.copy()
    result.posterior["saturation_lam"] = (
        idata.posterior["saturation_lam"] / scales["channel_scale"]
    )
    result.posterior["saturation_beta"] = (
        idata.posterior["saturation_beta"] * scales["target_scale"]
    )
    return result
pc = azp.plot_forest(
    original_unit_parameter_idata(idata_without),
    var_names=["saturation_lam"],
    combined=True,
    figure_kwargs={"figsize": (10, 6)},
)
ax = pc.viz["plot"].sel(column="forest").item()
plot_true_value(
    true_lam_c1, "channel 1", ax, pc, "saturation_lam", label=f"true λ₁ = {true_lam_c1}"
)
plot_true_value(
    true_lam_c2, "channel 2", ax, pc, "saturation_lam", label=f"true λ₂ = {true_lam_c2}"
)
ax.legend(fontsize=12, loc="lower right");
pc = azp.plot_forest(
    original_unit_parameter_idata(idata_without),
    var_names=["saturation_beta"],
    combined=True,
    figure_kwargs={"figsize": (10, 6)},
)
ax = pc.viz["plot"].sel(column="forest").item()
plot_true_value(
    true_beta_c1,
    "channel 1",
    ax,
    pc,
    "saturation_beta",
    label=f"true β₁ = {true_beta_c1}",
)
plot_true_value(
    true_beta_c2,
    "channel 2",
    ax,
    pc,
    "saturation_beta",
    label=f"true β₂ = {true_beta_c2}",
)
ax.legend(fontsize=12, loc="upper right");

We can also witness that while the actual saturation curves are different (because we specified the true parameters for each channel), the MMM is unable to distinguish between the two channels.

We can show this below by plotting the actual saturation curves (lines) and the direct response curves (points).

Direct response curves

Plots the direct contribution curves for each marketing channel. The term “direct” refers to the fact we plot costs vs immediate returns and we do not take into account the lagged effects of the channels e.g. adstock transformations. And so these curves will actually consist of a series of points, each representing the direct contribution of a spend level.

Hide code cell source

def saturation_function(x, lam, beta):
    return (beta * logistic_saturation(x, lam)).eval()


step_size = 0.05
xx = DataArray(np.arange(0, spend.max() * 1.1, step_size), dims=("step",))

c1_curve_fn = partial(saturation_function, lam=true_lam_c1, beta=true_beta_c1)
c2_curve_fn = partial(saturation_function, lam=true_lam_c2, beta=true_beta_c2)

c1_curve = c1_curve_fn(xx)
c2_curve = c2_curve_fn(xx)
curve = mmm.saturation.sample_curve(
    mmm.fit_result[["saturation_beta", "saturation_lam"]], max_value=1.1
)
fig, axes = mmm.plot.saturation_curves(
    curve,
    original_scale=True,
    n_samples=10,
    hdi_probs=0.85,
    random_seed=rng,
    subplot_kwargs={"figsize": (12, 8), "ncols": 2},
    rc_params={
        "xtick.labelsize": 10,
        "ytick.labelsize": 10,
        "axes.labelsize": 10,
        "axes.titlesize": 10,
    },
)


def plot_actual_curves(
    axes_array: np.ndarray, linestyle: str | None = None
) -> np.ndarray:
    axes_array[0].plot(xx, c1_curve, label="channel 1", color="C0", linestyle=linestyle)
    axes_array[1].plot(xx, c2_curve, label="channel 2", color="C1", linestyle=linestyle)
    return axes_array


def plot_reference(ax: plt.Axes) -> plt.Axes:
    ax.plot(xx, xx, label="y=x", color="black", linestyle="--")
    return ax


axes = np.ravel(axes)
plot_actual_curves(axes, linestyle="dashed")
fig.suptitle(
    "Direct response curves (points) and actual saturation curves (dashed lines)"
);
Sampling: []

../../_images/3c93ee9560efe493719e98784e01dd80d4f050cab38c5395efb7a04f1c3d46b1.png

We can see that the true but latent saturation curves (dashed lines) for each channel are different, but that the the MMM is unable to distinguish that the saturation curves for each channel (points) are different. And this is because the spends are perfectly correlated.

Let’s see if we can improve upon this by adding lift test measurements.

Note

In order to avoid confusion with the plot above, the actual saturation curves are represented by the dashed lines, while the direct contribution curves are represented by the points. If lift tests can help us in this situation of high spend correlation, then we should be able to detect this by: a) achieving better parameter estimates, and b) correspondingly, getting better estimates of the saturation curves.

We can also visualize the channel contributions over time. The wide HDI’s in the plot below shows that we have considerable uncertainty in the channel contributions. We can also see that the posterior means of the channel contributions are quite far off the mark of the actual channel contributions. Again, these true channel contributions are only known to us in this synthetic data example and would not be available to us in a real world scenario.

Hide code cell source

from pymc_marketing.mmm.transformers import geometric_adstock


def calculate_true_channel_contribitions(df, true_params):
    # apply geometric adstock transformation
    df["x1_adstock"] = geometric_adstock(
        x=df["channel 1"].to_xarray(),
        alpha=true_params["adstock_alpha"][0],
        l_max=6,
        normalize=True,
        dim="index",
    ).eval()
    df["x2_adstock"] = geometric_adstock(
        x=df["channel 2"].to_xarray(),
        alpha=true_params["adstock_alpha"][1],
        l_max=6,
        normalize=True,
        dim="index",
    ).eval()
    # apply saturation transformation
    df["x1_adstock_saturated"] = logistic_saturation(
        x=df["x1_adstock"].to_xarray(), lam=true_params["saturation_lam"][0]
    ).eval()
    df["x2_adstock_saturated"] = logistic_saturation(
        x=df["x2_adstock"].to_xarray(), lam=true_params["saturation_lam"][1]
    ).eval()
    return df


df = calculate_true_channel_contribitions(df, true_params)


def plot_channel_contributions(mmm, df):
    channels_contribution_original_scale = mmm.idata.posterior[
        "channel_contribution_original_scale"
    ]
    channels_contribution_original_scale_hdi = az.hdi(
        data=channels_contribution_original_scale
    )
    get_mean_contributions_over_time_xr = channels_contribution_original_scale.mean(
        dim=["chain", "draw"]
    )
    _, ax = plt.subplots(
        nrows=2,
        figsize=(15, 8),
        ncols=1,
        sharex=True,
        sharey=False,
        layout="constrained",
    )
    for i, x in enumerate(["channel 1", "channel 2"]):
        # Estimate true contribution in the original scale from the data generating process
        sns.lineplot(
            x=df["date"],
            y=true_params["saturation_beta"][i] * df[f"x{i + 1}_adstock_saturated"],
            color="black",
            label=f"{x} true contribution",
            ax=ax[i],
        )
        # HDI estimated contribution in the original scale
        ax[i].fill_between(
            x=df["date"],
            y1=channels_contribution_original_scale_hdi.sel(channel=x).sel(
                ci_bound="lower"
            ),
            y2=channels_contribution_original_scale_hdi.sel(channel=x).sel(
                ci_bound="upper"
            ),
            color=f"C{i}",
            label=rf"{x} $94\%$ HDI contribution",
            alpha=0.4,
        )
        # Mean estimated contribution in the original scale
        sns.lineplot(
            x=df["date"],
            y=get_mean_contributions_over_time_xr.sel(channel=x).to_numpy(),
            color=f"C{i}",
            label=f"{x} posterior mean contribution",
            alpha=0.8,
            ax=ax[i],
        )
        ax[i].legend(loc="center left", bbox_to_anchor=(1, 0.5))
        ax[i].set(title=x, ylim=(0, 1), ylabel="Contribution ($ millions/week)")
plot_channel_contributions(mmm, df)

About Lift Tests#

In a lift study, one changes a channel’s spend and estimates the resulting causal change in sales. Each row supplied to add_lift_test_measurements contains channel, baseline effective spend x, effective spend change delta_x, estimated weekly lift delta_y, and its standard error sigma. Spend and sales are in $ millions per week; their ratio is $ of incremental sales per $ of spend.

The historical sales series above contains no experiment. Below we simulate the results of separate, independent lift studies at several effective-spend levels. Their estimated lifts include measurement error around the known response curve, and their sigma values describe that error. A production analysis would estimate these rows from a randomized test or a credible counterfactual analysis. The static likelihood constrains a saturation contrast; it does not model a campaign’s adstock time path. A long-running test could use a near-steady-state window to obtain the effective-spend contrast used here.

lift_rng = np.random.default_rng(29)  # Independent of the historical sales simulation


def create_lift_test_from_actual_curve(
    channel: str, x: float, delta_x: float, sigma: float
) -> dict[str, float]:
    """Simulate an independent lift estimate at an effective-spend contrast."""
    curve_fn = c1_curve_fn if channel == "channel 1" else c2_curve_fn
    true_delta_y = float(curve_fn(x + delta_x) - curve_fn(x))
    measured_delta_y = true_delta_y + lift_rng.normal(0, sigma)
    return {
        "channel": channel,
        "x": x,
        "delta_x": delta_x,
        "delta_y": measured_delta_y,
        "sigma": sigma,
    }


def true_lift_at_row(row):
    curve_fn = c1_curve_fn if row.channel == "channel 1" else c2_curve_fn
    return float(curve_fn(row.x + row.delta_x) - curve_fn(row.x))
df_lift_test = pd.DataFrame(
    [
        # Channel x1
        create_lift_test_from_actual_curve("channel 1", 0.05, 0.05, 0.05),
        create_lift_test_from_actual_curve("channel 1", 0.15, 0.05, 0.05),
        create_lift_test_from_actual_curve("channel 1", 0.3, -0.05, 0.05),
        # Channel x2
        create_lift_test_from_actual_curve("channel 2", 0.5, 0.05, 0.10),
    ]
)

display(
    df_lift_test.assign(
        simulated_truth=[true_lift_at_row(row) for row in df_lift_test.itertuples()]
    ).round(4)
)
channel x delta_x delta_y sigma simulated_truth
0 channel 1 0.05 0.05 0.0999 0.05 0.1195
1 channel 1 0.15 0.05 0.0720 0.05 0.0695
2 channel 1 0.30 -0.05 -0.0395 0.05 -0.0313
3 channel 2 0.50 0.05 0.0154 0.10 0.0322

Each triangle uses the known simulated change in contribution: its vertical side ends on the known curve at the programmed final effective spend. The black cross marks that endpoint. The red circle shows the separate noisy lift estimate, anchored to the same baseline, with a vertical error bar of ±1 reported standard error (sigma). The circle need not lie on the curve.

Hide code cell source

def plot_triangle(
    x,
    delta_x,
    true_delta_y,
    color: str,
    ax: plt.Axes,
    offset: float = 0,
    label: str | None = None,
) -> plt.Axes:
    x_after = x + delta_x

    y = offset
    y_after = y + true_delta_y

    ax.plot([x, x_after], [y, y], color=color, label=label)
    ax.plot([x_after, x_after], [y, y_after], color=color)
    ax.plot([x, x_after], [y, y_after], color=color, linestyle="dashed")

    return ax


def plot_channel_triangles(
    df: pd.DataFrame, color: str, ax: plt.Axes, label: str
) -> plt.Axes:
    kwargs = {"label": label}
    for _, row in df.iterrows():
        plot_triangle(
            row["x"],
            row["delta_x"],
            true_lift_at_row(row),
            ax=ax,
            color=color,
            **kwargs,
        )
        ax.errorbar(
            row["x"] + row["delta_x"],
            row["delta_y"],
            yerr=row["sigma"],
            fmt="o",
            color="red",
            capsize=3,
            label="Estimated lift ± 1 SE" if "label" in kwargs else None,
            zorder=6,
        )
        if "label" in kwargs:
            kwargs.pop("label")
    return ax


def plot_lift_test_triangles(df: pd.DataFrame, ax: plt.Axes) -> plt.Axes:
    idx = df["channel"] == "channel 1"
    plot_channel_triangles(df.loc[idx], color="C0", ax=ax, label="channel 1")
    plot_channel_triangles(df.loc[~idx], color="C1", ax=ax, label="channel 2")
    return ax


_, ax = plt.subplots(1, 2, sharex=True, figsize=(12, 7))

# LEFT PLOT - Channel 1 curve with its triangles
ax[0].plot(xx, c1_curve, label="channel 1 curve", color="C0", linestyle="dashed")

# Add channel 1 triangles
ch1_data = df_lift_test[df_lift_test["channel"] == "channel 1"]
for i, (_, row) in enumerate(ch1_data.iterrows()):
    x, x_after = row["x"], row["x"] + row["delta_x"]
    y_base = float(c1_curve_fn(x))
    y_true = float(c1_curve_fn(x_after))
    y_measured = y_base + row["delta_y"]
    plot_triangle(
        x, row["delta_x"], y_true - y_base, ax=ax[0], color="C0", offset=y_base
    )
    ax[0].scatter(
        x_after,
        y_true,
        color="black",
        marker="x",
        s=65,
        label="Known curve endpoint" if i == 0 else None,
        zorder=5,
    )
    ax[0].errorbar(
        x_after,
        y_measured,
        yerr=row["sigma"],
        fmt="o",
        color="red",
        capsize=3,
        label="Estimated lift ± 1 SE" if i == 0 else None,
        zorder=6,
    )

ax[0].set(
    ylabel="Contribution ($ millions/week)",
    title="Channel 1: Curve and lift tests",
)
ax[0].legend()

# RIGHT PLOT - Channel 2 curve with its triangles
ax[1].plot(xx, c2_curve, label="channel 2 curve", color="C1", linestyle="dashed")

# Add channel 2 triangles
ch2_data = df_lift_test[df_lift_test["channel"] == "channel 2"]
for i, (_, row) in enumerate(ch2_data.iterrows()):
    x, x_after = row["x"], row["x"] + row["delta_x"]
    y_base = float(c2_curve_fn(x))
    y_true = float(c2_curve_fn(x_after))
    y_measured = y_base + row["delta_y"]
    plot_triangle(
        x, row["delta_x"], y_true - y_base, ax=ax[1], color="C1", offset=y_base
    )
    ax[1].scatter(
        x_after,
        y_true,
        color="black",
        marker="x",
        s=65,
        label="Known curve endpoint" if i == 0 else None,
        zorder=5,
    )
    ax[1].errorbar(
        x_after,
        y_measured,
        yerr=row["sigma"],
        fmt="o",
        color="red",
        capsize=3,
        label="Estimated lift ± 1 SE" if i == 0 else None,
        zorder=6,
    )

ax[1].set(
    xlabel="Effective spend ($ millions/week)",
    ylabel="Contribution ($ millions/week)",
    title="Channel 2: Curve and lift tests",
)
ax[1].legend()

plt.tight_layout();
fig, ax = plt.subplots(1, 1, figsize=(12, 5))
plot_lift_test_triangles(df_lift_test, ax)
ax.set_title("Known response and noisy lift estimates")
ax.set_ylabel("Weekly lift ($ millions/week)")
ax.set_xlabel("Effective spend ($ millions/week)")
ax.legend()
plt.tight_layout();

The upper panels put known curve geometry and noisy measurements on the same axes. The lower panel shows their changes relative to zero: triangle sides use the known simulated change, while red circles and error bars show what the lift studies estimated. The third Channel 1 row is a spend reduction, so its known and estimated changes are negative.

Add Lift Tests to Model#

Having created a MMM model instance, mmm and built it using the build_model method or fit with fit method, we can add lift test results to the model using the add_lift_test_measurements method.

First, let’s take a look at the model graph before adding the lift test measurements.

mmm.graphviz()
../../_images/cbdde7eef72d7bf1de0250b5bc3bc8fcd8f29477814f10a9b57977d6c369e453.svg

And now we’ll add the lift test measurements to the model and see how our model graph has changed.

mmm.add_lift_test_measurements(df_lift_test)
mmm.graphviz()
../../_images/7bf6a547f19cafe5bc18c0a5e55ce479aa4c982f0bf25227bcaa432e89de02ec.svg

The model graph now includes an observation for each lift estimate. By default, the likelihood is Normal: it compares the signed estimated lift with the signed lift implied by the saturation curve.

For each row, the added likelihood is

\[\Delta_y \sim \mathrm{Normal}(\tilde{\text{lift}}, \sigma).\]

Here \(\tilde{\text{lift}}\) is the model-implied change in contribution between \(x\) and \(x + \Delta x\). An estimate can be negative because the true effect is negative or because the study is noisy; its sign is retained.

How Lift Tests Are Implemented in PyMC

While the add_lift_test_measurements method handles all of this automatically in pymc-marketing, understanding the implementation mechanics is valuable. This section provides a step-by-step guide to how lift tests are integrated into the model.

Choosing a Measurement Likelihood

The default is a signed Normal likelihood because lift studies commonly report an effect estimate with a standard error. It compares each observed \(\Delta y\) directly with the corresponding model-implied contribution change. Sampling noise can give a negative estimate even when spend increased, so there is no requirement that \(\Delta x\) and \(\Delta y\) have the same sign.

For heavier-tailed estimates, pass a serializable likelihood such as likelihood=Prior("StudentT", nu=4). Gamma is available only when both observed and model-implied lifts are positive. The former Gamma-on-absolute-lift default could create a secondary mode for some high signal-to-noise rows; see issue #2958.

Implementation Algorithm

The following steps outline how lift test observations are added to a PyMC model:

Step 1: Scale the Lift Test Data

MMMs may work with scaled data internally (this example uses fixed unit scaling with scale factors of one). Lift tests, however, are specified in original units. Therefore, the first step is to transform the lift test measurements to match the model’s internal scale:

# Pseudo-code
# Scale channel-related measurements (x, delta_x)
x_scaled = channel_scaler.transform(x)
delta_x_scaled = channel_scaler.transform(x + delta_x) - x_scaled

# Scale target-related measurements (delta_y, sigma) 
delta_y_scaled = target_scaler.transform(delta_y)
sigma_scaled = target_scaler.transform(sigma)

This ensures that the lift test observations are compatible with the model’s internal representation of channels and target.

NOTE: This is done internally, users do not implement this step.

Step 2: Map DataFrame Coordinates to Model Indices

Each row in the lift test DataFrame corresponds to specific coordinates in the model. We need to map these coordinate values to their integer indices in the model:

# Example: if df has channel values ["channel_1", "channel_2", "channel_1"]
# and the model coords are {"channel": ["channel_1", "channel_2", "channel_3"]}
# then we map to indices: [0, 1, 0]

indices = {}
for dim in required_dims:  # e.g., ["channel"] or ["channel", "geo"]
    lift_values = df_lift_test[dim].values
    model_coords = model.coords[dim]
    # Find index of each lift test value in model coordinates
    indices[dim] = [model_coords.index(val) for val in lift_values]

This coordinate mapping is essential for extracting the correct parameter values for each lift test.

Note: For a simple national-level MMM (with only a “channel” dimension), this step is straightforward—you’re just mapping channel names to indices. The complexity of this step increases for multi-dimensional models (e.g., channel × geo × product) where each lift test must be mapped across multiple coordinate dimensions simultaneously.

Step 3: Extract Parameter Values for Each Lift Test

For each lift test, we need to extract the specific parameter values that apply to that test’s coordinates. For example, if testing “channel_1”, we need saturation_lam[0] and saturation_beta[0]:

# Create an indexer function that extracts parameters at specific coordinates
def get_parameter_at_indices(param_name):
    param = model[param_name]  # e.g., saturation_lam with dims=("channel",)
    dims = model.named_vars_to_dims[param_name]  # e.g., ("channel",)
    
    # Index into parameter using the coordinate indices
    idx = tuple([indices[dim] for dim in dims])
    return param[idx]

# Example: for lift tests on channels [0, 1, 0]
# get_parameter_at_indices("saturation_lam") returns [lam[0], lam[1], lam[0]]

Step 4: Evaluate the Saturation Curves

Now we compute the model’s prediction for each lift test by evaluating the saturation function at two points: before and after the spend change:

# Convert lift test data to PyTensor tensors
x_before = pt.as_tensor_variable(df_lift_test["x_scaled"])
x_after = x_before + pt.as_tensor_variable(df_lift_test["delta_x_scaled"])

# Define saturation curve evaluation with extracted parameters
def saturation_curve(x):
    return saturation_function(
        x,
        lam=get_parameter_at_indices("saturation_lam"),
        beta=get_parameter_at_indices("saturation_beta"),
    )

# Compute model-estimated lift: the key computation
model_estimated_lift = saturation_curve(x_after) - saturation_curve(x_before)

This model_estimated_lift is a PyTensor expression that depends on the model parameters, so it becomes part of the computational graph and will be different for each MCMC sample.

Step 5: Add the Likelihood Term

Finally, we add a Normal observation to the PyMC model that links the model’s predicted lift to the empirically observed lift:

with model:
    pm.Normal(
        name="lift_measurements",
        mu=model_estimated_lift,  # signed model prediction
        sigma=df_lift_test["sigma_scaled"],  # measurement uncertainty
        observed=df_lift_test["delta_y_scaled"],  # signed observed lift
    )

This creates an additional likelihood term in the model. During MCMC sampling, the sampler will try to find parameter values that not only fit the main time series data but also produce saturation curves consistent with the lift test observations.

Summary

Lift tests act as additional observations of the saturation curve that constrain the model parameters during inference. Instead of only learning from the historical time series (which may have limited variation or correlated channels), the model also learns from controlled experiments that directly probe the saturation curve at specific points.

This is particularly valuable when:

  • Channels are highly correlated in historical data (as in this notebook’s example)

  • You want to validate that the model’s saturation curves match real-world behavior

  • Historical data has limited variation in spend levels for certain channels

By adding lift test measurements, you’re essentially saying: “I know that at spend level \(x\) for this channel, a change of \(\Delta x\) produces a contribution change of approximately \(\Delta y\).” This directly informs the saturation curve parameters and helps the model distinguish between otherwise confounded effects.

We can refit the model but with the lift tests included

idata_with = mmm.fit(X, y, **fit_kwargs)

Hide code cell output

NUTS[numpyro]: [saturation_lam, saturation_beta, adstock_alpha, intercept_contribution, y_sigma]

The lift measurements add experimental evidence to the response curve. Before treating the curves below as a success score, keep the target of calibration in view: each test constrains an average response over one spend interval. It can therefore inform the local mROAS near that interval without identifying the entire curve at every spend level. The curves are useful diagnostics of what changed, while the mROAS comparison after the additional tests reports the decision quantity directly.

Hide code cell content

def plot_channel_rug(
    df: pd.DataFrame, color: str, ax: plt.Axes, height: float
) -> plt.Axes:
    for x in df["x"].to_numpy():
        ax.axvline(x, ymin=0, ymax=height, color=color)
    return ax


def plot_lift_test_rug(df, ax, height: float = 0.05) -> plt.Axes:
    idx = df["channel"] == "channel 1"
    plot_channel_rug(df.loc[idx], color="C0", ax=ax, height=height)
    plot_channel_rug(df.loc[~idx], color="C1", ax=ax, height=height)

    return ax
curve = mmm.saturation.sample_curve(
    mmm.fit_result[["saturation_beta", "saturation_lam"]], max_value=1.1
)
fig, axes = mmm.plot.saturation_curves(
    curve,
    original_scale=True,
    n_samples=10,
    hdi_probs=0.85,
    random_seed=rng,
    subplot_kwargs={"figsize": (12, 8), "ncols": 2},
    rc_params={
        "xtick.labelsize": 10,
        "ytick.labelsize": 10,
        "axes.labelsize": 10,
        "axes.titlesize": 10,
    },
)


def plot_lift_test_rugs_on_axes(
    axes_array: np.ndarray, df: pd.DataFrame, height: float = 0.05
) -> np.ndarray:
    # Channel 1 lift tests on first axis
    idx_c1 = df["channel"] == "channel 1"
    if idx_c1.any():
        plot_channel_rug(df.loc[idx_c1], color="C0", ax=axes_array[0], height=height)
    # Channel 2 lift tests on second axis
    idx_c2 = df["channel"] == "channel 2"
    if idx_c2.any():
        plot_channel_rug(df.loc[idx_c2], color="C1", ax=axes_array[1], height=height)
    return axes_array


axes = np.ravel(axes)
plot_actual_curves(axes, linestyle="dashed")
plot_lift_test_rugs_on_axes(axes, df_lift_test)
fig.suptitle(
    "Direct response curves (points) and actual saturation curves (dashed lines)"
);
Sampling: []

../../_images/76d44c4d00cf49698bd18f13be7c5c79bcb772a71414fccf7be05730f8dc8670.png

The ‘rug’ marks in the plot above show the initial channel spend before the lift test.

The first set of noisy lift estimates may move response parameters or change their interval widths. The forest plots use $ million units for both posterior and planted truth.

Hide code cell content

def plot_comparison(data, model_names, var_name: str):
    combined = xr.concat(
        [original_unit_parameter_idata(d)["posterior"].dataset for d in data],
        dim="model",
    ).assign_coords(model=model_names)
    dt = xr.DataTree.from_dict({"/posterior": xr.DataTree(combined)})
    pc = azp.plot_forest(
        dt,
        var_names=[var_name],
        combined=True,
        figure_kwargs={"figsize": (8, 4)},
    )
    return pc, pc.viz["plot"].sel(column="forest").item()
data = [idata_without, idata_with]
model_names = ["without lift tests", "with lift tests"]

pc, ax = plot_comparison(data, model_names, "saturation_lam")
plot_true_value(
    true_lam_c1, "channel 1", ax, pc, "saturation_lam", label=f"true λ₁ = {true_lam_c1}"
)
plot_true_value(
    true_lam_c2, "channel 2", ax, pc, "saturation_lam", label=f"true λ₂ = {true_lam_c2}"
)
ax.legend(fontsize=9, loc="upper right");
pc, ax = plot_comparison(data, model_names, "saturation_beta")
plot_true_value(
    true_beta_c1,
    "channel 1",
    ax,
    pc,
    "saturation_beta",
    label=f"true β₁ = {true_beta_c1}",
)
plot_true_value(
    true_beta_c2,
    "channel 2",
    ax,
    pc,
    "saturation_beta",
    label=f"true β₂ = {true_beta_c2}",
)
ax.legend(fontsize=9, loc="upper right");

The parameter posteriors respond to the first lift batch, but a posterior mean’s movement and its interval width answer different questions. The finite-lift and business-unit mROAS comparisons below provide the direct checks for the calibration goal.

The initial lift set changes the contribution estimates, but it does not uniformly improve them. Channel 1 moves closer to the simulated contribution while its interval shifts rather than clearly narrowing. Channel 2 moves farther from its simulated contribution; see the mROAS comparison below for the corresponding interval-coverage check.

plot_channel_contributions(mmm, df)

Add Additional Lift Tests#

We can add even more lift tests.

They can either all be added at one time or separately.

df_additional_lift_test = pd.DataFrame(
    [
        # More for Channel x1
        create_lift_test_from_actual_curve("channel 1", 0.1, 0.05, sigma=0.01),
        create_lift_test_from_actual_curve("channel 1", 0.5, 0.05, sigma=0.01),
        # More for channel x2
        create_lift_test_from_actual_curve("channel 2", 0.3, 0.05, sigma=0.01),
    ]
)

display(
    df_additional_lift_test.assign(
        simulated_truth=[
            true_lift_at_row(row) for row in df_additional_lift_test.itertuples()
        ]
    ).round(4)
)
channel x delta_x delta_y sigma simulated_truth
0 channel 1 0.1 0.05 0.0958 0.01 0.0952
1 channel 1 0.5 0.05 0.0006 0.01 0.0029
2 channel 2 0.3 0.05 0.0383 0.01 0.0354

Use the name parameter in order to separate the two sets of observations in the model graph.

mmm.add_lift_test_measurements(df_additional_lift_test, name="more_lift_measurements")

mmm.graphviz()
../../_images/067770d6d37ba5f1a2961c32a6c22b9a9c13dbd9e27735cde968b1691e5f7fd4.svg
idata_with_more = mmm.fit(X, y, **fit_kwargs)
NUTS[numpyro]: [saturation_lam, saturation_beta, adstock_alpha, intercept_contribution, y_sigma]

The expanded test set adds constraints at new effective-spend levels. The next plots show how the inferred response curves and contributions change before we compare finite lift and mROAS directly.

df_all_lift_tests = pd.concat([df_lift_test, df_additional_lift_test])
curve = mmm.saturation.sample_curve(
    mmm.fit_result[["saturation_beta", "saturation_lam"]], max_value=1.1
)
fig, axes = mmm.plot.saturation_curves(
    curve,
    original_scale=True,
    n_samples=10,
    hdi_probs=0.85,
    random_seed=rng,
    subplot_kwargs={"figsize": (12, 8), "ncols": 2},
    rc_params={
        "xtick.labelsize": 10,
        "ytick.labelsize": 10,
        "axes.labelsize": 10,
        "axes.titlesize": 10,
    },
)
axes = np.ravel(axes)
plot_actual_curves(axes, linestyle="dashed")
plot_lift_test_rugs_on_axes(axes, df_all_lift_tests)
fig.suptitle(
    "Direct response curves (points) and actual saturation curves (dashed lines)"
);
Sampling: []

../../_images/39c11e55f89f11cdcf20eb0eadeb5aa2d4cc944105506c09406f8764a69bf1d6.png
data = [idata_without, idata_with, idata_with_more]
model_names = ["without lift tests", "with lift tests", "with more lift tests"]

pc, ax = plot_comparison(data, model_names, "saturation_lam")
plot_true_value(
    true_lam_c1, "channel 1", ax, pc, "saturation_lam", label=f"true λ₁ = {true_lam_c1}"
)
plot_true_value(
    true_lam_c2, "channel 2", ax, pc, "saturation_lam", label=f"true λ₂ = {true_lam_c2}"
)
ax.legend(fontsize=12, loc="lower right");
pc, ax = plot_comparison(data, model_names, "saturation_beta")
plot_true_value(
    true_beta_c1,
    "channel 1",
    ax,
    pc,
    "saturation_beta",
    label=f"true β₁ = {true_beta_c1}",
)
plot_true_value(
    true_beta_c2,
    "channel 2",
    ax,
    pc,
    "saturation_beta",
    label=f"true β₂ = {true_beta_c2}",
)
ax.legend(fontsize=12, loc="upper right");

The extra rows constrain different parts of the channel response curves. Read their effect on parameter location and uncertainty alongside the finite-lift check and mROAS table; one noisy row need not improve every quantity.

The expanded lift set narrows the contribution intervals relative to the uncalibrated fit and moves the plotted posterior means closer to the simulated contributions. These are results of this simulated data set; the finite-lift and mROAS comparison below makes the assessment at the tested spend levels explicit.

plot_channel_contributions(mmm, df)

The identical historical spend series make the uncalibrated channel effects weakly identified. NUTS therefore needs a high acceptance target to avoid divergent transitions in this example. This setting improves exploration of the posterior geometry; it does not make the separate channel effects identifiable. The table checks divergences, rank-normalized \(\hat R\), and bulk and tail effective sample sizes for the saturation parameters in all three fits. These diagnostics are necessary for interpreting the mROAS comparison, but cannot by themselves establish causal identification.

diagnostic_rows = []
for name, idata in {
    "Uncalibrated": idata_without,
    "Initial test set": idata_with,
    "Expanded test set": idata_with_more,
}.items():
    diagnostic = az.summary(
        idata, var_names=["saturation_lam", "saturation_beta"], kind="diagnostics"
    )
    diagnostic_rows.append(
        {
            "fit": name,
            "divergences": int(idata.sample_stats.diverging.sum()),
            "max R-hat": diagnostic["r_hat"].max(),
            "min bulk ESS": diagnostic["ess_bulk"].min(),
            "min tail ESS": diagnostic["ess_tail"].min(),
        }
    )
display(pd.DataFrame(diagnostic_rows).round(3))
fit divergences max R-hat min bulk ESS min tail ESS
0 Uncalibrated 0 1.00 1302 1349
1 Initial test set 0 1.00 1501 1411
2 Expanded test set 0 1.00 1556 1784

Finite return and marginal ROAS in business units#

A lift row directly constrains the finite return \(\Delta y / \Delta x\) across its tested effective-spend interval. The fitted curve implies the next-dollar slope, or mROAS, at a selected spend. We compare all three models at the same spend for each channel: the mean baseline spend across that channel’s rows. The initial set has four rows and the expanded set adds three.

Fixed unit scaling keeps posterior saturation parameters in business units. The helper below still reads the model’s actual scales, so the derivative remains correct if a different fixed scale is chosen. The resulting slope is $ of sales per $ of spend. Lift rows themselves are passed in original units and are scaled by add_lift_test_measurements.

Caption: Posterior mROAS at each channel’s mean test baseline spend. Points are posterior means, bars are 94% HDIs, and dashed lines mark the simulated business-unit values. This static slope excludes the separate time path of campaign carryover.

def logistic_sat_np(spend, lam):
    """Logistic saturation on NumPy arrays in business-unit spend."""
    return (1 - np.exp(-lam * spend)) / (1 + np.exp(-lam * spend))


def logistic_mroas(lam, beta, spend):
    """Compute the derivative of beta * logistic_sat_np(spend, lam)."""
    return beta * lam / 2 * (1 - logistic_sat_np(spend, lam) ** 2)


def business_parameter_samples(model, idata, channel):
    """Convert posterior response parameters to $ million business units."""
    scales = model.get_scales_as_xarray()
    channel_scale = float(scales["channel_scale"].sel(channel=channel))
    target_scale = float(scales["target_scale"])
    lam = idata.posterior["saturation_lam"].sel(channel=channel).values.ravel()
    beta = idata.posterior["saturation_beta"].sel(channel=channel).values.ravel()
    return lam / channel_scale, beta * target_scale


model_results = {
    "Uncalibrated": idata_without,
    "Initial test set": idata_with,
    "Expanded test set": idata_with_more,
}
model_colors = {
    "Uncalibrated": COLOR_MMM_UNCALIBRATED,
    "Initial test set": COLOR_MMM_CALIBRATED,
    "Expanded test set": COLOR_MMM_MORE_TESTS,
}
reference_spend = df_all_lift_tests.groupby("channel")["x"].mean()
true_parameters = {
    "channel 1": (true_lam_c1, true_beta_c1),
    "channel 2": (true_lam_c2, true_beta_c2),
}

summary_rows = []
fig, axes = plt.subplots(1, 2, figsize=(FIG_WIDTH, FIG_HEIGHT), sharey=True)
for ax, channel in zip(axes, ["channel 1", "channel 2"], strict=True):
    spend_at_test = reference_spend.loc[channel]
    true_lam, true_beta = true_parameters[channel]
    true_value = logistic_mroas(true_lam, true_beta, spend_at_test)
    for position, (model_name, idata) in enumerate(model_results.items()):
        lam, beta = business_parameter_samples(mmm, idata, channel)
        samples = logistic_mroas(lam, beta, spend_at_test)
        lower, upper = az.hdi(samples, prob=0.94)
        mean = samples.mean()
        summary_rows.append(
            {
                "channel": channel,
                "model": model_name,
                "posterior mean": mean,
                "94% HDI lower": lower,
                "94% HDI upper": upper,
                "simulated value": true_value,
                "absolute error": abs(mean - true_value),
                "94% HDI width": upper - lower,
                "truth in HDI": lower <= true_value <= upper,
            }
        )
        ax.errorbar(
            position,
            mean,
            yerr=[[mean - lower], [upper - mean]],
            fmt="o",
            color=model_colors[model_name],
            capsize=4,
            label=model_name,
        )
    ax.axhline(
        true_value, color=COLOR_SIMULATED_TRUTH, linestyle="--", label="Simulated value"
    )
    ax.set_title(f"{channel.title()} at ${spend_at_test:.2f}M/week", fontsize=12)
    ax.set_xticks(
        range(len(model_results)),
        ["No tests", "Initial set", "Expanded set"],
        fontsize=11,
    )
    ax.set_ylabel("mROAS ($ sales / $ spend)" if ax is axes[0] else "", fontsize=11)
    ax.tick_params(axis="y", labelsize=11)
    ax.grid(axis="y", alpha=0.25)

display(pd.DataFrame(summary_rows).round(3))
handles, labels = axes[0].get_legend_handles_labels()
fig.legend(
    handles, labels, loc="upper center", ncol=4, bbox_to_anchor=(0.5, 1.04), fontsize=10
)
fig.tight_layout(rect=(0.08, 0.02, 0.99, 0.9))
plt.show()

# Check the directly calibrated quantity at every measured interval.
finite_rows = []
for stage, idata, rows in [
    ("Initial test set", idata_with, df_lift_test),
    ("Expanded test set", idata_with_more, df_all_lift_tests),
]:
    for row in rows.itertuples():
        lam, beta = business_parameter_samples(mmm, idata, row.channel)
        estimated = beta * (
            logistic_sat_np(row.x + row.delta_x, lam) - logistic_sat_np(row.x, lam)
        )
        finite_rows.append(
            {
                "model": stage,
                "channel": row.channel,
                "x ($M/week)": row.x,
                "measured lift ($M/week)": row.delta_y,
                "model lift ($M/week)": estimated.mean(),
                "sigma": row.sigma,
            }
        )
df_finite_check = pd.DataFrame(finite_rows)
df_finite_check["residual / sigma"] = (
    df_finite_check["model lift ($M/week)"] - df_finite_check["measured lift ($M/week)"]
) / df_finite_check["sigma"]
display(df_finite_check.round(3))
channel model posterior mean 94% HDI lower 94% HDI upper simulated value absolute error 94% HDI width truth in HDI
0 channel 1 Uncalibrated 0.475 0.000 1.083 0.988 0.513 1.083 True
1 channel 1 Initial test set 0.758 0.069 1.412 0.988 0.229 1.343 True
2 channel 1 Expanded test set 1.170 0.786 1.539 0.988 0.182 0.752 True
3 channel 2 Uncalibrated 0.365 0.000 0.793 0.686 0.321 0.793 True
4 channel 2 Initial test set 0.277 0.000 0.663 0.686 0.409 0.663 False
5 channel 2 Expanded test set 0.581 0.285 0.876 0.686 0.106 0.591 True
../../_images/ba2cd504bc466473a4688c60b899932463e216ef07fa6a5bbb5332161f4532d7.png
model channel x ($M/week) measured lift ($M/week) model lift ($M/week) sigma residual / sigma
0 Initial test set channel 1 0.05 0.100 0.044 0.05 -1.122
1 Initial test set channel 1 0.15 0.072 0.040 0.05 -0.640
2 Initial test set channel 1 0.30 -0.040 -0.035 0.05 0.087
3 Initial test set channel 2 0.50 0.015 0.012 0.10 -0.034
4 Expanded test set channel 1 0.05 0.100 0.108 0.05 0.162
5 Expanded test set channel 1 0.15 0.072 0.074 0.05 0.039
6 Expanded test set channel 1 0.30 -0.040 -0.043 0.05 -0.062
7 Expanded test set channel 2 0.50 0.015 0.026 0.10 0.101
8 Expanded test set channel 1 0.10 0.096 0.092 0.01 -0.378
9 Expanded test set channel 1 0.50 0.001 0.008 0.01 0.763
10 Expanded test set channel 2 0.30 0.038 0.031 0.01 -0.710

The finite-lift table reports each model-implied mean minus its noisy measurement in standard-error units. This is a model diagnostic, not an execution threshold. For mROAS, the expanded set lowers absolute error for both channels and narrows both 94% intervals relative to the uncalibrated fit. The first set is mixed: Channel 1 moves closer to truth but widens (HDI width 1.08 → 1.34); Channel 2 narrows (0.79 → 0.66) but moves farther from truth, and its simulated mROAS falls outside the 94% HDI. The added, more precise rows bring both channels closer and narrow their intervals to about 0.75 and 0.59.

Constraint based on Cost Per Target#

If you don’t have experimental information in that shape, you can provide the estimated cost per target for each channel (e.g: cost per install, cost per registration, cost per action, cost per unit sale) and calibrate the model response based on it.

mmm.add_cost_per_target_calibration?
avg_cost_per_target_df = pd.DataFrame(
    {
        "channel": ["channel 1"],
        "cost_per_target": [1.03],
        "sigma": [0.1],
    }
)
mmm.add_cost_per_target_calibration(
    data=df[["date", "channel 1", "channel 2"]],
    calibration_data=avg_cost_per_target_df,
)
mmm.graphviz()
../../_images/226cb149170a62aedaf31d0d80958199bae36ce8a2cdfbc40819fd4a4b640beb.svg
idata_with_more_and_penalty = mmm.fit(X, y, **fit_kwargs)
NUTS[numpyro]: [saturation_lam, saturation_beta, adstock_alpha, intercept_contribution, y_sigma]

plot_channel_contributions(mmm, df)

Conclusion#

add_lift_test_measurements incorporates independent experimental estimates in their original business units; fixed unit scaling keeps the model in the same business units. A finite lift directly checks the return over the tested interval. Point mROAS follows from the calibrated response curve and need not improve monotonically with every noisy test. Compare the model-implied finite lifts with the supplied measurements before interpreting the mROAS plot.

%load_ext watermark
%watermark -n -u -v -iv -w -p pymc_marketing,pytensor
Last updated: Mon, 12 Oct 2026

Python implementation: CPython
Python version       : 3.12.12
IPython version      : 9.15.0

pymc_marketing: 1.1.0
pytensor      : 3.3.2

IPython       : 9.15.0
arviz         : 1.2.0
arviz_plots   : 1.2.0
matplotlib    : 3.11.1
numpy         : 2.4.6
pandas        : 3.0.5
pymc          : 6.3.2
pymc_marketing: 1.1.0
seaborn       : 0.13.2
xarray        : 2026.4.0

Watermark: 2.6.0