Math for Causal Inference

Day 64. 2SLS in Matrix Form

Two-stage least squares generalises IV to many instruments and controls. Project the regressors on the instruments, regress the outcome on the projections, and get the variance right. Includes the GMM interpretation and the classic mistakes (manual second-stage standard errors, the forbidden regression).

Video coming soon
Learning outcomes
  • ●Derive the 2SLS estimator with the projection matrix and show it equals OLS on first-stage fitted values.
  • ●State the order and rank conditions for identification.
  • ●Compute 2SLS by hand in small examples and see it as a weighted average of single-instrument estimates.
  • ●Explain why manual second-stage standard errors are wrong and why nonlinear first stages must not be plugged in.
2-HOUR SESSION PLAN
Theory 25′Warm-up (1–5) 20′Proofs (6–10) 35′Applied (11–15) 25′Python & Lab 15′
Colab notebook (.ipynb) Jump to the simulator

Theory

Set-up

y=Xβ+ε\mathbf y = \mathbf X\boldsymbol\beta + \boldsymbol\varepsilon, where X\mathbf X (n×kn \times k) contains the endogenous regressors and the exogenous controls (including the constant). Z\mathbf Z (n×ln \times l) contains the excluded instruments and the same exogenous controls. Assumptions: E[ziεi]=0E[\mathbf z_i\varepsilon_i] = \mathbf 0 (instrument exogeneity) and rank⁡E[zixi⊤]=k\operatorname{rank}E[\mathbf z_i\mathbf x_i^\top] = k (rank condition).

  • Order condition: l≥kl \ge k: at least as many instruments as endogenous regressors. l=kl = k: just identified; l>kl > k: over-identified.

The estimator

With the projection matrix PZ=Z(Z⊤Z)−1Z⊤\mathbf P_Z = \mathbf Z(\mathbf Z^\top\mathbf Z)^{-1}\mathbf Z^\top,

β^2SLS=(X⊤PZX)−1X⊤PZy.\hat{\boldsymbol\beta}_{2SLS} = (\mathbf X^\top\mathbf P_Z\mathbf X)^{-1}\mathbf X^\top\mathbf P_Z\mathbf y.

Two stages. (1) Regress each column of X\mathbf X on Z\mathbf Z: X^=PZX\hat{\mathbf X} = \mathbf P_Z\mathbf X (exogenous columns are reproduced exactly). (2) Regress y\mathbf y on X^\hat{\mathbf X}. Because PZ\mathbf P_Z is symmetric and idempotent, X^⊤X^=X⊤PZX\hat{\mathbf X}^\top\hat{\mathbf X} = \mathbf X^\top\mathbf P_Z\mathbf X, so the second-stage OLS coefficients are exactly 2SLS.

Just identified: β^=(Z⊤X)−1Z⊤y\hat{\boldsymbol\beta} = (\mathbf Z^\top\mathbf X)^{-1}\mathbf Z^\top\mathbf y, the IV estimator.

Variance

Under homoskedasticity, Var⁡^(β^)=σ^2(X⊤PZX)−1\widehat{\operatorname{Var}}(\hat{\boldsymbol\beta}) = \hat\sigma^2(\mathbf X^\top\mathbf P_Z\mathbf X)^{-1} with σ^2=1n∑(yi−xi⊤β^)2\hat\sigma^2 = \frac1n\sum(y_i - \mathbf x_i^\top\hat{\boldsymbol\beta})^2, residuals computed with the actual X\mathbf X. The robust (sandwich) version is

(X^⊤X^)−1(∑ie^i2 x^ix^i⊤)(X^⊤X^)−1.(\hat{\mathbf X}^\top\hat{\mathbf X})^{-1}\Big(\sum_i\hat e_i^2\,\hat{\mathbf x}_i\hat{\mathbf x}_i^\top\Big)(\hat{\mathbf X}^\top\hat{\mathbf X})^{-1}.

Running the second stage by hand in software uses residuals yi−x^i⊤β^y_i - \hat{\mathbf x}_i^\top\hat{\boldsymbol\beta}, which gives the wrong standard errors.

GMM view

2SLS minimises (Z⊤(y−Xb))⊤(Z⊤Z)−1(Z⊤(y−Xb))(\mathbf Z^\top(\mathbf y - \mathbf X\mathbf b))^\top(\mathbf Z^\top\mathbf Z)^{-1}(\mathbf Z^\top(\mathbf y - \mathbf X\mathbf b)): GMM (Day 30) with weight matrix (Z⊤Z)−1(\mathbf Z^\top\mathbf Z)^{-1}, which is efficient under homoskedasticity. With heteroskedasticity, two-step GMM can be more efficient.

Many instruments: a weighted average

With one endogenous regressor and orthogonal instruments, 2SLS is a weighted average of the single-instrument IV estimates, with weights proportional to the squared first-stage strength of each instrument (Exercise 11).

Two mistakes to avoid

  • Controls in one stage only. Every exogenous control must appear in both stages; otherwise the first-stage residual is correlated with the omitted control.
  • The forbidden regression. With a binary treatment, plugging fitted probabilities from a probit into the second stage is not 2SLS and is inconsistent unless the probit is exactly right. Use the fitted probabilities as an instrument instead, or just use the linear first stage.

Part 1 · Warm-up

Exercise 1 · Just-identified by hand

Demeaned data (no constant): z=(1,−1,1,−1)z = (1, -1, 1, -1), x=(2,0,3,−1)x = (2, 0, 3, -1), y=(5,1,7,−1)y = (5, 1, 7, -1). Compute β^IV\hat\beta_{IV}.

Show solution

Step 1. z⊤y=5−1+7+1=12\mathbf z^\top\mathbf y = 5 - 1 + 7 + 1 = 12.

Step 2. z⊤x=2−0+3+1=6\mathbf z^\top\mathbf x = 2 - 0 + 3 + 1 = 6.

Step 3. β^=12/6=2\hat\beta = 12/6 = 2.

Exercise 2 · Properties of the projection

Show that PZ\mathbf P_Z is symmetric and idempotent.

Show solution

Step 1. PZ⊤=Z(Z⊤Z)−⊤Z⊤=PZ\mathbf P_Z^\top = \mathbf Z(\mathbf Z^\top\mathbf Z)^{-\top}\mathbf Z^\top = \mathbf P_Z, since Z⊤Z\mathbf Z^\top\mathbf Z is symmetric.

Step 2. PZPZ=Z(Z⊤Z)−1Z⊤Z(Z⊤Z)−1Z⊤=PZ\mathbf P_Z\mathbf P_Z = \mathbf Z(\mathbf Z^\top\mathbf Z)^{-1}\mathbf Z^\top\mathbf Z(\mathbf Z^\top\mathbf Z)^{-1}\mathbf Z^\top = \mathbf P_Z.

Exercise 3 · First-stage fitted values

In Exercise 1, compute the first-stage coefficient and fitted values x^\hat x.

Show solution

Step 1. π^=z⊤x/z⊤z=6/4=1.5\hat\pi = \mathbf z^\top\mathbf x/\mathbf z^\top\mathbf z = 6/4 = 1.5.

Step 2. x^=1.5z=(1.5,−1.5,1.5,−1.5)\hat x = 1.5z = (1.5, -1.5, 1.5, -1.5).

Step 3. Second stage: x^⊤y/x^⊤x^=1.5(12)/(2.25×4)=18/9=2\hat x^\top y/\hat x^\top\hat x = 1.5(12)/(2.25 \times 4) = 18/9 = 2, matching Exercise 1.

Exercise 4 · Order condition

A wage equation has two endogenous regressors (schooling and experience) and one instrument (quarter of birth). Is it identified? What if you add age as an instrument for experience?

Show solution

Step 1. kendog=2k_{endog} = 2, excluded instruments 1: order condition fails; not identified.

Step 2. With age: 2 instruments for 2 endogenous regressors: just identified (if the rank condition holds: age must predict experience separately from quarter of birth).

Exercise 5 · Controls in both stages

Why must region dummies that appear in the wage equation also appear in the first stage?

Show solution

Step 1. If region is omitted from the first stage, the first-stage residual X−X^X - \hat X contains the part of XX explained by region.

Step 2. Region is in the second stage, so that residual is correlated with a second-stage regressor; the estimator no longer equals (X⊤PZX)−1X⊤PZy(\mathbf X^\top\mathbf P_Z\mathbf X)^{-1}\mathbf X^\top\mathbf P_Z\mathbf y with a valid Z\mathbf Z and becomes inconsistent in general.

Answer: exogenous controls are their own instruments; include them in Z\mathbf Z.

Part 2 · Proofs

Exercise 6 · Two stages give 2SLS

Prove that OLS of y\mathbf y on X^=PZX\hat{\mathbf X} = \mathbf P_Z\mathbf X equals (X⊤PZX)−1X⊤PZy(\mathbf X^\top\mathbf P_Z\mathbf X)^{-1}\mathbf X^\top\mathbf P_Z\mathbf y.

Show solution

Step 1. OLS: (X^⊤X^)−1X^⊤y(\hat{\mathbf X}^\top\hat{\mathbf X})^{-1}\hat{\mathbf X}^\top\mathbf y.

Step 2. X^⊤X^=X⊤PZ⊤PZX=X⊤PZX\hat{\mathbf X}^\top\hat{\mathbf X} = \mathbf X^\top\mathbf P_Z^\top\mathbf P_Z\mathbf X = \mathbf X^\top\mathbf P_Z\mathbf X (Exercise 2).

Step 3. X^⊤y=X⊤PZy\hat{\mathbf X}^\top\mathbf y = \mathbf X^\top\mathbf P_Z\mathbf y. ■\blacksquare

Exercise 7 · Just identification

If l=kl = k and Z⊤X\mathbf Z^\top\mathbf X is invertible, prove β^2SLS=(Z⊤X)−1Z⊤y\hat{\boldsymbol\beta}_{2SLS} = (\mathbf Z^\top\mathbf X)^{-1}\mathbf Z^\top\mathbf y.

Show solution

Step 1. X⊤PZX=(X⊤Z)(Z⊤Z)−1(Z⊤X)\mathbf X^\top\mathbf P_Z\mathbf X = (\mathbf X^\top\mathbf Z)(\mathbf Z^\top\mathbf Z)^{-1}(\mathbf Z^\top\mathbf X), a product of three square invertible matrices.

Step 2. Its inverse is (Z⊤X)−1(Z⊤Z)(X⊤Z)−1(\mathbf Z^\top\mathbf X)^{-1}(\mathbf Z^\top\mathbf Z)(\mathbf X^\top\mathbf Z)^{-1}.

Step 3. Multiply by X⊤PZy=(X⊤Z)(Z⊤Z)−1Z⊤y\mathbf X^\top\mathbf P_Z\mathbf y = (\mathbf X^\top\mathbf Z)(\mathbf Z^\top\mathbf Z)^{-1}\mathbf Z^\top\mathbf y: everything cancels except (Z⊤X)−1Z⊤y(\mathbf Z^\top\mathbf X)^{-1}\mathbf Z^\top\mathbf y. ■\blacksquare

Exercise 8 · Consistency

Assume 1nZ⊤Z→Qzz\frac1n\mathbf Z^\top\mathbf Z \to \mathbf Q_{zz} (invertible), 1nZ⊤X→Qzx\frac1n\mathbf Z^\top\mathbf X \to \mathbf Q_{zx} (rank kk) and 1nZ⊤ε→0\frac1n\mathbf Z^\top\boldsymbol\varepsilon \to \mathbf 0. Prove β^2SLS→β\hat{\boldsymbol\beta}_{2SLS} \to \boldsymbol\beta.

Show solution

Step 1. Substitute y=Xβ+ε\mathbf y = \mathbf X\boldsymbol\beta + \boldsymbol\varepsilon: β^=β+(X⊤PZX)−1X⊤PZε\hat{\boldsymbol\beta} = \boldsymbol\beta + (\mathbf X^\top\mathbf P_Z\mathbf X)^{-1}\mathbf X^\top\mathbf P_Z\boldsymbol\varepsilon.

Step 2. Scale by 1/n1/n: 1nX⊤PZX→Qzx⊤Qzz−1Qzx\frac1n\mathbf X^\top\mathbf P_Z\mathbf X \to \mathbf Q_{zx}^\top\mathbf Q_{zz}^{-1}\mathbf Q_{zx}, invertible by the rank condition.

Step 3. 1nX⊤PZε=(1nX⊤Z)(1nZ⊤Z)−1(1nZ⊤ε)→Qzx⊤Qzz−10=0\frac1n\mathbf X^\top\mathbf P_Z\boldsymbol\varepsilon = (\frac1n\mathbf X^\top\mathbf Z)(\frac1n\mathbf Z^\top\mathbf Z)^{-1}(\frac1n\mathbf Z^\top\boldsymbol\varepsilon) \to \mathbf Q_{zx}^\top\mathbf Q_{zz}^{-1}\mathbf 0 = \mathbf 0.

Step 4. By Slutsky, the second term vanishes. ■\blacksquare

Exercise 9 · Why manual second-stage SEs are wrong

Show that the manual residual yi−x^iβ^y_i - \hat x_i\hat\beta equals εi+(xi−x^i)β\varepsilon_i + (x_i - \hat x_i)\beta asymptotically (scalar case), so σ^manual2→σ2+β2Var⁡(v)+2βCov⁡(v,ε)\hat\sigma^2_{manual} \to \sigma^2 + \beta^2\operatorname{Var}(v) + 2\beta\operatorname{Cov}(v, \varepsilon), where v=x−x^v = x - \hat x is the first-stage error.

Show solution

Step 1. yi=xiβ+εi=x^iβ+(xi−x^i)β+εiy_i = x_i\beta + \varepsilon_i = \hat x_i\beta + (x_i - \hat x_i)\beta + \varepsilon_i.

Step 2. With β^→β\hat\beta \to \beta, the manual residual is εi+viβ\varepsilon_i + v_i\beta.

Step 3. Its mean square converges to σ2+β2Var⁡(v)+2βCov⁡(v,ε)\sigma^2 + \beta^2\operatorname{Var}(v) + 2\beta\operatorname{Cov}(v, \varepsilon).

Answer: unless β=0\beta = 0, this differs from σ2\sigma^2; the standard errors are wrong (usually too large, but too small when βCov⁡(v,ε)<0\beta\operatorname{Cov}(v, \varepsilon) < 0 is large). ■\blacksquare

Exercise 10 · 2SLS is GMM

Show that minimising J(b)=(y−Xb)⊤Z(Z⊤Z)−1Z⊤(y−Xb)J(\mathbf b) = (\mathbf y - \mathbf X\mathbf b)^\top\mathbf Z(\mathbf Z^\top\mathbf Z)^{-1}\mathbf Z^\top(\mathbf y - \mathbf X\mathbf b) gives the 2SLS estimator.

Show solution

Step 1. J(b)=(y−Xb)⊤PZ(y−Xb)J(\mathbf b) = (\mathbf y - \mathbf X\mathbf b)^\top\mathbf P_Z(\mathbf y - \mathbf X\mathbf b).

Step 2. Gradient: −2X⊤PZ(y−Xb)=0-2\mathbf X^\top\mathbf P_Z(\mathbf y - \mathbf X\mathbf b) = \mathbf 0.

Step 3. Solve: b=(X⊤PZX)−1X⊤PZy\mathbf b = (\mathbf X^\top\mathbf P_Z\mathbf X)^{-1}\mathbf X^\top\mathbf P_Z\mathbf y. ■\blacksquare

Part 3 · Applied

Exercise 11 · Two instruments for schooling

With demeaned data and two orthogonal instruments (a quarter-of-birth indicator and a compulsory-schooling-law indicator), Z⊤Z=diag⁡(100,100)\mathbf Z^\top\mathbf Z = \operatorname{diag}(100, 100), Z⊤x=(20,10)⊤\mathbf Z^\top\mathbf x = (20, 10)^\top and Z⊤y=(3,1)⊤\mathbf Z^\top\mathbf y = (3, 1)^\top (log wages). Compute the two single-instrument IV estimates and the 2SLS estimate, and show 2SLS is their weighted average.

Show solution

Step 1. Single instruments: 3/20=0.153/20 = 0.15 and 1/10=0.101/10 = 0.10.

Step 2. x⊤PZx=(202+102)/100=5\mathbf x^\top\mathbf P_Z\mathbf x = (20^2 + 10^2)/100 = 5.

Step 3. x⊤PZy=(20×3+10×1)/100=0.7\mathbf x^\top\mathbf P_Z\mathbf y = (20 \times 3 + 10 \times 1)/100 = 0.7.

Step 4. β^2SLS=0.7/5=0.14\hat\beta_{2SLS} = 0.7/5 = 0.14.

Step 5. Weights proportional to (zj⊤x)2(\mathbf z_j^\top\mathbf x)^2: 400/500=0.8400/500 = 0.8 and 100/500=0.2100/500 = 0.2; 0.8(0.15)+0.2(0.10)=0.140.8(0.15) + 0.2(0.10) = 0.14.

Answer: 14% per year; the stronger instrument gets four times the weight.

Exercise 12 · A first stage with controls

A study of the effect of class size on test scores instruments class size with a rule that splits classes above 40 pupils (Maimonides' rule), controlling for enrolment. Write the two stages and say what identifies the effect.

Show solution

Step 1. First stage: class size =π0+π1f(enrolment)+π2 enrolment+v= \pi_0 + \pi_1 f(\text{enrolment}) + \pi_2\,\text{enrolment} + v, where ff is the rule's predicted class size.

Step 2. Second stage: score =β0+β1class size^+β2 enrolment+ε= \beta_0 + \beta_1\widehat{\text{class size}} + \beta_2\,\text{enrolment} + \varepsilon.

Step 3. Enrolment is in both stages; identification comes from the rule's discontinuous jumps in predicted class size, not from enrolment's smooth effect.

Answer: a 2SLS with an RD flavour (Day 76).

Exercise 13 · Manual standard errors in a simulation

In the simulation below (returns to schooling, true effect 0.08), compare the correct 2SLS standard error with the one from running the second stage by OLS.

Show solution

Step 1. The correct SE uses residuals y−Xβ^y - X\hat\beta.

Step 2. The manual SE uses y−X^β^y - \hat X\hat\beta, which adds βv\beta v to every residual (Exercise 9).

Step 3. Here the first-stage error has a large variance relative to σ2\sigma^2, so the manual SE is wrong by a noticeable factor (the code prints both, and the Monte Carlo standard deviation for reference).

Answer: always use the IV routine's standard errors (or compute residuals with the original regressors).

Exercise 14 · The forbidden regression

To estimate the effect of hospital admission DD (binary) on costs with distance as instrument, an analyst fits a probit of DD on distance and covariates, then regresses costs on the fitted probabilities. Why is this risky, and what should be done instead?

Show solution

Step 1. 2SLS's consistency relies on the first-stage residual being orthogonal to all second-stage regressors by construction (linear projection).

Step 2. A probit's residual has no such property; if the probit is misspecified, the second stage inherits a correlation between the fitted value and the error.

Step 3. Safe alternatives: linear first stage (2SLS), or use the probit fitted probability as an instrument for DD in a linear IV.

Answer: the plug-in version is consistent only if the probit is exactly right; using the probit as an instrument stays consistent regardless.

Exercise 15 · Heteroskedasticity-robust standard errors

In an IV regression of firm productivity on management training (instrumented by a subsidy lottery), residual variance is larger for small firms. Write the robust variance estimator and explain why it is preferred.

Show solution

Step 1. Var⁡^=(X^⊤X^)−1(∑ie^i2x^ix^i⊤)(X^⊤X^)−1\widehat{\operatorname{Var}} = (\hat{\mathbf X}^\top\hat{\mathbf X})^{-1}\big(\sum_i\hat e_i^2\hat{\mathbf x}_i\hat{\mathbf x}_i^\top\big)(\hat{\mathbf X}^\top\hat{\mathbf X})^{-1} with e^i=yi−xi⊤β^\hat e_i = y_i - \mathbf x_i^\top\hat{\boldsymbol\beta}.

Step 2. The homoskedastic formula assumes E[εi2∣zi]=σ2E[\varepsilon_i^2 \mid \mathbf z_i] = \sigma^2, false here.

Answer: the sandwich is consistent either way (Day 29); with clustered assignment (lotteries by region), cluster the middle term.

Verify in Python

import numpy as np

# Exercises 1 and 3
z = np.array([1, -1, 1, -1.]); x = np.array([2, 0, 3, -1.]); y = np.array([5, 1, 7, -1.])
print("IV:", z @ y / (z @ x), " first stage:", z @ x / (z @ z))

# Exercise 11 from cross-products
ZZ = np.diag([100., 100.]); Zx = np.array([20., 10.]); Zy = np.array([3., 1.])
print("single IVs:", Zy / Zx, " 2SLS:", round((Zx @ np.linalg.solve(ZZ, Zy)) / (Zx @ np.linalg.solve(ZZ, Zx)), 4))

# 2SLS by matrices, correct versus manual standard errors, with a Monte Carlo check (Exercise 13)
rng = np.random.default_rng(64)
def draw(n=2000):
    A = rng.normal(size=n); Z = rng.normal(size=(n, 2))
    S = 12 + Z @ np.array([.5, .3]) + 1.5 * A + rng.normal(0, 2, n)
    lw = 1 + .08 * S + .1 * A + rng.normal(0, .3, n)
    return lw, np.column_stack([np.ones(n), S]), np.column_stack([np.ones(n), Z])
def tsls(y, X, Z):
    Xh = Z @ np.linalg.lstsq(Z, X, rcond=None)[0]
    b = np.linalg.solve(Xh.T @ Xh, Xh.T @ y)
    inv = np.linalg.inv(Xh.T @ Xh)
    se_ok = np.sqrt((y - X @ b) @ (y - X @ b) / len(y) * inv[1, 1])
    se_manual = np.sqrt((y - Xh @ b) @ (y - Xh @ b) / len(y) * inv[1, 1])
    return b[1], se_ok, se_manual
y, X, Z = draw()
b, s1, s2 = tsls(y, X, Z)
print(f"2SLS {b:.4f}  correct SE {s1:.4f}  manual SE {s2:.4f}")
reps = [tsls(*draw())[0] for _ in range(500)]
print(f"Monte Carlo SD of 2SLS: {np.std(reps):.4f}")

Key takeaways

  • β^2SLS=(X⊤PZX)−1X⊤PZy\hat{\boldsymbol\beta}_{2SLS} = (\mathbf X^\top\mathbf P_Z\mathbf X)^{-1}\mathbf X^\top\mathbf P_Z\mathbf y: OLS on first-stage fitted values, with exogenous controls in both stages.
  • Identification needs as many instruments as endogenous regressors (order) and a full-rank first stage (rank).
  • Compute residuals with the actual regressors; never plug nonlinear first-stage predictions into the second stage.

Simulation Lab: Two-Stage Least Squares

Open full screen →

Watch both stages, and see why manual second-stage standard errors are wrong.

STAGE 1: x on z
-4-2024-3-2-10123instrument zregressor x
STAGE 2: y on fitted x̂
-2024-2-1012fitted x̂outcome y
first stage π̂
0.477
2SLS
0.387
truth 0.500
OLS
1.126
correct SE
0.1027
residuals y − b̂·x
manual 2nd-stage SE
0.1337
residuals y − b̂·x̂ (wrong)

Stage 1 projects the endogenous regressor on the instrument (left); stage 2 regresses the outcome on the fitted values (right). The slope is 2SLS. Standard errors must use residuals computed with the actual x, not the fitted x̂: compare the two.

Day 63Day 65