09CUPED: cut the variance of an experiment metric (NumPy)

mediumnumpy
40:00

09 CUPED: cut the variance of an experiment metric (NumPy)

CUPED comes from a 2013 Microsoft paper, which reported cutting a metric's variance by about 50% on Bing with data from before each test. An interviewer asks for it in this order: the adjustment, the test on the adjusted metric, users with no history, and one theta per arm.

Set a 40-minute timer. Read one level at a time, and run only that level's tests until they pass: pytest problems/09_cuped -k level1. Earlier levels must keep passing.

Level 1. cuped(y, x): y is each user's metric during the experiment, x the same user's value of a pre-experiment covariate, often the same metric in the weeks before. Return (y_adjusted, theta), where y_adjusted keeps the mean of y and has the smallest variance any adjustment y - theta * (x - mean(x)) can give.

Level 2. cuped_effect(y, x, t), where t is True for treated users. Adjust every user in one call, then return the difference in adjusted means, treatment minus control, and its standard error: each arm's sample variance (ddof 1) over its users, added, under one square root.

Level 3. Some users have no pre-period, so their x is NaN. Keep them. Fill their x with 0, add a has-history flag as a second covariate, and fit both coefficients by least squares on the centered covariates. theta is still the coefficient on x.

Level 4. lin_effect(y, x, t): one theta per arm, fitted inside that arm, with each arm's head start measured from the pooled mean of x. That's Lin's estimator, the coefficient on the treatment flag in the regression with the treatment-by-covariate interaction. Return that one number, treatment minus control (every user here has a pre-period).

Things to get right: the theta that minimizes the variance and why it's the regression slope, centering x so the mean (and so the treatment effect) doesn't move, using the same degrees of freedom in the covariance and the variance, and the variance falling by a factor of 1 - corr(x, y)^2. Follow-ups: why the covariate must be measured before the experiment starts, and the link to regression adjustment (ANCOVA).

solution.py
Run the tests to see which pass.