19Randomized by city, analyzed by user: clustered standard errors (NumPy)
19 Randomized by city, analyzed by user: clustered standard errors (NumPy)
A prep site lists Netflix data science onsite questions on interference, clustering and choosing the randomization unit (nfx-057, nfx-058, guide only). Anthropic's own eval guidance recommends clustered standard errors on the unit of randomization (1 source). Same math.
An experiment assigned whole cities to treatment or control, then logged a metric per user. y holds each
user's metric, treat is 1 for treated users, and cluster holds each user's city id. Write in solution.py,
for the regression y ~ 1 + treat:
Set a 45-minute timer. Read one level at a time, and run only that level's tests until they pass:
pytest problems/19_cluster_randomized -k level1. Earlier levels must keep passing.
Level 1. diff_in_means(y, treat), the treatment effect estimate, and naive_se(y, treat), the ordinary OLS
standard error of that estimate, which treats every user as independent.
Level 2. cluster_se(y, treat, cluster): the cluster-robust standard error, clustered on city, with the usual
small-sample correction G / (G - 1) * (N - 1) / (N - K) (what statsmodels does by default).
Level 3. city_means_test(y, treat, cluster): collapse each city to its mean and run an ordinary two-sample
t-test on the means. Return (estimate, se, df): the estimate is the mean of the treated cities' means minus the
mean of the control cities' means, so each city counts once even when cities differ in size. Use the pooled
(equal-variance) standard error of the means, which differs from Welch's when the arms have different numbers of
cities, and df = G - 2. Every user in a city has the same treat.
Level 4. cities_per_arm(effect_sd, m, icc, alpha=0.05, power=0.8): the cities each arm needs to detect an
effect of effect_sd standard deviations with a two-sided test at any alpha and power, with m users per city
and an intra-cluster correlation icc. Size it for independent users, multiply by the design effect, divide by m,
and round up once, at the end (don't round the user count first). Return an int.
Things to get right: why users in one city aren't independent, the sandwich formula, what the design effect
1 + (m - 1) * ICC predicts, and what changes when there are few clusters (wild cluster bootstrap, or analyze
city-level means). Follow-ups: switchback tests, marketplace interference (Airbnb and Netflix both have it), and
choosing the unit before the test starts.
The expected values in the level 1 and 2 tests come from statsmodels on the same data.