Regression the econometric way: projection, FWL and asymptotics
Reinterpret OLS without Gaussian errors as the best linear approximation to a conditional expectation, develop its large-sample sandwich variance under appropriate assumptions, use Frisch-Waugh-Lovell and distinguish descriptive from causal regression.
After this lesson you can
- Derive the population linear projection and error orthogonality without assuming a linear conditional expectation.
- Prove Frisch-Waugh-Lovell and interpret a coefficient after controlling for variables.
- Derive OLS consistency and asymptotic normality with sandwich variance under the stated sampling and moment assumptions.
- Distinguish a well-estimated projection coefficient from a biased causal parameter using an example.
- Reproduce a statsmodels OLS summary from a custom implementation.
Before you start
One slope, two questions
You want to know whether more developer training reduces the number of vulnerabilities introduced. A regression can describe how that number varies with training hours in observed data. To conclude what would change if more training were assigned, you must also justify how hours were chosen, which variables are controlled and whether selection or common causes occur.
In the Gaussian linear model, exact distributions follow under specific error assumptions. Here we drop normality and homoskedasticity, but not every assumption: moments, rank and sampling assumptions are needed to discuss limits and standard errors. A descriptive coefficient and causal effect can coincide, but that equality is a claim about the data-generating process.
Conditional expectation is the best predictor
Let be square integrable and . The conditional-expectation decomposition writes with . This is projection by conditional expectation. For every square-integrable function ,
The cross term is zero because . Thus minimizes squared error among all measurable predictors of , up to changes on probability-zero sets. If takes finitely many categories, a saturated regression with one indicator per category estimates each observed group mean; in the population it recovers the CEF for positive-probability categories.
Condition is stronger than one zero correlation: it implies for every appropriate integrable function. It follows from defining the residual relative to the CEF itself, not from a guarantee that variables missing from a causal model are irrelevant. If categories with no observations are added, their sample mean is undefined; including every indicator and a constant introduces exact linear dependence.
Projection depends on where data lie
Now restrict predictors to , including an intercept if desired. If and are finite and is positive definite, the population linear projection is unique:
The final equality follows from normal equations, not a randomized experiment. The CEF can be curved and can be nonzero. For example, if is uniform on and , the slope with intercept is and intercept . The curve’s slope is , so the line does not match all local derivatives.
CEF decomposition also explains why the same projection appears if is replaced by : residual is orthogonal to every component of . For any , expanding gives
The cross term vanishes by ; positive definite makes the minimum unique. If the CEF is linear it coincides with the projection and . The implication does not reverse from linear orthogonality alone.
The distribution of also matters: the criterion integrates squared error with respect to that distribution. Changing where observations concentrate can change the best line even if the conditional curve is identical. If is singular, unique projected predictions may exist in the closed linear space but coefficients are not uniquely identified.
from scipy.integrate import quad
# Densidad uniforme en [0,2] y CEF x².
moment = lambda k: quad(lambda x: x**k/2, 0, 2)[0]
ex, ex2, ex3 = moment(1), moment(2), moment(3)
slope = (ex3-ex*ex2)/(ex2-ex**2)
intercept = ex2-slope*ex
print('Uniforme, intercepto y pendiente:', intercept, slope)
# D=U+V; U y V independientes con varianza 1; efecto estructural de D igual a 1.
var_d, cov_du, structural_effect = 2., 1., 1.
descriptive = structural_effect+cov_du/var_d
print('Efecto estructural y pendiente descriptiva:', structural_effect, descriptive)Controlling means residualizing
Partition the design matrix into , with full rank, and define . This is a projection matrix onto the complement of the control space. The Frisch-Waugh-Lovell theorem states
The proof eliminates from the normal equations: project onto the orthogonal complement of columns of , then impose orthogonality to . is symmetric and idempotent, so the expression is also the regression of on . If the residualized block lacks full rank, the coefficient is not unique.
With one regressor of interest, residualizing only and regressing on it without an intercept gives the same slope because is orthogonal to . If the constant belongs to , adding an intercept to that auxiliary regression also leaves the slope unchanged, since the residualized regressor has mean zero. This is a sample algebraic identity. For standard errors and tests, retain the full model and its degrees of freedom; do not confuse the number of columns in the residual auxiliary regression with the number of parameters originally estimated.
Geometrically, is the part of the regressor outside the space spanned by controls. If two regressors are nearly collinear, that vector can have very small norm: the coefficient exists while rank remains, but becomes sensitive to noise. Under spherical errors its scalar conditional variance is . The graph uses a reproducible construction with controlled sample correlation to isolate that effect; it does not by itself prove coverage.
Law of large numbers and sandwich variance
For an iid sample of , positive definite , and sufficient moments for products, OLS asymptotics begin with
The law of large numbers and give consistency. If is also finite, the multivariate CLT and Slutsky imply
Orthogonality alone supplies neither independence, LLN nor CLT. A dependent time sample can require other assumptions and long-run covariance. HC0 estimation replaces moments with
The inner matrix retains the relationship between size of and squared residual. The classical formula replaces this structure with a common variance. HC0 needs its own convergence conditions and its intervals have no guaranteed exact finite-sample coverage. It does not by itself correct temporal dependence, selection, causal bias or infinite moments.
The robust construction relates to White’s (1980) estimator. Projection, least-squares algebra and asymptotics are developed further in the open text Hansen’s Econometrics.
Sandwich variance does not assume a correctly linear CEF: it estimates uncertainty of the projection coefficient under corresponding sampling and moment conditions. In the special case , and asymptotic variance simplifies to . Outside that case, two observations with the same residual error can contribute differently because product also depends on the regressor vector.
In the figure’s heteroskedastic example, and are independent standard normals and . With intercept, limiting variance of is , while the classical formula converges to . Thus the nominal 95% classical normal interval has limiting coverage , not 0.95. Robust estimation converges to the correct value under the example’s assumptions, but a finite simulation fluctuates randomly and improvement need not be monotonic.
import numpy as np
from scipy.stats import norm
z = norm.ppf(.975)
print('Varianza límite verdadera:', 3., 'varianza clásica:', 1.)
print('Cobertura límite clásica:', 2*norm.cdf(z/np.sqrt(3))-1)Partial association and causal effect
The distinction between descriptive and causal regression appears in an example. Let and , with independent, centered and unit-variance . The population projection of on an intercept and has slope . However, in the structural equation, changing by one unit while holding and fixed changes by one unit. The descriptive coefficient is well defined but does not identify that effect.
Conditioning on appropriate common causes can help under explicit identification assumptions. Condition in a structural model does not follow automatically from normal equations; nor does it turn an arbitrary control set, such as post-treatment variables, into valid causal adjustment. High or low measures sample fit under a specific definition, not validity of that assumption.
In the structural example, omitted variable changes both exposure and outcome. Term is nonzero for the structural error. By contrast, if projection error is defined as , it is orthogonal to by construction. These are different residuals: calling both without specifying the model is a common source of confusion. Even when measuring a common cause, ask whether it precedes treatment and suffices for the identification strategy.
Lab: reconstruct a regression
Longley has 16 observations and six regressors plus an intercept. The lab uses QR to estimate coefficients, derives classical and HC0 errors and compares each result with statsmodels. The condition number of an unscaled matrix depends on units: also compare the centered and scaled design. Normal equations form , whose condition number is the square of that of for full rank; this can amplify rounding errors.
The default summary shows classical intervals and statistics, alongside diagnostics and criteria calculated under its conventions. Exact t and F tests depend on their error assumptions; the displayed log-likelihood uses a concentrated Gaussian likelihood. None automatically makes data Gaussian or independent. The cell also calculates HC0, checks each component and verifies FWL with YEAR as the regressor of interest. Longley is a small time series: numerical comparison does not establish HC0 is sufficient for its temporal dependence.
"""OLS por QR; summary clásico de Longley y HC0 con comparación independiente."""
import numpy as np
import statsmodels.api as sm
from scipy import stats
data = sm.datasets.longley.load()
X = np.asarray(sm.add_constant(data.exog), dtype=float)
y = np.asarray(data.endog, dtype=float)
names = ['const', *list(data.exog.columns)]
n, p = X.shape
q, r = np.linalg.qr(X, mode='reduced')
if np.linalg.matrix_rank(X) != p:
raise ValueError('El diseño no tiene rango completo')
b = np.linalg.solve(r, q.T @ y)
residual = y-X@b
sse = residual@residual
centered = y-y.mean()
tss = centered@centered
df = n-p
sigma2 = sse/df
r_inv = np.linalg.solve(r, np.eye(p))
bread = r_inv @ r_inv.T
se = np.sqrt(sigma2*np.diag(bread))
influence = r_inv @ (q.T * residual)
cov_hc0 = influence @ influence.T
se_hc0 = np.sqrt(np.diag(cov_hc0))
t = b/se
p_values = 2*stats.t.sf(np.abs(t), df)
critical = stats.t.ppf(.975, df)
ci = np.column_stack((b-critical*se, b+critical*se))
r2 = 1-sse/tss
r2_adj = 1-(1-r2)*(n-1)/df
f = ((tss-sse)/(p-1))/sigma2
f_p = stats.f.sf(f, p-1, df)
loglike = -n/2*(np.log(2*np.pi)+1+np.log(sse/n))
aic, bic = -2*loglike+2*p, -2*loglike+np.log(n)*p
skew = stats.skew(residual)
kurt = stats.kurtosis(residual, fisher=False)
jb = n/6*(skew**2+(kurt-3)**2/4)
jb_p = stats.chi2.sf(jb, 2)
omnibus, omnibus_p = stats.normaltest(residual)
dw = np.sum(np.diff(residual)**2)/sse
fit = sm.OLS(y, X).fit()
assert np.allclose(b, fit.params, rtol=1e-8, atol=1e-7)
assert np.allclose(se, fit.bse, rtol=1e-8)
assert np.allclose(se_hc0, fit.HC0_se, rtol=1e-8)
assert np.allclose(p_values, fit.pvalues, rtol=1e-8)
assert np.allclose(ci, fit.conf_int(), rtol=1e-8, atol=1e-7)
assert np.allclose([r2, r2_adj, f, f_p, loglike, aic, bic],
[fit.rsquared, fit.rsquared_adj, fit.fvalue, fit.f_pvalue, fit.llf, fit.aic, fit.bic], rtol=1e-8)
jb_ref = sm.stats.stattools.jarque_bera(residual)
assert np.allclose([jb, jb_p, skew, kurt], jb_ref)
assert np.allclose([omnibus, omnibus_p], sm.stats.stattools.omni_normtest(residual))
assert np.allclose(dw, sm.stats.stattools.durbin_watson(residual))
print('Desde QR: coeficiente, EE clásico, t, p, IC95, EE HC0')
for i, name in enumerate(names):
print(f'{name:8s} {b[i]:.6g} {se[i]:.6g} {t[i]:.4g} {p_values[i]:.4g} '
f'[{ci[i,0]:.6g},{ci[i,1]:.6g}] {se_hc0[i]:.6g}')
print('R², R² ajustado, F, p(F):', *(f'{v:.6g}' for v in (r2,r2_adj,f,f_p)))
print('logL gaussiana concentrada, AIC, BIC:', *(f'{v:.6g}' for v in (loglike,aic,bic)))
print('Omnibus, p, JB, p, asimetría, curtosis, DW:',
*(f'{v:.6g}' for v in (omnibus,omnibus_p,jb,jb_p,skew,kurt,dw)))
print('Coeficientes, errores, p, intervalos, diagnóstico y resumen contrastados con statsmodels.')
# Las ecuaciones normales elevan al cuadrado el número de condición de X.
means = X[:,1:].mean(axis=0)
scales = X[:,1:].std(axis=0)
Z = np.column_stack((np.ones(n), (X[:,1:]-means)/scales))
qz, rz = np.linalg.qr(Z, mode='reduced')
bz = np.linalg.solve(rz, qz.T@y)
back = np.r_[bz[0]-np.sum(means*bz[1:]/scales), bz[1:]/scales]
assert np.allclose(X@b, X@back, rtol=1e-9, atol=1e-6)
try:
normal_b = np.linalg.solve(X.T@X, X.T@y)
print('Ecuaciones normales: máxima diferencia coeficiente frente a QR:', np.max(np.abs(normal_b-b)))
print('Ecuaciones normales: SSE y SSE QR:', np.sum((y-X@normal_b)**2), sse)
except np.linalg.LinAlgError as error:
print('Ecuaciones normales no resolubles numéricamente:', error)
print('Rango, condición original, condición centrada/escalada:', np.linalg.matrix_rank(X), np.linalg.cond(X), np.linalg.cond(Z))
print('El número de condición sin escalar depende de unidades; centrar y escalar separa ese efecto de la colinealidad.')"""Comprueba FWL y muestra el summary tras ejecutar la celda anterior."""
# Trata YEAR como regresor de interés y las seis columnas restantes como controles.
x1 = X[:,-1]
x2 = X[:,:-1]
q2, r2_control = np.linalg.qr(x2, mode='reduced')
res_x = x1-q2@(q2.T@x1)
res_y = y-q2@(q2.T@y)
b_fwl = (res_x@res_y)/(res_x@res_x)
assert np.allclose(b_fwl,b[-1],rtol=1e-8)
print('YEAR: coeficiente regresión múltiple y FWL:', b[-1], b_fwl)
print(fit.summary(xname=names, yname='TOTEMP'))"""Proyección ponderada por la distribución y regresión saturada."""
import numpy as np
from scipy.integrate import quad
# X=2*sqrt(U), U uniforme en [0,1]: densidad f(x)=x/2 en [0,2].
# La CEF es m(x)=x² y la perturbación independiente tiene media cero.
density = lambda x: x / 2
moment = lambda k: quad(lambda x: x**k * density(x), 0, 2)[0]
ex, ex2, ex3 = (moment(k) for k in (1, 2, 3))
slope = (ex3 - ex*ex2) / (ex2 - ex**2)
intercept = ex2 - slope*ex
assert np.allclose([ex, ex2, ex3, intercept, slope], [4/3, 2, 16/5, -6/5, 12/5])
print('Proyección poblacional (integración): intercepto, pendiente =', intercept, slope)
print('Pendiente local m\'(x) en x=1:', 2., '; no tiene por qué coincidir con la proyección')
gen = np.random.default_rng(270101)
u = gen.uniform(size=20000)
x = 2*np.sqrt(u)
y_sim = x*x + gen.normal(scale=.5, size=len(x))
for n_sim in (200, 2000, 20000):
X_sim = np.column_stack((np.ones(n_sim), x[:n_sim]))
q_sim, r_sim = np.linalg.qr(X_sim, mode='reduced')
beta = np.linalg.solve(r_sim, q_sim.T @ y_sim[:n_sim])
print('n:', n_sim, 'intercepto y pendiente estimados:', beta)
# El ruido impide igualdad exacta entre medias de muestra y CEF poblacional.
categories = gen.choice(3, size=6000, p=[.2, .5, .3])
cef = np.array([0., 1., 4.])
observed = cef[categories] + gen.normal(scale=.5, size=len(categories))
D = np.eye(3)[categories] # Una columna por categoría, sin constante adicional.
q_sim, r_sim = np.linalg.qr(D, mode='reduced')
coeff = np.linalg.solve(r_sim, q_sim.T @ observed)
sample_means = np.array([observed[categories == j].mean() for j in range(3)])
assert np.allclose(coeff, sample_means)
print('CEF poblacional por categoría:', cef)
print('Regresión saturada = medias empíricas:', coeff)
print('Diferencia respecto de la CEF poblacional:', coeff-cef)Exercises
Step 1 of 3. What identity does M₂ satisfy for the control block?
Step 1 of 3. What does the law of large numbers imply for the average of Xᵢuᵢ?
import numpy as np
def ols(X,y):
passfrom scipy.integrate import quad
moment_ejercicio = lambda k: quad(lambda x: x**k/3, 0, 3)[0]
cov = moment_ejercicio(3)-moment_ejercicio(1)*moment_ejercicio(2)
variance = moment_ejercicio(2)-moment_ejercicio(1)**2
print('Covarianza, varianza y pendiente:', cov, variance, cov/variance)