14/36
Part 3 of 6 · The clustered SELearn
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}")
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.
Pick an answer above to see the rest