23/36
Part 4 of 6 · RegressionLearn

A clustered standard error sums within each city before squaring

The fix is the same sandwich.

def cluster_se(X, y, cluster, j=-1):
    XtX_inv = np.linalg.inv(X.T @ X)
    resid = y - X @ (XtX_inv @ X.T @ y)
    groups = np.unique(cluster)
    meat = sum(np.outer(s, s) for s in
               (X[cluster == g].T @ resid[cluster == g] for g in groups))
    n, k, G = X.shape[0], X.shape[1], len(groups)
    V = XtX_inv @ meat @ XtX_inv * G / (G - 1) * (n - 1) / (n - k)
    return float(np.sqrt(V[j, j]))

Cluster on the unit that carries the correlation: here the city, which is usually also the unit that was treated.

The usual standard error treats each row's residual as its own piece of information. The clustered one first adds up, within each city, the rows weighted by their residuals: that sum is the city's score. Then it uses the spread of those 30 scores. Rows of one city that move together count as one lump, not 16 separate draws.

In the code, the inner generator makes each city's score, and sum adds up their outer products into meat. The inverse of X⊤XX^\top X goes on both sides, so it's called the sandwich formula. The last factors are a small-sample correction. j=-1 picks the last coefficient, δ\delta in both the four-mean regression and two-way fixed effects. The lesson Randomized by city, analyzed by user builds the same formula step by step.