CUPAC in Python: Use a Machine Learning Model to Reduce A/B Test Variance

Implement CUPAC in Python: train a gradient boosting model on a past cohort, use its prediction as the CUPED covariate, and see how much narrower the A/B test interval gets than with CUPED or linear regression.

CUPAC (Control Using Predictions As Covariates) is CUPED with a machine learning model supplying the covariate. You train a model on a past cohort to predict the metric from pre-experiment features, predict for the users in your experiment, and use that prediction in place of a single pre-period metric: y_adj = y - theta * (pred - pred.mean()). The treatment estimate stays unbiased because the prediction uses only data from before the experiment, and the interval narrows in proportion to how well the model predicts the outcome. It helps most when the metric depends on many features, or depends on them nonlinearly, so a single pre-period value (what CUPED uses) leaves a lot of variance on the table.

Quick Example

The data is simulated: weekly order value for shoppers, with a true treatment effect of +$2. Each user has a handful of pre-experiment attributes (tenure, app sessions, plan, device, region) plus last period's order value, y_pre. The model trains on 20,000 users from an earlier cohort that never saw the treatment, then predicts for the 4,000 users in the experiment.

import numpy as np
import pandas as pd
from scipy import stats
from sklearn.ensemble import HistGradientBoostingRegressor


def make_users(n, rng, effect=0.0):
    """Weekly order value for n shoppers. `y_pre` is last period's value; the rest
    are pre-experiment attributes. The link to the outcome is nonlinear."""
    tenure = rng.exponential(18, n).clip(0, 80)              # months as a customer
    sessions = rng.poisson(6, n)                              # weekly app sessions
    plan = rng.choice([0, 1, 2], n, p=[0.55, 0.3, 0.15])     # 0 free, 1 plus, 2 pro
    mobile = rng.binomial(1, 0.65, n)
    region = rng.integers(0, 6, n)
    region_lift = np.array([0, 4, -3, 8, 2, -5])[region]
    base = (10 + 14 * np.log1p(sessions) * (1 + 0.5 * plan)
            + 0.6 * np.minimum(tenure, 30) + region_lift
            + 12 * (plan == 2) * (sessions > 7) - 6 * mobile * (plan == 0))
    y_pre = (base + rng.normal(0, 14, n)).clip(0)
    group = rng.integers(0, 2, n)
    y = (base + rng.normal(0, 14, n) + effect * group).clip(0)
    return pd.DataFrame({"tenure": tenure, "sessions": sessions, "plan": plan,
                         "mobile": mobile, "region": region, "y_pre": y_pre,
                         "group": group, "y": y})


FEATURES = ["tenure", "sessions", "plan", "mobile", "region", "y_pre"]
TRUE_EFFECT = 2.0
rng = np.random.default_rng(21)
history = make_users(20000, rng)                  # a past cohort, no treatment
df = make_users(4000, rng, effect=TRUE_EFFECT)    # the experiment

# CUPAC: predict the metric from pre-experiment features, then adjust with the prediction
model = HistGradientBoostingRegressor(max_depth=4, learning_rate=0.08, max_iter=250,
                                      random_state=0).fit(history[FEATURES], history["y"])
df["pred"] = model.predict(df[FEATURES])


def adjust(y, x):
    theta = np.cov(y, x)[0, 1] / np.var(x, ddof=1)
    return y - theta * (x - x.mean())


df["y_cuped"] = adjust(df["y"], df["y_pre"])      # classic CUPED, for comparison
df["y_cupac"] = adjust(df["y"], df["pred"])

for col in ["y", "y_cuped", "y_cupac"]:
    a, b = df.loc[df.group == 1, col], df.loc[df.group == 0, col]
    res = stats.ttest_ind(a, b, equal_var=False)
    ci = res.confidence_interval(0.95)
    print(f"{col:8s} lift = {a.mean() - b.mean():+.2f}  CI [{ci.low:.2f}, {ci.high:.2f}]  "
          f"width {ci.high - ci.low:.2f}")
y        lift = +2.66  CI [1.31, 4.02]  width 2.72
y_cuped  lift = +2.29  CI [1.20, 3.39]  width 2.19
y_cupac  lift = +2.02  CI [1.14, 2.89]  width 1.75

The unadjusted interval is $2.72 wide. CUPED shrinks it to $2.19, and CUPAC to $1.75, about 36% narrower than no adjustment. The unadjusted estimate of +$2.66 also lands a bit above the true +$2 by chance. The adjusted ones are pulled back toward it because the covariate soaks up baseline differences between the two random groups.

Horizontal confidence intervals for the estimated lift: no adjustment is widest at 2.72, CUPED is 2.19, a linear regression prediction is 1.89, and CUPAC with gradient boosting is narrowest at 1.75, with a dashed line at the true effect of 2

The chart adds one more row, a linear regression trained on the same features and used the same way. It matters for the honest comparison, and we come back to it below.

Why a Model Prediction Works as a Covariate

CUPED needs a covariate that correlates with the outcome and is unaffected by treatment. Any function of pre-experiment data qualifies. A model's prediction is just a function of several pre-experiment columns, compressed into one number that tracks the outcome as well as possible. Two things have to hold:

  • The model only sees pre-experiment features. Never include the treatment flag or any in-experiment behavior. Anything the treatment can touch would make the adjustment biased.
  • The model doesn't train on the experiment's own outcomes. Train on a past cohort, as above. If you must train on the experiment users, use cross-fitting (cross_val_predict with a handful of folds) so each user's prediction comes from a model that never saw their outcome.

On the experiment users, last period's value correlates with the outcome at r = 0.59, while the gradient boosting prediction reaches r = 0.76:

Two scatter plots of order value during the test: against last period's order value the points form a wide cloud with correlation 0.59, against the gradient boosting prediction they sit in a much tighter band with correlation 0.76

As with CUPED, the variance that remains is 1 - r² of the original. For this data df["y_cuped"].var() / df["y"].var() is 0.65, and the CUPAC equivalent is 0.42, so the standard error drops to sqrt(0.42), about 65% of the unadjusted one.

How Much Better Is CUPAC Than a Linear Model?

Less than the headline suggests, and that is worth knowing before you build a model pipeline. Most of the gain over CUPED comes from using more features, not from using a fancier model. Here is the same experiment with each covariate, measured as the share of the unadjusted variance that remains:

from sklearn.linear_model import LinearRegression

lin = LinearRegression().fit(history[FEATURES], history["y"])
df["pred_lin"] = lin.predict(df[FEATURES])
df["y_linear"] = adjust(df["y"], df["pred_lin"])

(df[["y_cuped", "y_linear", "y_cupac"]].var() / df["y"].var()).round(3)
y_cuped     0.649
y_linear    0.483
y_cupac     0.415

A plain linear regression on all six features removes about half the variance (0.483 remaining), against 0.649 for CUPED on y_pre alone. Gradient boosting adds another step to 0.415. The extra comes from the interactions and thresholds in the simulated data, such as the bonus that only pro-plan users with more than seven sessions get, which a linear model can't represent.

Covariate Correlation with outcome Variance remaining CI width
None n/a 1.00 2.72
y_pre (CUPED) 0.59 0.65 2.19
Linear regression prediction 0.72 0.48 1.89
Gradient boosting prediction (CUPAC) 0.77 0.42 1.75

On real data the gap between the linear and boosted versions depends on how nonlinear your metric is. If a linear model gets you most of the way, you can skip the model-serving machinery, and the regression form (smf.ols("y ~ group + pre + tenure + ...")) from the CUPED post does the same job.

Is the CUPAC Estimate Still Unbiased?

Yes, and a simulation shows it. The check is to run 500 independent experiments with a true effect of +$2, reusing the model trained on history, and look at the mean and spread of each method's estimate:

sim = {k: [] for k in ["raw", "cuped", "linear", "cupac"]}
sim_rng = np.random.default_rng(99)
for _ in range(500):
    d = make_users(4000, sim_rng, effect=TRUE_EFFECT)
    d["pred"] = model.predict(d[FEATURES])
    d["pred_lin"] = lin.predict(d[FEATURES])
    cols = {"raw": d["y"], "cuped": adjust(d["y"], d["y_pre"]),
            "linear": adjust(d["y"], d["pred_lin"]), "cupac": adjust(d["y"], d["pred"])}
    for k, v in cols.items():
        sim[k].append(v[d.group == 1].mean() - v[d.group == 0].mean())

pd.DataFrame({k: [np.mean(v), np.std(v, ddof=1)] for k, v in sim.items()},
             index=["mean", "sd"]).T.round(3)
         mean     sd
raw     2.039  0.679
cuped   2.034  0.530
linear  2.018  0.462
cupac   2.011  0.434

All four methods average close to the true 2.0, so the adjustment doesn't bias the lift. What changes is the spread: the standard deviation of the estimate falls from 0.68 (raw) to 0.43 (CUPAC). That is a variance ratio of 0.41, matching the single-experiment number, and it means you could reach the same precision with roughly 40% of the users, or detect a smaller effect with the same traffic. Use the variance ratio with the sample size and power calculation to plan that.

Overlaid histograms of the estimated lift across 500 simulated experiments: all three methods center on the true effect of 2, with the unadjusted histogram widest at standard deviation 0.68, CUPED 0.53, and CUPAC narrowest at 0.43

When to Use CUPAC vs CUPED

Situation Use
You have the same metric from before the experiment and not much else CUPED
You have many pre-experiment features (tenure, device, plan, history) Regression adjustment or CUPAC
The metric depends on features through thresholds and interactions CUPAC
New users with no history CUPAC on attributes like device and acquisition channel, since CUPED has no y_pre to use
You can't keep a model retrained and versioned CUPED or linear regression

Practical Tips

  • Freeze the model before the experiment starts. Train it, save it, and write down the training date. Retraining halfway through changes the covariate mid-test.
  • Fit theta on the experiment users, not the history. adjust() estimates theta from the data in the test. That keeps the adjustment tuned to the actual relationship, and it also corrects for a model that is a bit overconfident or off in scale.
  • Check the prediction before you trust it. If the model's correlation on a held-out slice of history is low, CUPAC can't beat CUPED. A quick np.corrcoef on a validation split is enough.
  • Use the same covariate for both arms. Compute predictions with one model for everyone. Never fit separate models per arm.
  • Mind drift. A model trained on last year's cohort loses power if user behavior has changed, but it stays unbiased, because the adjustment can only fail to help, not fail to be valid.
  • Don't add leaky features. Anything measured after assignment, such as in-test sessions, can carry the treatment effect and bias the result.

Similar Topics