A prep site lists a Netflix data science onsite question on a frequency-cap test that asks you to "provide power calculations that account for interference and clustering" (1 source), and a candidate's report of a Netflix onsite says both technical cases were about ad frequency caps (1 report). When eval questions come in related groups, like several questions about one reading passage, Anthropic recommends "clustering standard errors on the unit of randomization" (1 source). The frequency-cap question and the eval guidance use the same math. Our version of the practice reads like this:
An experiment assigned 40 whole cities to treatment or control, 20 each, then logged a metric for each of their 2,000 users. Estimate the effect, and give a standard error you'd defend. Then tell me how many cities the next test needs.
The practice comes in four levels. Level 1 writes diff_in_means and naive_se, the standard error that treats every user as independent. Level 2 writes cluster_se, clustered on city. Level 3 writes city_means_test, a t-test on one mean per city. Level 4 writes cities_per_arm, the next test's size in cities.
You don't write them yet. The lesson shows why users in one city aren't independent, measures how far that fools the naive standard error, builds the clustered one, and handles the case of few cities. At the end you solve the whole problem, level by level, in an interview simulation with a 45-minute timer.
This lesson builds on the A/B test lesson's comparison of two arms, and on the sample-size lesson's design effect. The difference-in-differences lesson comes next, for changes you can't randomize at all.
Some changes switch on for a whole city at once
Start with the two units the practice data mixes.
Predict
40 cities each flip a coin, and 2,000 users get analyzed. How many independent units of randomization are there?
The practice data
How many
Unit
Randomized
40 cities, 20 of them treated
one coin flip per city, copied to its users
Analyzed
2,000 rows
one per user, 50 per city
A new delivery fee, a pricing rule, a city-wide promotion: you can't give these to one user and skip the user next door. So the experiment flips a coin for each city. Then it logs a metric for every user in that city.
The unit of randomization is what the coin flip assigns: here, the city. The unit of analysis is one row of your table: here, the user.
When those two differ, the usual standard error, the one that treats every user as independent, is wrong, usually by a lot. This lesson is about getting it right.
Pick an answer above to see the rest
The estimate is a difference in means, and clustering never changes it
The practice fits the regression y ~ 1 + treat. That's formula notation: it predicts y from an intercept, the 1, and the treatment flag, 0 or 1. The fit is ordinary least squares, OLS: the line with the smallest sum of squared misses.
With a 0 or 1 flag, that line passes through the two arms' means. So its slope on treat is the treated mean minus the control mean.
The estimate is the easy part, and clustering never changes it. Everything after this step is about its standard error.
In the editor, write diff_in_means(y, treat) from the two arms' means. y6 holds six small cities that the lesson comes back to.
Users in one city share a shock, so they aren't independent
Here are those six cities, four users each.
Predict
Users in one city sit near their city's level. Is a second user from the same city new, independent evidence?
Six cities of four users
A, control
B, control
C, control
D, treated
E, treated
F, treated
02468101214
control usertreated userthe city's mean
Cities A, B and C are the control arm, and D, E and F are treated. Every user sits 1 or 2 away from their city's mean. The city means sit 3 apart.
So one user's value tells you about the others in the same city. A user in city A scored 1, so the next user in A probably scored low too. That's what it means for users not to be independent.
The worked example near the end runs every method on these six cities.
Pick an answer above to see the rest
Each user's metric is a city shock plus the user's own noise
The practice data is built from that same picture.
import numpy as npdef practice_data(seed, city_sd): rng = np.random.default_rng(seed) cluster = np.repeat(np.arange(40), 50) treat = rng.permutation(np.r_[np.ones(20), np.zeros(20)])[cluster] shock = rng.normal(0, city_sd, 40)[cluster] y = 10 + 0.5 * treat + shock + rng.normal(0, 2, 2000) return y, treat, clustery, treat, cluster = practice_data(0, 1.5)means = np.array([y[cluster == g].mean() for g in range(40)])inside = np.array([y[cluster == g].std() for g in range(40)])print(f"users inside one city spread by {inside.mean():.2f}")print(f"the 40 city means spread by {means.std():.2f}")
users inside one city spread by 1.97the 40 city means spread by 1.39
This is how the practice data is made. cluster holds each user's city id, 0 to 39, fifty users each. rng.normal(0, city_sd, 40) draws one shock per city, and indexing with [cluster] copies it to the city's 50 users. The coin flips are copied the same way.
The spread here is the standard deviation. Users inside a city spread by about 2, their own noise. If users were independent, a mean of 50 of them would spread by only 2/50=0.28. The city means spread by 1.39. Most of that is the city shock, which every user in the city shares.
In symbols:
yig=μ+τtg+bg+eig
In words: user i in city g gets the base level μ (10 in the code), plus the effect τ (0.5) when the city's flag tg is 1, plus the city's shock bg, plus the user's own noise eig. The shocks have variance σb2, 1.5 squared in the code, and the users' own noise has variance σw2, 2 squared. There are G cities of m users, so N=Gm users in all.
Averaging more users shrinks their own noise, never the city's shock
So how much can averaging a city's users help?
Predict
A city's mean has shock variance 2.25 plus user noise 4 / m. Average 50 users. About what's left?
The variance of one city's mean
0246
m = 1 user: 6.25
2.25
4
m = 4: 3.25
2.25
1
m = 10: 2.65
2.25
0.4
m = 50: 2.33
2.25
the city shock, 2.25the users' own noise, 4 / m
A city's mean is its shock plus the average of its m users' own noise. That average has variance σw2/m, so it shrinks as the city grows. The shock doesn't shrink at all, because every user in the city carries the same bg.
So the difference in means carries the average shock of the treated cities minus the average shock of the control cities. Only more cities can average that away. More users per city can't.
That's why randomizing cities changes the standard error. The noise that moves the estimate comes in city-sized pieces, and the practice data has only 40 of them.
In the editor, write city_mean_variance(city_sd, user_sd, m): the variance of one city's mean.
The naive standard error counts every user as independent evidence
Now the standard error the usual formula gives.
def fit(y, treat): X = np.column_stack([np.ones(len(y)), treat]) XtX_inv = np.linalg.inv(X.T @ X) beta = XtX_inv @ X.T @ y return X, XtX_inv, beta, y - X @ betadef diff_in_means(y, treat): return fit(y, treat)[2][1]def naive_se(y, treat): X, XtX_inv, _, resid = fit(y, treat) n, k = X.shape s2 = resid @ resid / (n - k) return np.sqrt(s2 * XtX_inv[1, 1])b, se = diff_in_means(y, treat), naive_se(y, treat)print(f"estimate {b:.3f} naive SE {se:.3f}")print(f"naive 95% interval: {b - 1.96 * se:.2f} to {b + 1.96 * se:.2f}")
Predict
The practice data was built with a true effect of 0.5. Does the naive 95% interval cover it?
Pick one to see what it prints.
X is the design matrix: one row per user, holding a 1 for the intercept and the user's treatment flag. beta solves the normal equations, β^=(X⊤X)−1X⊤y, which give the least-squares fit. beta[0] is the control mean, and beta[1] the difference in means. fit also returns the residuals, y - X @ beta.
naive_se is this formula:
SEnaive=s2(NT1+NC1),s2=N−K∑ie^i2
In words: e^i is user i's residual, its value minus its arm's mean. NT and NC count the users in each arm. K=2 counts the fitted coefficients, the intercept and the treatment effect. In the code, the treatment's diagonal entry of (X⊤X)−1, XtX_inv[1, 1], is exactly 1/NT+1/NC.
The formula assumes N independent draws. So it counts a city's 50 copies of bg as 50 pieces of evidence.
Pick an answer above to see the rest
On the practice data, the naive interval misses the true effect
On the practice data, that formula gives a confident, wrong answer.
The practice data, two 95% intervals around the estimate
true effect 0.5
naive-0.37 to 0.06
clustered-1.06 to 0.75
-1-0.500.51
The practice data was built with a true effect of 0.5. Its treated cities happened to draw shocks 0.61 lower than the control cities on average, so the estimate came out at -0.155.
The naive interval, -0.37 to 0.06, is narrow and confident, and it misses 0.5. The clustered standard error is 0.446, four times the naive 0.108. Its interval, -1.06 to 0.75, covers the truth. It uses a cutoff of 2.023 instead of 1.96, for a reason Part 4, Few cities, explains.
One data set could be bad luck, so a later step runs this design with no true effect at all. A 5% test built on the naive standard error calls about two of every three runs significant.
In the editor, write naive_se(y, treat) from the formula, with no matrices.
CheckpointThe standard error that ignores cities
Write naive_se(y, treat) from the formula, with no matrices: residuals from each arm's own mean, s2 as their sum of squares over N−K with K=2, then s2(1/NT+1/NC). treat is 1 for treated users and 0 for the rest.
Part 1 done
Part 2 of 6about 19 min
The design effect
The ICC is the share of the variance that comes from the city
How far the naive standard error falls short depends on one number about the cities.
Predict
City shocks have variance 2.25 and user noise 4.00. What share of a user's variance comes from the city?
One user's variance in the practice data, 6.25 in all
02.256.25
the ICC is 2.25 / 6.25 = 0.36
2.25
4.00
city shockuser noise
Each user's metric varies for two reasons: the city's shock and the user's own noise. In the practice data, 2.25 of the 6.25 comes from the city. That share is the intraclass correlation, the ICC, written ρ:
ρ=σb2+σw2σb2=6.252.25=0.36
It's also the correlation between two users in the same city. They share bg and nothing else, so their covariance is σb2, and their correlation is σb2 over the total.
In the editor, write icc(city_sd, user_sd): the practice data's ICC from its two spreads.
With equal city sizes, the design effect is 1 + (m - 1) × ICC
The ICC turns into a factor on the variance.
Predict
Equal cities of 50 users and an ICC of 0.36. The design effect is 1 + (m - 1) × ICC. About how big?
Take one arm's mean. With m users in each city and GT treated cities, it's the average of GT city means. Each city mean has variance σb2+σw2/m: the shock, plus the user noise shrunk by averaging, as the city_mean_variance task found. So:
The second line rearranges the first. Its first factor is the variance that NT=GTm independent users would give. The second factor is the design effect, DEFF: how many times bigger the true variance is.
DEFF=1+(m−1)ρNeff=DEFFN
In words: m−1 counts the other users who share each user's city. Neff, the effective sample size, is how many independent users your N users are worth.
Treat the users as independent and you understate the variance by a factor of about DEFF, and the standard error by about DEFF.
The formula holds exactly under these conditions:
every city has the same number of users, m
the treatment is the same for every user in a city, as it is when you randomize cities
different cities' shocks are independent, and so is each user's own noise
both arms have the same ICC.
The practice data meets all four, with ρ=0.36 and m=50. So DEFF=1+49×0.36=18.64. That predicts a clustered standard error 18.64=4.3 times the naive one, and 2,000 users worth about 107 independent ones.
The data shows 4.1 times, 0.446 against 0.108. The formula gives the expected ratio. A clustered standard error from 40 cities is itself an estimate: the true standard deviation of this design's estimate is 0.48, and this data set's clustered estimate lands a little low.
In the editor, write design_effect(city_sd, user_sd, m): the ICC from the two spreads, then the design effect.
CheckpointThe design effect from two spreads
Write design_effect(city_sd, user_sd, m): the ICC from the standard deviation of the city shocks and of each user's own noise, then 1+(m−1)ρ for cities of m users. The practice data's standard deviations are 1.5 and 2, in cities of 50.
Pick an answer above to see the rest
A tiny ICC in a big city is still a big design effect
The design effect grows with the city size, so even a small ICC adds up.
ICC 0.01: the design effect by users per city
10 users
1.09
100 users
1.99
1,000 users
10.99
The standard error grows with the square root: 1.04, 1.41 and 3.32 times the naive one.
An ICC of 0.01 sounds like nothing. But the design effect multiplies it by the number of other users in the city. In cities of 1,000 users, 1+999×0.01=10.99, and the naive standard error is 3.3 times too small.
Cameron and Miller retell Moulton's classic example: an error correlation of 0.032 within states, about 387 people per state, and a regressor that's the same for everyone in a state. That's 1+0.032×386≈13.4, so the default standard errors were about 3.7 times too small.
Their one-line summary of the problem: "In such settings, default standard errors can greatly overstate estimator precision."
A city is worth at most 1 / ICC independent users
Turn the design effect around, and it says what one city is worth.
Predict
At an ICC of 0.36, one city of 50 users is worth about how many independent users?
ICC 0.36: one city is worth this many independent users
1 user
1.00
10 users
2.36
50 users
2.68
200 users
2.75
1,000 users
2.77
Never past 1 / 0.36 = 2.78, however many users a city holds.
Each city carries m/DEFF users' worth of information. As m grows, that climbs toward 1/ρ and never passes it.
At ρ=0.36, a city of 50 is worth 2.7 independent users, and no city of any size is worth more than 2.8. The first ten users of a city buy most of what a city can give.
In the editor, write effective_users(m, icc): one city's worth in independent users.
Real cities aren't all one size, and that costs more.
Predict
Same average city size, but the sizes are unequal. Is the design effect bigger or smaller than with equal sizes?
With cities of different sizes, replace m with mˉ(1+CV2). Here mˉ is the mean city size, and CV, the coefficient of variation, is the city sizes' standard deviation over their mean. Cameron and Miller give the same correction in another form.
With 40 cities of 10 to 190 users and ρ=0.05, simulation gives a design effect of 7.1. The corrected formula gives 7.2, and the mean size alone 5.3.
In the editor, write design_effect_unequal(sizes, icc): the design effect with the size correction.
The cluster-robust standard error adds up inside each city, then squares
Here's the fix the design effect points to, as code.
def cluster_se(y, treat, cluster): X, XtX_inv, _, resid = fit(y, treat) n, k = X.shape groups = np.unique(cluster) G = len(groups) meat = np.zeros((k, k)) for g in groups: # sum in the city s = X[cluster == g].T @ resid[cluster == g] # then square meat += np.outer(s, s) V = XtX_inv @ meat @ XtX_inv # small-sample fix V *= G / (G - 1) * (n - 1) / (n - k) return np.sqrt(V[1, 1])for seed, city_sd in [(0, 1.5), (1, 0.0)]: yy, tt, cc = practice_data(seed, city_sd) print(f"city shocks sd {city_sd}: naive {naive_se(yy, tt):.4f}" f" clustered {cluster_se(yy, tt, cc):.4f}")
Predict
With city shocks of sd 1.5, the clustered SE is about 4 times the naive one. With no city shocks, sd 0, how do they compare?
Pick one to see what it prints.
With city shocks, the clustered standard error is four times the naive one. Without them it's within 5% of it: when cities don't differ, clustering costs almost nothing. The line marked small-sample fix gets its own step in Part 4, Few cities.
The code is a sandwich. Every OLS variance has this shape:
Var(β^)=(X⊤X)−1X⊤ΩX(X⊤X)−1
In words: Ω is the covariance of the errors, how each user's error moves with every other user's. The naive formula assumes Ω=σ2I: every user has the same variance, and no two users move together. Then the middle collapses to σ2X⊤X, and the whole thing to σ2(X⊤X)−1.
The cluster-robust version assumes only that errors in different cities are independent. Inside a city they can be correlated in any pattern. It estimates the middle from the residuals, one city at a time:
V^=(X⊤X)−1M^(X⊤X)−1,M^=g=1∑GXg⊤e^ge^g⊤Xg
In words: (X⊤X)−1 on each side is the bread, and M^ in the middle is the meat. Xg and e^g are city g's rows of X and its residuals. Xg⊤e^g is city g's score, s in the code: its users' rows of X, each weighted by its residual, added up. It has K=2 entries, so np.outer(s, s) is 2 by 2.
Pick an answer above to see the rest
Adding up inside the city before squaring keeps the pairs that share a city
The loop's one important move is the order: add, then square.
Predict
City A's residuals are -5, -2, -4 and -1. Their total squared is 144, and the diagonal, each user alone, adds up to 46. What do the other 12 cells hold?
×
-5
-2
-4
-1
-5
25
10
20
5
-2
10
4
8
2
-4
20
8
16
4
-1
5
2
4
1
City A
Adds up to
the diagonal, each user alone
25 + 4 + 16 + 1 = 46
the whole grid, the total squared
(-12) × (-12) = 144
the other 12 cells, the pairs in A
144 - 46 = 98
City A is from the six cities. Its users' values are 1, 4, 2 and 5, and the control arm's mean is 6, so its residuals are -5, -2, -4 and -1.
Square a sum and you get every product of two of its terms. The diagonal is what you'd get by squaring each user alone. The other 12 cells are the pairs of users who share city A. They're all positive because A's users all sit below their arm's mean together.
That's the whole trick, and the order is what matters. Add up inside the city, then square. Squaring the sum keeps every cross-product e^ie^j between two users of the same city. That's exactly the within-city correlation the naive formula throws away.
Pairs from different cities never meet:
A sketch, 3 cities of 2 users: the pairs each estimator adds up
naive and robust: each user alone
clustered: every pair inside one city
Rows and columns are users, in city order. The clustered estimator adds up every marked cell.
Each grid has one row and one column per user. A ■ is a pair whose product enters the estimate. Each 2 by 2 block on the clustered grid's diagonal is one city, like city A's 4 by 4 grid above, only smaller. The cells outside the blocks, pairs from different cities, are left out, because different cities are assumed independent.
In the editor, write sum_then_square(cities) and square_then_sum(cities): the two ways to add up residuals.
For a 0/1 treatment, each city counts through its residual total
With a 0 or 1 treatment, the sandwich has a short closed form.
Predict
Cities B and E have a residual total of 0. What do they add to the clustered variance?
City
Arm
Residual total, Eg
A
control
-12
B
control
0
C
control
+12
D
treated
-12
E
treated
0
F
treated
+12
For a treatment that's 0 or 1, the treatment's entry of V^ works out to:
V^τ=g∈T∑NT2Eg2+g∈C∑NC2Eg2,Eg=i∈g∑e^i
In words: Eg is city g's residual total. It equals the city's user count times how far its mean sits from its arm's mean. Each treated city adds its total squared over NT2, the treated users squared, and each control city the same over NC2.
On the six cities, A, C, D and F each square to 144, and B and E add nothing. So V^=(144+144)/122+(144+144)/122=4, a standard error of 2.0 before the correction.
So the clustered variance is driven by how far whole cities sit from their arm's mean. That's exactly the city-shock noise that moves the estimate.
In the editor, write cr0_se(y, treat, cluster) from the closed form, each city through its residual total.
CheckpointSum inside the city, then square
Write cr0_se(y, treat, cluster), the clustered standard error before the small-sample correction, from the closed form: each city's residual total Eg, then the square root of ∑g∈TEg2/NT2+∑g∈CEg2/NC2. residuals, the first step of your naive_se, is in the editor.
Pick an answer above to see the rest
On a design with no true effect, count how often each test finds one
Check the clustered standard error the way you'd check any function: simulate it.
No true effect at all, 40 cities of 50 users. How often does the naive 5% test call the result significant?
Pick one to see what it prints.
This runs the practice design 2,000 times with no effect at all. 2.023 is the cutoff of a t distribution with 39 degrees of freedom, which Part 4, Few cities, explains.
The naive test finds an effect in 65% of the runs. A longer run of 20,000 gives 65.6%: two times in three, it reports an effect that doesn't exist. The clustered test finds one about 5% of the time, which is what a 5% test is supposed to do.
Pick an answer above to see the rest
Part 3 done
Part 4 of 6about 20 min
Few cities
The small-sample correction raises the standard error, more with fewer cities
On the six cities, the sandwich alone gives 2.0, and cluster_se gives 2.240. The gap is one factor on the variance:
c=G−1G⋅N−KN−1
In words: the number of cities over one less than that, times the number of users minus 1 over the number of users minus the K coefficients.
Here's why it's needed. Residuals are fitted, so they sit closer to zero than the true errors do. OLS already corrects for that by dividing by N−K instead of N. The cluster-robust estimator has the same bias at the city level, because its meat is built from only G city scores.
Cameron and Miller give this factor and note that Stata uses it. The practice tests' expected values come from statsmodels, which applies it by default.
On the six cities, c=56⋅2223=1.2545. The standard error grows by c=1.12, from 2.0 to 2.240.
On the practice data, c=1.026. The standard error grows by c=1.013, from 0.4403 to 0.4460.
It shrinks the downward bias. It doesn't remove it, which is why the rest of this part exists.
In the editor, write correction(G, N, K=2): the factor, for the six cities and for the practice data.
The correction's extra percent roughly doubles each time the cities halve
How much the correction matters depends on how many cities you have.
Cities G, 50 users each
c
Standard error grows by
100
1.005
0.5%
40
1.013
1.3%
20
1.026
2.6%
10
1.055
5.5%
6
1.097
9.7%
4
1.158
15.8%
The second factor, (N−1)/(N−K), is close to 1 whenever N is large. The first one, G/(G−1), is the one that matters, and it matters most when cities are few.
In the editor, finish cluster_se(y, treat, cluster): cr0_se, corrected by the factor c.
CheckpointThe small-sample correction
Finish cluster_se(y, treat, cluster): cr0_se from the earlier task, corrected by the factor c=G−1G⋅N−KN−1 on the variance, with G counted from the city ids and K=2. That's the number statsmodels reports.
With few cities, use t with G - 1 degrees of freedom, and it still runs hot
The correction fixes the standard error. The cutoff needs fixing too.
A t distribution has fatter tails, so its 5% cutoff sits past 1.96
Predict
Six cities give a t test 5 degrees of freedom. Where does its two-sided 5% cutoff sit?
The cutoff a two-sided 5% test uses
normal
1.960
t, 39 df
2.023
t, 19 df
2.093
t, 9 df
2.262
t, 5 df
2.571
t, 3 df
3.182
The clustered standard error is built from G city scores. With few cities it's a noisy estimate of the true one. So the ratio τ^/SE swings wider than a draw from the normal curve.
A t distribution describes that swing: a bell like the normal, with fatter tails. Its one setting is the degrees of freedom, df. The fewer of them, the fatter the tails and the further out the cutoff. These cutoffs match any t table.
The standard fix compares the clustered t statistic to a t distribution with G−1 degrees of freedom, not to 1.96. Cameron and Miller treat the correction plus G−1 degrees of freedom as the minimum. They warn that tests still over-reject with few clusters: they find effects that aren't there more often than they promise.
Pick an answer above to see the rest
With equal cities, equal arms and normal noise, even the corrected test runs hot below about 20 cities
Even with the correction and the t cutoff, few cities cost you.
Cities G
CR0 vs 1.96
CR1 vs 1.96
CR1 vs t
City means vs t
4
30.0%
25.0%
12.1%
5.0%
6
18.5%
15.4%
8.3%
5.0%
10
11.8%
10.2%
6.5%
5.0%
20
7.9%
7.2%
5.6%
5.0%
40
6.4%
6.0%
5.3%
5.0%
100
5.5%
5.4%
5.1%
5.0%
Each entry is how often a 5% test rejects when there's no effect. Half the cities are treated, every city has 50 users, and the noise is normal.
CR0 is the uncorrected sandwich. CR1 is the corrected one, the one cluster_se returns.
The 1.96 columns compare the t statistic to the normal curve's cutoff.
The t columns compare it to a t distribution: G−1 degrees of freedom for CR1, and G−2 for the city means.
Under those conditions:
Every clustered t statistic in the table is a fixed multiple of the city-means t statistic from a later step.
The city-means t statistic has an exact t distribution, so these rates are exact.
The ICC drops out.
The city size enters only through (N−1)/(N−K). At 50 users or more, it moves no entry by more than a tenth of a point.
A 200,000-run simulation of each row lands within about a tenth of a point of every entry.
At 40 cities, the correction and G−1 degrees of freedom get you close. Below about 20, even both together run hot.
What counts is the number of cities in the smaller arm
Unequal arms make it worse.
Predict
20 cities are treated and 3 are in control. Which count decides how few cities you have?
With 40 cities but only 3 of them treated, CR1 with 39 degrees of freedom rejects a true null 19% of the time in simulation (100,000 runs). With 2 treated, it's 31%. The city-means test holds 5% in both.
Most of the variance rests on just the 3 treated city totals. Fitting the treated mean pulls those totals toward zero, so on average they show about two thirds of the true spread. A correction sized for 40 cities adds 2.6% and does not make up for it.
Pick an answer above to see the rest
The wild cluster bootstrap resamples by flipping whole cities
One fix for few cities is a bootstrap that respects them.
Predict
The wild cluster bootstrap builds new data sets by flipping what?
When you need the regression, for covariates or very unequal cities, the standard tool for few clusters is the wild cluster bootstrap:
Refit the model with the null imposed, so the treatment effect is zero.
Flip the sign of each whole city's residuals at random.
Rebuild the data from those residuals, refit, and keep the t statistic.
Repeat many times, and read the p-value off where your real t statistic falls among them.
In this lesson's simulations it beat CR1 with G−1 degrees of freedom at 6 and 10 cities, though only the city-means test was exact.
Pick an answer above to see the rest
Or analyze at the level you randomized: one mean per city
The other fix skips the sandwich altogether.
Predict
Why is an ordinary t-test on the city means valid?
est, se, df = city_means_test(y, treat, cluster)print(f"estimate {est:.3f} SE {se:.3f} {df} degrees of freedom")
estimate -0.155 SE 0.452 38 degrees of freedom
The simplest valid analysis collapses each city to one number, its mean. Then it runs an ordinary two-sample t-test on the G means, with G−2 degrees of freedom. The unit of analysis becomes the unit of randomization, and the problem is gone.
The city means are independent of each other. With equal city sizes and normal noise, this test is exact at any number of cities: the city-means column of the few-cities table held 5.0% at every row.
On the practice data it gives the same estimate, -0.155, and a standard error of 0.452, against the clustered 0.446.
In the editor, write city_means_test(y, treat, cluster): one mean per city, then an ordinary t-test.
With equal city sizes and equal arms, the clustered standard error is a fixed multiple of this one
That 0.446 against 0.452 is no coincidence. With equal city sizes and equal arms:
SEcity meansSEclustered=G−1G−2⋅N−KN−1
In words: the clustered standard error is the city-means one times a factor just under 1. At 40 cities and 2,000 users the factor is 0.987.
So the sandwich is the city-means t-test in disguise. It has a slightly smaller standard error, and a slightly smaller cutoff, with G−1 degrees of freedom instead of G−2. Those two small gaps are where its extra false positives with few cities come from.
In the editor, write sandwich_factor(G, N, K=2): the factor between the two standard errors.
With unequal city sizes, the plain average of city means answers a per-city question
With unequal city sizes, the plain average of city means weights a town of 50 users the same as a city of 50,000. So it estimates the average effect per city, not per user. If the effect varies with city size, those are different numbers.
Weighting the means by city size gets the per-user estimate back. But then the simple t-test isn't exact anymore.
Part 4 done
Part 5 of 6about 12 min
The worked example
A worked example
Run every method on the six cities from the start.
Six cities of four users, with their residuals and city totals
City
Users
Mean
Residuals
Eg
A
1, 4, 2, 5
3
-5, -2, -4, -1
-12
B
8, 4, 7, 5
6
2, -2, 1, -1
0
C
7, 10, 11, 8
9
1, 4, 5, 2
12
D
5, 8, 4, 7
6
-4, -1, -5, -2
-12
E
10, 7, 11, 8
9
1, -2, 2, -1
0
F
14, 10, 13, 11
12
5, 1, 4, 2
12
These are the six cities from the start: A, B and C are control, and D, E and F are treated. The residuals are each user's value minus their arm's mean, 6 for control and 9 for treated. Eg is their total. The estimate is 9−6=3.
estimate 3.000naive SE 1.243clustered 2.240city means 2.449
Predict
Six cities: the naive test gives p = 0.025. What do you expect from the clustered test?
By hand: the naive test says p = 0.025, the clustered test 0.24 and the city means 0.29
Naive. The squared residuals add up to 204. 60 of it comes from users around their own city's mean. 144 comes from four city means that sit 3 away from their arm's mean: 4 users times 9, in each of those four cities. So s2=204/22=9.27, and
SEnaive=9.27(121+121)=1.243
t=3/1.243=2.41. With 22 degrees of freedom the cutoff is 2.074, so p=0.025, and the 95% interval runs from 0.42 to 5.58. Ship it?
Clustered. Only cities A, C, D and F have a nonzero residual total, and each one squares to 122=144:
V^CR0=122144+144+122144+144=4
The correction is c=56⋅2223=1.2545, so SE=4×1.2545=2.240, and t drops to 1.34. With G−1=5 degrees of freedom the cutoff is 2.571. So p is 0.24, and the interval runs from -2.76 to 8.76.
City means. The treated means are 6, 9 and 12, and the control means 3, 6 and 9. Each arm has variance 9. So SE=9/3+9/3=2.449 and t=1.22. With 4 degrees of freedom the cutoff is 2.776, so p=0.29, and the interval runs from -3.80 to 9.80.
The six cities, three 95% intervals around the estimate, 3
0
naive0.42 to 5.58
clustered-2.76 to 8.76
city means-3.80 to 9.80
-4-20246810
Only the naive interval leaves out 0.
Same data, opposite conclusions: report the city means
The clustered standard error is 1.80 times the naive one, 2.240 against 1.243. That's a design effect of 3.25 in this sample. So the 24 users carry about as much information as 7 independent ones.
The formula agrees. The between-city variance is about 8.17 and the within-city variance 3.33, an ICC of 0.71, and 1+3×0.71=3.13.
Six cities is where the table says even the corrected sandwich runs hot, 8.3% at a nominal 5%. So the city-means test is the one to report.
Pick an answer above to see the rest
Power: count cities, not users
Power runs the same math backwards:
Garm=mniid(1+(m−1)ρ)
In words: niid is the users per arm you'd need if users were independent. Times the design effect, it's the users you need. Divided by m, the users per city, it's the cities you need in each arm.
Say you want to detect a lift of 0.1 standard deviations, at 5% two-sided, with 80% power. With independent users that's niid=2(1.96+0.84)2/0.12, about 1,570 per arm. Here 1.96 is the two-sided 5% cutoff, and 0.84 the point with 80% of the normal curve below it. The sample-size lesson derives this.
With 50 users per city and ρ=0.05, the design effect is 3.45. So it takes 5,416 users, 109 cities per arm.
In the editor, write cities_per_arm(effect_sd, m, icc): the cities per arm for a given city size and ICC.
Bigger cities stop helping, because their shocks never average away
Bigger cities help less and less.
Predict
Independent users would need 1,570 per arm, and the ICC is 0.05. How many cities per arm do you need at least, however big the cities?
ICC 0.05, a lift of 0.1 SD: cities per arm by users per city
10 users
228
50 users
109
200 users
86
1,000 users
80
Never below the floor: 1,570 × 0.05 = 78.5 cities per arm.
As m grows, Garm falls toward niidρ, 78.5, so 79 cities per arm here, and never below it. Past a point, only more cities help.
Turn it around. With 20 cities per arm, the standard error in units of the metric's standard deviation is 0.083 at 50 users per city, and 0.071 at 1,000. That's twenty times the users for 14% less noise.
In the editor, write city_floor(effect_sd, icc): the fewest cities per arm any city size can give.
You randomize by city instead of by user. What do you trade?
The unit you randomize, from finest to coarsestInteractive
→
→
→
→
query. The most units and the most power
The unit is a design decision. Once the test has run, you can't re-randomize it. You can only analyze it at the level it was randomized. Two rules settle most cases:
Randomize at the smallest unit that contains the interference. If treated users can affect control users, they belong in the same unit.
Analyze at the unit you randomized, or cluster on it. A user-randomized test with a per-session metric clusters on the user, because one user's sessions move together. A city-randomized test clusters on the city.
A prep site lists a Netflix ranking-test question that asks you to "Choose among user-level, session-level, or query-level randomization." (1 source).
Finer units give you more units and more power. But a user who lands in both arms sees both rankings and carries what they learned in one into the other. And you can't read user-level outcomes like retention. Coarser units cost you the design effect. Say the tradeoff, pick one, and size the test in that unit.
Pick an answer above to see the rest
Interference: treated users can take supply from control users
Some changes leak from treated users to control users.
Predict
In a 50/50 test, treated riders get 20% more rides than control. Does the launch deliver 20% more rides?
100 cars give one ride each an hour, and riders ask for 200 rides:
Rides asked for
Rides given
before the test
200
100
the test, 50/50: treated half
120
54.5
the test, 50/50: control half
100
45.5
after the launch
240
100
Every A/B test quietly assumes SUTVA, the stable unit treatment value assumption. Its key part says one unit's outcome doesn't depend on which arm anyone else is in. A prep site lists a Netflix question about a feature with network effects that asks you to "Explain SUTVA and why it matters here." (1 source).
Marketplaces break it through shared supply. In the table, a feature makes treated riders ask for 20% more rides. The cars go out in proportion to requests, so treated riders get 54.5 rides and control riders 45.5. The test reports 20% more rides.
Launch to everyone, and requests rise to 240 while rides stay at 100. The real effect on rides is zero. The treatment didn't create rides, it took them from control. Cabify's switchback write-up calls this cannibalization.
An ad frequency-cap test can leak the same way. A campaign with budget left to spend can show control users the impressions the cap withheld from treatment users, so control changes too.
The fix is to randomize a unit that contains the interference, so treated users only compete with treated users. That unit is a cluster. So a design that handles interference has to handle clustering too, which is what the frequency-cap question asks for (1 source). The price is bias against variance: bigger units remove more interference and leave you fewer, noisier units.
Pick an answer above to see the rest
Switchback tests randomize time blocks instead of cities
When cities are too few, randomize time instead.
Predict
In a switchback test, what's one unit?
Hour
9
10
11
12
13
14
city 1
T
C
C
T
C
T
city 2
C
T
T
C
T
C
One unit is a city-hour, not the orders inside it.
When the whole market has to switch together and you have few markets, randomize time instead. A switchback test flips each city between treatment and control in time blocks, say an hour at a time. Every city-hour is a unit, and each city serves as its own control.
The analysis is this lesson's with a new cluster: the city-hour, not the order. Cabify's write-up puts it plainly: "Lastly, take into account that, in switchback experiments, each interval is one sample, so you need longer experiments to get significant results."
Two things to raise in an interview:
Carryover. A ride requested late in a treatment block can finish in the next control block. Longer blocks, or a washout period dropped after each switch, as Cabify does, keep one arm's effects out of the other's numbers.
Correlated blocks. Neighboring hours in a city share demand, so the blocks aren't fully independent either. Check that clustering on a coarser unit, such as the city-day, doesn't change your answer.
Watch · 15 min
A Shipt data scientist on switchback tests in a three-sided marketplace, from choosing the region and time blocks to powering and analyzing by those blocks rather than the orders inside them.
Experiment Rigor for the Design and Analysis of Switchback Experiments · Data Science Connect · Oct 2022YouTube
Pick an answer above to see the rest
Evals with related questions: cluster on the passage
An eval is an experiment too. Here a model answers 3 questions on each of 6 reading passages, scored 1 if right. When an eval asks several questions about each passage, the questions are the users and the passages are the cities. A model that misreads a passage misses several questions at once.
For one eval score, the sandwich has only an intercept. So each passage contributes its residual total, squared. np.bincount(ids, weights=w) adds up the weights that share each id: ids 0, 0, 1, 2, 2 with weights 1, 2, 5, -1, 4 give totals 3, 5 and 3. Give it the residuals as weights and it returns each passage's residual total. It needs the ids to be whole numbers, 0 or more. Neither standard error uses a small-sample correction, so the two compare fairly.
On these 18 answers, the clustered standard error is 1.45 times the naive one. Anthropic's guidance is to cluster on the unit of randomization, here the passage (1 source). In Evan Miller's paper behind that guidance, the clustered standard error on DROP, a reading-comprehension eval, came out 3.05 times the naive one. On the multilingual MGSM, where one question appears in many languages, it was 1.88 times. The paper's summary: "Analyzing the same data, clustered standard errors can be over 3X larger than naive standard errors."
To compare two models on the same questions, run it on the per-question score differences.
In the editor, write eval_ses(score, passage): the naive and the clustered standard error of an eval score.
That's every piece of the practice problem, and the follow-ups after it. The simulation asks for all five functions under a timer, so rehearse the order once.
Check yourself
5 questions
1.Cities of 1,000 users each, randomized by city, and the ICC is only 0.01. How far off is the naive standard error?
2.On the practice data with city effects, you swap the naive standard error for a heteroskedasticity-robust one. What happens?
3.With 40 cities and 2,000 users, what does the factor G/(G - 1) × (N - 1)/(N - K) do to the clustered standard error?
4.Your naive_se divides the residual sum of squares by N instead of N - K. Why is N - K right?
5.Six cities of equal size, three of them treated. Which test keeps its false positive rate at 5%?
Where this shows up
The reports behind this lesson, each with its source.
A prep site lists a Netflix DS onsite question (posted 2025-10-13): design and power a frequency-cap experiment that accounts for interference and clustering.
Prep site·PracHub (prep site question bank)·2025-10-13Source
When eval questions come in related groups, Anthropic recommends clustered standard errors on the unit of randomization.
“we recommend clustering standard errors on the unit of randomization”
Company source·Anthropic research (Alignment)·2024-11-19Source
Data scientist onsite (Oct 2025 report): both technical cases were about ad frequency caps.
Candidate report·PracHub (first-person report, curated and edited by the site)·2026-08-25Source
Netflix DS onsite question on the prep site (posted 2025-10-13): plan a ranking A/B test, choosing user, session or query randomization.
Prep site·PracHub (prep site question bank)·2025-10-13Source
Netflix DS question on the prep site (posted 2025-08-04): network effects and SUTVA in a test of a social or streaming feature.
Prep site·PracHub (prep site question bank)·2025-08-04Source