Algorithmresearch
CUPED
Also called controlled-experiment using pre-experiment data, regression adjustment for A/B tests.
Reduces the variance of an online experiment's estimate by subtracting theta times a pre-experiment covariate, with theta the regression coefficient, as in control variates.
- Time
- Θ(n) worst · best
- Space
- Θ(n) extra
- Where
- n = the number of units in both arms
- Model
- Real RAM
- Properties
- deterministicequals ancova with within thetaneeds pre treatment covariateunbiased for fixed theta
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Alex Deng, Ya Xu, Ron Kohavi, Toby Walker, 2013
CUPED (controlled-experiment using pre-experiment data) makes a randomized experiment more sensitive by removing from each unit's outcome the part that a covariate measured before the experiment already predicts. For a metric and a pre-experiment covariate , usually the same metric over an earlier period, it replaces with and compares the arm means of the adjusted values. Because is fixed before the coin is tossed, the adjustment does not move the mean of the estimate, but with the regression slope of on it cuts the variance by the factor , where is the correlation of and . It is the control variates method of Monte Carlo integration applied to an A/B test, and with the within-arm slope it gives exactly the analysis of covariance (ANCOVA) estimate. The cost is one pass over the data.
In plain words
Some users spend much more than others, week after week. In an A/B test this spread is noise: it hides the small change that the new version makes. But we already know how much each user spent last month, before the test started. CUPED takes away from each user's number the part that last month's number predicts, and compares what is left between the two groups.
Last month's spending cannot be affected by the new version, and the two groups were formed at random, so the subtraction takes away the same amount from both groups on average and the comparison stays fair. What it takes away is the spread that the two months share. If the months are strongly related, the remaining numbers are much less noisy, and the test needs fewer users or less time to detect the same change.
The problem
Identification. This is the identification of a randomized experiment. Each unit has potential outcomes and , the observed outcome is under SUTVA, and the treatment is assigned at random, so is independent of . The estimand is the average treatment effect , or its finite population version . It is identified by the difference of the arm means, ; no model is needed. The one extra assumption is that is a pre-treatment covariate: it is measured before the assignment, so the treatment cannot change it. This is checkable in part: the arms should have the same distribution of , and a test of is a test of the randomization and of this assumption.
Estimation. The input is the outcomes and covariates of the treated units and the control units, and a rule for . The output is an estimate of , the coefficient used, and an estimated variance. The estimator is
The second form shows what happens: if the treated arm happened to have a larger pre-period mean, the estimate is moved down by times that chance difference. Three rules for are common:
- Fixed in advance, for example from an earlier experiment. Then is exactly unbiased over the randomization.
- Pooled: the slope of on over all units, ignoring the arms, . This is the control variates formula .
- Within: the slope fitted inside each arm and pooled, which is the coefficient of in the regression of on .
An estimated makes biased by a term of order , which is negligible next to its standard error of order . The variance estimate is the Welch form computed on the adjusted values, with treated as fixed, and a normal interval follows. Unlike the propensity weighted estimators of observational studies, nothing here can fail by positivity: the assignment probabilities are known and away from 0 and 1 by design.
The algorithm
CUPED(Yt, Xt, Yc, Xc, rule) ▷ X measured before the experiment- 1
θ ← the value given by rule: fixed, pooled slope of Y on X, or within-arm slope - 2
x̄ ← mean of X over all n_t + n_c units - 3
for every unit i: A_i ← Y_i - θ (X_i - x̄) - 4
δ ← mean of A over the treated - mean of A over the controls - 5
v ← s²(A over treated) / n_t + s²(A over controls) / n_c - 6
return (δ, θ, v)
Line L1 is one pass of sums for the slope. Line L2 only centres the adjusted values; by the second form of it does not change , but it keeps the adjusted values on the scale of so that the per-arm means can be reported. Line L5 is the usual Welch variance of a difference in means, applied to the adjusted metric, and the interval is .
Example
Six users, three per arm. The covariate is last month's spending and the outcome is this month's.
| arm | ||
|---|---|---|
| treated | 2, 4, 6 | 5, 8, 11 |
| control | 1, 3, 5 | 2, 6, 7 |
The plain difference in means is , with Welch variance . But the treated users also spent more last month: against .
Within-arm . About the arm means, the treated deviations are and , and the control deviations are and . So and , and . With , the adjusted values are
| arm | adjusted values | mean | |
|---|---|---|---|
| treated | 113/16, 117/16, 121/16 | 117/16 | 1/16 |
| control | 87/16, 107/16, 79/16 | 91/16 | 13/16 |
so , and , against before. The least squares fit of on is : the coefficient of is the CUPED estimate, as the theory says.
Pooled . Over all six users, and , so and . The pooled slope is larger because the treated users are both higher in and, through the treatment, higher in , so part of the effect looks like slope. In a sample this small the two rules differ by 0.14; in the simulation below, with 500 users per arm, they never differed by more than 0.0013.
Simulation. , , so and the predicted factor is . Over 400 experiments with 500 users per arm (seed 2026), measured:
| estimator | mean | SD | 95% coverage |
|---|---|---|---|
| difference in means | 0.1065 | 0.0831 | 0.935 |
| CUPED, pooled | 0.1029 | 0.0499 | 0.930 |
| CUPED, within | 0.1030 | 0.0499 | 0.930 |
The ratio of the two Monte Carlo variances was 0.360, and the mean of the per-experiment ratio was also 0.360. The same precision without CUPED would need about times as many users.
Correctness
The full proofs are in the correctness proof. The key facts:
- The form. , whatever value is used for centring.
- Unbiased for a fixed . Under complete randomization each unit is treated with probability , so and . Hence exactly for any chosen without the assignment. The tests check this by listing all 20 assignments of 6 units with exact fractions.
- Estimated . Under the sharp null the pooled slope does not depend on the assignment, so the estimate is exactly unbiased there. With a real effect, , which is not 0 in general; the tests show a case. Freedman (2008) shows the bias is of order .
- The factor . is smallest at , where it equals . If both arms have the same variance and the same covariance with (for example a constant effect), the variance of falls by the same factor. The identity holds exactly for sample moments too, which the tests check.
- ANCOVA. In the regression of on , the residuals sum to 0 in each arm, which gives the coefficient of as with the coefficient of ; the normal equation for then makes the within-arm slope.
Proved: these exact statements. Cited, not proved: that an estimated leaves the large-sample distribution unchanged and that the interval has its nominal level (Deng et al. 2013; Lin 2013).
Proof: CUPED with a fixed coefficient is unbiased, the best coefficient cuts the variance by 1 - rho^2, and the within-arm coefficient gives the ANCOVA estimatefull
There are units. Unit has a covariate measured before the experiment and an outcome ; the treated arm has units and the control arm has units. Write for the means over , for the means over , and for the mean of over all units. CUPED returns
Lemma 1 (the form of the estimate). .
Proof. The mean of over is , and over it is . The terms cancel in the difference.
So centring by does not change ; it only keeps the adjusted values on the scale of , which makes the per-arm means readable.
Unbiased under randomization
Theorem 2 (fixed theta). Take the finite population view: each unit has fixed potential outcomes and a fixed , and the treated set is a uniformly random subset of size (complete randomization). Let . If does not depend on the assignment, then .
Proof. Each unit is treated with probability , so , and in the same way and . By Lemma 1 and linearity, .
The covariate must be measured before the treatment starts. If the treatment can change , then is not fixed in the sense of the theorem, and is the effect of the treatment on , which leaks into .
Theorem 3 (pooled theta under the sharp null). If for every unit, the pooled coefficient does not depend on the assignment, and .
Proof. Under the sharp null the observed equals whatever the assignment, and uses all units without their arm labels. So is a constant, and Theorem 2 applies with .
With a real effect, the pooled and the within-arm both depend on the assignment, and , which is not 0 in general. The tests find a population of 6 units where the mean over all 20 assignments differs from . Freedman (2008) shows the bias is of order ; it is not proved here.
The variance
Theorem 4 (the best coefficient). Let and be random variables with finite variances, , and correlation . Then is smallest at , and
The same identity holds for sample moments: with the sums of squares and cross products about the means, and , the sum of squares of about its mean is .
Proof. , a quadratic in with positive leading coefficient, smallest where its derivative is 0. Putting in gives , since . The sample version is the same algebra with in place of the moments.
Theorem 5 (the variance of the estimate). Take the sampling view: the units of each arm are independent, the treated units are draws of and the control units are draws of from one population, so has the same law in both arms. Let , and . For a fixed ,
It is smallest at . If and , which holds for example when the effect is the same for every unit, the smallest value is times the variance of , where is the correlation of and .
Proof. By Lemma 1, is the difference of the arm means of ; the two arms are independent and each mean averages independent terms, so the variance is the sum of , and each of these expands as in Theorem 4. The sum is a quadratic in with leading coefficient , smallest at . If and , then , and each arm term is by Theorem 4, while the unadjusted variance is .
When , the pooled coefficient estimates a weighted slope that need not be , and the variance can even rise when the arm sizes differ. This is the case that Freedman (2008) studied; Lin (2013) shows that fitting a separate slope in each arm removes the problem in large samples. The plug-in variance that CUPED reports (line L5) treats as fixed; its validity in large samples is cited from Deng et al. (2013) and Lin (2013).
The within-arm coefficient is ANCOVA
Theorem 6. Let , with a positive denominator. In the least squares fit of on , the coefficient of is and the coefficient of is .
Proof. Let be the coefficients of and the residuals. The normal equations for the columns and say and , so the residuals sum to 0 in each arm:
Subtracting, by Lemma 1. Substituting , where is the arm of unit , gives . The normal equation for the column , , becomes because in each arm. That is , so . The denominator is positive, so the design has full rank and the solution is unique.
What is proved and what is measured
Proved here: the form of the estimate (Lemma 1), exact unbiasedness over the randomization for any coefficient fixed in advance (Theorem 2) and for the pooled coefficient under the sharp null (Theorem 3), the factor for the best coefficient (Theorems 4 and 5), and the equality with the ANCOVA coefficient (Theorem 6). The tests check Lemma 1 and Theorems 2, 3, 4 and 6 exactly with fractions. Not proved: that the estimated coefficient changes the large-sample distribution by a negligible amount and that the interval has its nominal level; these come from Deng et al. (2013) and Lin (2013). The variance ratio 0.360 and the coverage on the page are measured in a simulation.
Complexity
Each step is a constant number of sums over the units, so the time is . The code keeps the adjusted values, space; a streaming version that keeps the sums of , , , and per arm needs space, at the cost of the cancellation risk of the textbook variance formula (use Welford's updates for large values). The real cost is in data engineering: joining each unit to its pre-period metric.
Properties
- No bias from the adjustment. The covariate is fixed before assignment, so the adjustment only removes noise. With a fixed this is exact; with an estimated the bias is of order .
- Gain set by the correlation. The variance falls by . For that is only 25%; for it is 81%. Metrics that are stable per user over time, such as sessions or spend, gain the most.
- Any is valid. A poor only loses precision; with the estimate is the plain difference in means.
- Same as regression. With the within-arm slope it is the ANCOVA coefficient exactly, so standard regression software gives the same point estimate.
- Missing pre-period data. New users have no . A common fix is to set to a constant and add an indicator of missingness as a second covariate; this is valid because the indicator is also pre-treatment.
Variants and improvements
- Separate slopes (Lin's estimator). Fit in the treated arm and in the control arm, and adjust each arm with its own slope around the overall . This is the regression with a interaction. Lin (2013) shows that it is never less precise than the unadjusted estimate in large samples, which is not true of a common slope when the arms differ in size and the effect varies with .
- Several covariates. Replace by with from a multiple regression; the factor becomes , with the coefficient of determination of on .
- Machine-learning predictions. Use as the covariate a prediction of from any model trained on pre-experiment data. As long as the model never sees the experiment's outcomes or assignments, the prediction is a pre-treatment covariate and the method stays valid. Cross-fitting as in double machine learning lets the model use the experiment's own covariates.
- Stratification. Post-stratifying by a discrete pre-period variable, when every stratum has units in both arms, is exactly the separate-slopes adjustment with the stratum indicators as covariates: in each arm the regression on the indicators fits the stratum means, and the adjusted arm mean weights them by the stratum shares.
- Ratio metrics. For metrics like clicks per session, apply CUPED to the linearized metric from the delta method.
When to use it
Use CUPED in every A/B test where a pre-experiment version of the metric exists, which is most tests on returning users. It costs one join and one pass, and the gain is free power: the same sensitivity with fewer users or a shorter test. It helps little for metrics with weak memory (one-off conversions), for new users without history, and for very short pre-periods. In an observational study, where is also needed to remove confounding, use an adjustment estimator such as AIPW instead: CUPED relies on randomization for its unbiasedness.
Pitfalls
- A covariate affected by the treatment. If is measured after exposure starts, even partly, the treatment's effect on is subtracted out. The pre-period must end before the first exposure.
- Choosing or the covariate after looking at the effect. Trying several covariates and reporting the one with the best p-value inflates the type I error. Fix the rule in advance.
- Common slope with unequal arms. With very unbalanced arms and heterogeneous effects, the pooled or within slope can make the estimate less precise (Freedman 2008). Use separate slopes.
- Reporting the pooled theta as the ANCOVA answer. They agree only in large samples; in small samples, as in the example, they differ. Say which rule was used.
- Variance of the wrong unit. If users are randomized but the metric is per page view, the units are not independent; compute the variance at the randomization unit (see cluster-robust standard errors).
- Missing dropped. Dropping units without pre-period data changes the population. Keep them with an imputed constant and an indicator.
Implementations
Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/cuped/. The authors are listed in prov/Y9J2V9.jsonl.
"""CUPED: variance reduction for a randomized experiment with a pre-experiment covariate.
Each unit has a metric y measured during the experiment and a covariate x measured
before it (often the same metric in an earlier period). The adjusted metric is
y_cv = y - theta (x - mean of x over all units),
and the effect estimate is the difference of the arm means of y_cv:
delta = (ybar_t - ybar_c) - theta (xbar_t - xbar_c).
theta can be a number fixed in advance, "pooled" (the slope of y on x over all units,
ignoring the arms) or "within" (the pooled within-arm slope). With "within", delta is
exactly the treatment coefficient of the regression of y on (1, T, x) (ANCOVA).
All functions are exact for Fraction inputs, except the interval.
"""
import math
from collections.abc import Sequence
from statistics import NormalDist
from typing import NamedTuple
class CupedResult(NamedTuple):
delta: object # the adjusted difference in means
theta: object # the coefficient used
var: object # the estimated variance of delta (Welch form, divisors n_t - 1 and n_c - 1)
naive_delta: object # ybar_t - ybar_c
naive_var: object # its estimated variance
def _mean(v):
return sum(v) / len(v)
def _svar(v):
m = _mean(v)
return sum((a - m) ** 2 for a in v) / (len(v) - 1)
def theta_pooled(y: Sequence, x: Sequence) -> object:
"""Slope of y on x over all units: sum (x - xbar)(y - ybar) / sum (x - xbar)^2."""
mx, my = _mean(x), _mean(y)
sxx = sum((a - mx) ** 2 for a in x)
if sxx == 0:
raise ValueError("the covariate is constant")
return sum((a - mx) * (b - my) for a, b in zip(x, y)) / sxx
def theta_within(yt, xt, yc, xc) -> object:
"""Pooled within-arm slope: the coefficient of x in the regression of y on (1, T, x)."""
mxt, myt, mxc, myc = _mean(xt), _mean(yt), _mean(xc), _mean(yc)
sxx = sum((a - mxt) ** 2 for a in xt) + sum((a - mxc) ** 2 for a in xc)
if sxx == 0:
raise ValueError("the covariate is constant within both arms")
sxy = sum((a - mxt) * (b - myt) for a, b in zip(xt, yt)) + sum((a - mxc) * (b - myc) for a, b in zip(xc, yc))
return sxy / sxx
def cuped(yt: Sequence, xt: Sequence, yc: Sequence, xc: Sequence, theta="pooled") -> CupedResult:
"""CUPED estimate of the treatment effect. Cost: Theta(n) time, Theta(n) space for the adjusted values."""
if len(yt) != len(xt) or len(yc) != len(xc):
raise ValueError("each arm needs one covariate per outcome")
if len(yt) < 2 or len(yc) < 2:
raise ValueError("each arm needs at least two units")
if theta == "pooled": # @line L1
th = theta_pooled(list(yt) + list(yc), list(xt) + list(xc))
elif theta == "within":
th = theta_within(yt, xt, yc, xc)
else:
th = theta
xbar = _mean(list(xt) + list(xc)) # @line L2
at = [b - th * (a - xbar) for a, b in zip(xt, yt)] # @line L3
ac = [b - th * (a - xbar) for a, b in zip(xc, yc)]
delta = _mean(at) - _mean(ac) # @line L4
var = _svar(at) / len(at) + _svar(ac) / len(ac) # @line L5
naive = _mean(yt) - _mean(yc)
nvar = _svar(yt) / len(yt) + _svar(yc) / len(yc)
return CupedResult(delta, th, var, naive, nvar) # @line L6
def interval(res: CupedResult, alpha: float = 0.05) -> tuple[float, float]:
"""Normal interval delta +- z sqrt(var), approximate level 1 - alpha."""
z = NormalDist().inv_cdf(1 - alpha / 2)
se = math.sqrt(float(res.var))
return float(res.delta) - z * se, float(res.delta) + z * se
# ----------------------------------------------------------------- reference: ANCOVA by least squares
def solve(a: list[list], b: list) -> list:
"""Solve a x = b by Gaussian elimination with partial pivoting (exact for Fractions)."""
k = len(b)
m = [list(row) + [bi] for row, bi in zip(a, b)]
for c in range(k):
p = max(range(c, k), key=lambda r: abs(m[r][c]))
if m[p][c] == 0:
raise ValueError("singular system")
m[c], m[p] = m[p], m[c]
for r in range(c + 1, k):
f = m[r][c] / m[c][c]
if f != 0:
for j in range(c, k + 1):
m[r][j] -= f * m[c][j]
out = [0] * k
for c in range(k - 1, -1, -1):
out[c] = (m[c][k] - sum(m[c][j] * out[j] for j in range(c + 1, k))) / m[c][c]
return out
def ancova(yt, xt, yc, xc) -> list:
"""Coefficients (intercept, T, x) of the least squares regression of y on (1, T, x)."""
one = xt[0] * 0 + 1 # 1 in the number type of the input, so Fractions stay exact
zero = one - one
rows = [[one, one, a] for a in xt] + [[one, zero, a] for a in xc]
y = list(yt) + list(yc)
xtx = [[sum(r[i] * r[j] for r in rows) for j in range(3)] for i in range(3)]
xty = [sum(r[i] * v for r, v in zip(rows, y)) for i in range(3)]
return solve(xtx, xty)
test_cuped.py 136 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/cuped/. The authors are listed in prov/Y9J2V9.jsonl.
import itertools
import math
import random
import statistics
from fractions import Fraction as Fr
import pytest
from cuped import ancova, cuped, interval, theta_pooled
def test_worked_example():
xt, yt = [Fr(2), Fr(4), Fr(6)], [Fr(5), Fr(8), Fr(11)]
xc, yc = [Fr(1), Fr(3), Fr(5)], [Fr(2), Fr(6), Fr(7)]
w = cuped(yt, xt, yc, xc, "within")
assert (w.naive_delta, w.theta, w.delta) == (3, Fr(11, 8), Fr(13, 8))
p = cuped(yt, xt, yc, xc, "pooled")
assert (p.theta, p.delta) == (Fr(53, 35), Fr(52, 35))
assert ancova(yt, xt, yc, xc) == [Fr(7, 8), Fr(13, 8), Fr(11, 8)]
def test_within_theta_equals_ancova_coefficient_exactly():
rng = random.Random(1)
for _ in range(200):
nt, nc = rng.randint(2, 7), rng.randint(2, 7)
xt = [Fr(rng.randint(-9, 9), rng.randint(1, 4)) for _ in range(nt)]
xc = [Fr(rng.randint(-9, 9), rng.randint(1, 4)) for _ in range(nc)]
yt = [Fr(rng.randint(-20, 20)) for _ in range(nt)]
yc = [Fr(rng.randint(-20, 20)) for _ in range(nc)]
try:
res = cuped(yt, xt, yc, xc, "within")
except ValueError:
continue
b = ancova(yt, xt, yc, xc)
assert res.delta == b[1] and res.theta == b[2]
def test_zero_theta_is_difference_in_means():
yt, xt, yc, xc = [Fr(3), Fr(5)], [Fr(1), Fr(2)], [Fr(1), Fr(4)], [Fr(0), Fr(7)]
r = cuped(yt, xt, yc, xc, 0)
assert r.delta == r.naive_delta == Fr(3, 2) and r.var == r.naive_var
def enumerate_designs(y1, y0, x, n_t):
"""All assignments of n_t of the n units to treatment, each equally likely (complete randomization)."""
n = len(x)
for tr in itertools.combinations(range(n), n_t):
s = set(tr)
yield ([y1[i] for i in tr], [x[i] for i in tr], [y0[i] for i in range(n) if i not in s], [x[i] for i in range(n) if i not in s])
def test_fixed_theta_is_exactly_unbiased_over_the_randomization():
"""n = 6 units with fixed potential outcomes, 3 treated: averaging over all 20 assignments,
CUPED with any theta fixed in advance has mean equal to the sample average treatment effect."""
rng = random.Random(2)
for _ in range(30):
x = [Fr(rng.randint(0, 9)) for _ in range(6)]
y0 = [xi + Fr(rng.randint(-3, 3)) for xi in x]
y1 = [v + Fr(rng.randint(-2, 6)) for v in y0]
tau = sum(a - b for a, b in zip(y1, y0)) / 6
for theta in (Fr(0), Fr(1), Fr(7, 3), Fr(-2)):
ests = [cuped(*d, theta).delta for d in enumerate_designs(y1, y0, x, 3)]
assert len(ests) == 20 and sum(ests) / 20 == tau
def test_estimated_theta_bias():
"""With theta estimated from the same data the estimate is not exactly unbiased, but under the sharp
null (Y(1) = Y(0)) the pooled theta does not depend on the assignment, so the mean is exactly 0."""
x = [Fr(v) for v in (0, 1, 2, 3, 4, 9)]
y0 = [Fr(v) for v in (1, 0, 4, 3, 7, 8)]
y1 = [Fr(v) for v in (1, 6, 4, 3, 7, 20)] # effects 0, 6, 0, 0, 0, 12: tau = 3
within = [cuped(*d, "within").delta for d in enumerate_designs(y1, y0, x, 3)]
assert sum(within) / 20 != 3
null = [cuped(*d, "pooled").delta for d in enumerate_designs(y0, y0, x, 3)]
assert sum(null) == 0
def test_variance_identity_exact():
"""With theta the pooled slope, the sample variance of y - theta x is var(y) (1 - r^2) exactly."""
rng = random.Random(3)
for _ in range(100):
n = rng.randint(3, 12)
x = [Fr(rng.randint(-9, 9)) for _ in range(n)]
y = [Fr(rng.randint(-9, 9)) for _ in range(n)]
mx, my = sum(x) / n, sum(y) / n
sxx = sum((a - mx) ** 2 for a in x)
syy = sum((b - my) ** 2 for b in y)
sxy = sum((a - mx) * (b - my) for a, b in zip(x, y))
if sxx == 0 or syy == 0:
continue
th = theta_pooled(y, x)
z = [b - th * a for a, b in zip(x, y)]
mz = sum(z) / n
szz = sum((c - mz) ** 2 for c in z)
assert szz == syy * (1 - sxy * sxy / (sxx * syy))
def test_monte_carlo_variance_reduction_and_coverage():
"""X ~ N(0, 1), Y = 2 + X + 0.75 noise, so rho^2 = 1/1.5625 = 0.64 and the variance factor is 0.36.
Effect 0.1, 500 units per arm, r = 400 replicates (seed 2026). Checks: the CUPED and naive estimates
are unbiased within 4 SE; the ratio of the Monte Carlo variances is within 0.36 +- 0.08 (the ratio of
two sample variances of 400 draws has relative SE about 0.07 each, and they are positively correlated);
the mean of the per-sample variance ratio is within 0.36 +- 0.01; the 95% interval covers in at least
0.92 of runs (4 SE below 0.95 is 0.906)."""
rng = random.Random(2026)
r, m, tau = 400, 500, 0.1
cu, nv, ratios, cover = [], [], [], 0
for _ in range(r):
def arm(eff):
xs = [rng.gauss(0, 1) for _ in range(m)]
return [2 + eff + v + 0.75 * rng.gauss(0, 1) for v in xs], xs
yt, xt = arm(tau)
yc, xc = arm(0.0)
res = cuped(yt, xt, yc, xc, "pooled")
cu.append(res.delta)
nv.append(res.naive_delta)
ratios.append(res.var / res.naive_var)
lo, hi = interval(res)
cover += lo <= tau <= hi
for est in (cu, nv):
assert abs(statistics.mean(est) - tau) < 4 * statistics.stdev(est) / math.sqrt(r)
assert abs(statistics.variance(cu) / statistics.variance(nv) - 0.36) < 0.08
assert abs(statistics.mean(ratios) - 0.36) < 0.01
assert cover / r >= 0.92
def test_input_checks():
with pytest.raises(ValueError):
cuped([1, 2], [1], [1, 2], [1, 2])
with pytest.raises(ValueError):
cuped([1], [1], [1, 2], [1, 2])
with pytest.raises(ValueError):
cuped([1, 2], [5, 5], [3, 4], [5, 5], "pooled")
History
Analysis of covariance, the regression of an experiment's outcome on the treatment and a covariate measured beforehand, is part of classical experimental design and goes back to Fisher. The control variates method of Monte Carlo integration subtracts a correlated quantity with known mean in the same way. Deng, Xu, Kohavi and Walker (2013) brought the idea to online controlled experiments at Microsoft Bing, with the same metric over the pre-experiment period as the covariate, and named it CUPED; it became standard in the experimentation platforms of large web companies. Freedman (2008) had criticized regression adjustment of experiments for its finite sample bias and possible loss of precision, and Lin (2013) answered that the adjustment with treatment by covariate interactions and robust standard errors is safe in large samples.
References
- Alex Deng, Ya Xu, Ron Kohavi and Toby Walker, Improving the sensitivity of online controlled experiments by utilizing pre-experiment data, Proceedings of the Sixth ACM International Conference on Web Search and Data Mining (WSDM), 2013, pp. 123 to 132 (the control variates estimator, the optimal theta and the factor 1 - rho^2)
- Winston Lin, Agnostic notes on regression adjustments to experimental data, reexamining Freedman's critique, The Annals of Applied Statistics 7(1), 2013, pp. 295 to 318 (regression adjustment with treatment by covariate interactions cannot hurt asymptotic precision, and the sandwich variance is valid)
- David A. Freedman, On regression adjustments to experimental data, Advances in Applied Mathematics 40(2), 2008, pp. 180 to 193 (under randomization, ANCOVA has a bias of order 1/n and can lose precision when arm sizes differ)
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag Y9J2V9 Edit this page History Report an error Markdown