Module contents
Lesson 19 of 27Core 120 min

The linear model as a statistical model

Derive exact Gaussian regression inference, interpret predictions and diagnose model failures.

After this lesson you can

  • Derive least-squares sampling distributions and Gauss–Markov optimality.
  • Use t and F tests and distinguish confidence from prediction intervals.
  • Interpret coefficients and diagnose collinearity, leverage and influence.
  • Apply heteroscedasticity-robust standard errors and regression bootstrap.

Before you start

Motivation: what slows a service, and how certain are we?

A platform team measures 120 service requests: latency in milliseconds, response size in KB, whether the request hit cache, and server load at the time (hundreds of concurrent requests). Nobody here asks which model best predicts the next request’s latency, the question of regression as prediction. The questions differ: how many milliseconds does a cache hit save, and with what margin of error? Is no size effect compatible with the data? How long will a particular request take, and how much uncertainty could more data reduce? This is inference, using the same tool as prediction, least squares, but emphasizing something different: not the fitted value but the distribution of coefficients and predictions under a probability model for the data.

The next cell simulates that service, fits regression, and compares two quantities that run through the lesson: each coefficient’s standard error from a formula applied to one sample, and actual coefficient dispersion when the experiment is repeated 5000 times with the same design and fresh noise.

[ ]A service, four coefficients and their uncertaintyBrowser
import numpy as np

rng = np.random.default_rng(19)
n = 120
kb = rng.lognormal(3.0, 0.6, n)              # tamaño de la respuesta, en KB
hit = rng.binomial(1, 0.55, n)               # 1 si la petición acierta en caché
load = rng.uniform(1, 8, n)                  # peticiones concurrentes, en cientos
beta_true = np.array([30.0, 0.12, -18.0, 0.9])
sigma = 12.0
X = np.column_stack([np.ones(n), kb, hit, load])
y = X @ beta_true + rng.normal(0, sigma, n)  # latencia en ms

beta, *_ = np.linalg.lstsq(X, y, rcond=None)
e = y - X @ beta
s2 = e @ e / (n - X.shape[1])
se = np.sqrt(s2 * np.diag(np.linalg.inv(X.T @ X)))          # s * sqrt((X'X)^-1_jj)

# 5000 repeticiones del experimento: mismo diseño X, ruido nuevo
A = np.linalg.inv(X.T @ X) @ X.T
Bs = beta_true + rng.normal(0, sigma, (5000, n)) @ A.T       # cada fila es un beta_hat
se_true = sigma * np.sqrt(np.diag(np.linalg.inv(X.T @ X)))
names = ["constante", "kb", "caché", "carga"]
print(f"{'':10s} {'verdad':>8s} {'estimado':>9s} {'EE (fórmula, con s)':>20s} {'EE (fórmula, con sigma)':>24s} {'desv. típica en 5000 réplicas':>30s}")
for j, nm in enumerate(names):
    print(f"{nm:10s} {beta_true[j]:8.2f} {beta[j]:9.3f} {se[j]:20.3f} {se_true[j]:24.3f} {Bs[:, j].std(ddof=1):30.3f}")
print(f"\nsigma = {sigma}, s = {np.sqrt(s2):.3f}")

In this sample, a cache hit reduces latency by 19.019.0 ms, with standard error 2.12.1 ms. That figure, 2.1462.146, comes from one sample and a formula, and resembles the result of repeating the experiment five thousand times (2.2262.226; with true σ\sigma, 2.2332.233). Coefficients are random variables: another sample gives different numbers, and the linear model is one of the few cases where we can say exactly how they change. Why does it matter? Without knowing the standard error of the carga coefficient is 0.540.54, we would not know whether 1.311.31 ms per hundred requests is signal or artifact.

The figure gives geometric intuition before formulas. Each line fits a different sample from the same model.

InteractiveMany possible lines
Lines fitted to 80 samples from the same model (truth: y=1+0.8 xy = 1 + 0.8\,x)
x̄x₀
  • one sample
  • its line (thick) and lines of other samples
  • empirical 5–95 % band
  • true line
  • β0+β1x±1.645 σh(x)\beta_0 + \beta_1 x \pm 1.645\,\sigma\sqrt{h(x)}
Slopes β^1\hat\beta_1 of these lines versus N(β1,σ2/Sxx)\Normal(\beta_1, \sigma^2/S_{xx})
β₁
  • histogram of β^1\hat\beta_1
  • exact normal
25
1.5
3.0
8.0
Lines drawn80
SE of β^1\hat\beta_1: theoretical σ/Sxx\sigma/\sqrt{S_{xx}} | empirical0.173 | 0.164
SE of β^0\hat\beta_0: theoretical | empirical0.755 | 0.666
SE of y^(x0)\hat y(x_0) at x0=8.0x_0 = 8.0: theoretical | empirical0.755 | 0.761
Standard error of the line at x0x_0 is 2.52 times that at xˉ=4\bar x = 4 (at x0=xˉx_0 = \bar x it is σ/n=0.300\sigma/\sqrt n = 0.300). Lines cross around xˉ\bar x and pivot like a door.
Left: least-squares lines fitted to up to 200 samples of y=1+0.8 x+εy = 1 + 0.8\,x + \varepsilon with ε∼N(0,σ2)\varepsilon \sim \Normal(0, \sigma^2) and identical xx values. Blue points are one sample and the thick orange line its fit. The shaded band contains the central 90% of lines at each xx, and dashed lines are the theoretical prediction β0+β1x±1.645 σh(x)\beta_0 + \beta_1 x \pm 1.645\,\sigma\sqrt{h(x)}. Right: slopes of all lines against their exact normal distribution. Press 'Add lines' to reach 200. Where is line dispersion smallest? Increase nn from 25 to 150: how much does the band narrow? Reduce xx dispersion to 1: what happens to the slope and the value at xˉ\bar x? Move x0x_0 outside the data range.

Three readings of the figure that the lesson will prove:

  • Lines rotate like a door. All pass near (xˉ,yˉ)(\bar x, \bar y) and spread out farther away. Uncertainty of the line at xx is smallest at xˉ\bar x, where it is σ/n\sigma/\sqrt n, and grows with (x−xˉ)2(x - \bar x)^2: extrapolation is costly, and the formula says how much.
  • Three levers control slope precision: less noise σ\sigma, more data nn, and, often forgotten, more dispersion in xx. With Sxx=∑i(xi−xˉ)2S_{xx} = \sum_i (x_i - \bar x)^2, the slope’s standard deviation is σ/Sxx\sigma/\sqrt{S_{xx}}. Experimental design is largely choosing the xx values.
  • The form is exactly normal. Not asymptotically: it is so even with n=6n = 6, provided noise is normal. This exactness is the Gaussian model’s gift and permits use of the tt distribution rather than only normal.

This lesson answers five questions. What is assumed and why? The Gaussian linear model and a table of which assumption supports which conclusion. What is the exact distribution of β^\hat{\vb{\beta}} and s2s^2? From it come tt tests, intervals, and the FF test for nested models. Is least squares optimal? Gauss–Markov and its limits. How is the model read and interpreted, and when does it warn that it is wrong? Categorical variables, collinearity, residuals, leverage and influence. What happens when assumptions fail? Sandwich standard errors and bootstrap, plus a complete implementation of the summary from statsmodels.

We use without further explanation maximum likelihood, normal sampling theory (χ2\chi^2, tt and FF), confidence intervals, prediction intervals, hypothesis tests and the likelihood ratio, as well as orthogonal projection, the projection matrix, column space, rank, inverse and QR decomposition, and the multivariate Gaussian with its affine transformations.

The Gaussian linear model

This is a statistical model as in lesson 2, with p+1p + 1 parameters, and is identifiable exactly when rank⁡(X)=p\rank(\mat{X}) = p: if columns are linearly dependent, some β≠β′\vb{\beta} \ne \vb{\beta}' have Xβ=Xβ′\mat{X}\vb{\beta} = \mat{X}\vb{\beta}', both producing the same distribution. “Linear” means linear in β\vb{\beta}, not variables: a column can be x2x^2, log⁡x\log x or a product of variables and the model remains linear.

The model combines five assumptions worth separating, because each conclusion rests on a different subset:

  1. Linearity and exogeneity: E[ε∣X]=0\E[\vb{\varepsilon} \given \mat{X}] = \vb{0}, i.e. E[y∣X]=Xβ\E[\vb{y} \given \mat{X}] = \mat{X}\vb{\beta}.
  2. Full rank: rank⁡(X)=p\rank(\mat{X}) = p.
  3. Homoscedasticity: Var⁡(εi∣X)=σ2\Var(\varepsilon_i \given \mat{X}) = \sigma^2 is equal for all ii.
  4. Uncorrelated errors (independent under the Gaussian model): Cov⁡(εi,εj)=0\Cov(\varepsilon_i, \varepsilon_j) = 0 if i≠ji \ne j.
  5. Normality: εi∼N(0,σ2)\varepsilon_i \sim \Normal(0, \sigma^2).
Assumptions satisfiedWhat can be claimed
1 and 2β^\hat{\vb{\beta}} is unbiased. Nothing about its variance.
1 through 4 (“spherical” errors)Var⁡(β^)=σ2(X⊤X)−1\Var(\hat{\vb{\beta}}) = \sigma^2(\mat{X}\T\mat{X})\inv, s2s^2 unbiased, and Gauss–Markov theorem.
1 through 5Exact distribution of β^\hat{\vb{\beta}}, s2s^2, tt and FF tests, exact confidence and prediction intervals. β^\hat{\vb{\beta}} is the MLE and minimum-variance unbiased estimator.
1 through 4 with independent errors, without 5, large nntt and FF tests and coefficient intervals asymptotically valid (central limit theorem, if no observation has dominant leverage). Prediction intervals are not: they depend on error shape.
1, 2 and 4, without 3β^\hat{\vb{\beta}} remains unbiased, but classical standard errors are incorrect. Use sandwich or bootstrap.

Two messages govern the rest. First, normality is the least important assumption for coefficients and the most important for predicting an individual case, because a coefficient is a weighted sum of errors handled by the central limit theorem, whereas a new observation brings one error with its own shape. Second, the assumption crucial to interpreting coefficients, exogeneity, cannot be tested from data: if a relevant variable correlated with included ones is omitted, β^\hat{\vb{\beta}} estimates something else and no pp-value reveals it. We return to this in common mistakes.

Least squares: projection and maximum likelihood

Proof

(1) Normal equations X⊤(y−Xβ^)=0\mat{X}\T(\vb{y} - \mat{X}\hat{\vb{\beta}}) = \vb{0} say e\vb{e} is orthogonal to col⁡(X)\col(\mat{X}). For any b\vb{b}, y−Xb=e+X(β^−b)\vb{y} - \mat{X}\vb{b} = \vb{e} + \mat{X}(\hat{\vb{\beta}} - \vb{b}) and the terms are orthogonal, so Pythagoras gives RSS(b)=∥e∥2+∥X(β^−b)∥2\mathrm{RSS}(\vb{b}) = \norm{\vb{e}}^2 + \norm{\mat{X}(\hat{\vb{\beta}} - \vb{b})}^2, minimal only if X(β^−b)=0\mat{X}(\hat{\vb{\beta}} - \vb{b}) = \vb{0}, i.e. b=β^\vb{b} = \hat{\vb{\beta}} because X\mat{X} has independent columns. (2) Log-likelihood is

ℓ(β,σ2)=−n2log⁡(2πσ2)−RSS(β)2σ2.\ell(\vb{\beta}, \sigma^2) = -\tfrac{n}{2}\log(2\pi\sigma^2) - \frac{\mathrm{RSS}(\vb{\beta})}{2\sigma^2}.

For any fixed σ2\sigma^2 it is maximized over β\vb{\beta} by minimizing RSS\mathrm{RSS}, so β^EMV=β^\hat{\vb{\beta}}_{\mathrm{EMV}} = \hat{\vb{\beta}}. Differentiating ℓ(β^,σ2)\ell(\hat{\vb{\beta}}, \sigma^2) with respect to σ2\sigma^2 gives −n2σ2+RSS2σ4=0-\frac{n}{2\sigma^2} + \frac{\mathrm{RSS}}{2\sigma^4} = 0, i.e. σ^2=RSS/n\hat\sigma^2 = \mathrm{RSS}/n. (3) RSS=ε⊤Mε\mathrm{RSS} = \vb{\varepsilon}\T\mat{M}\vb{\varepsilon}, because MX=0\mat{M}\mat{X} = \mat{0} and hence My=Mε\mat{M}\vb{y} = \mat{M}\vb{\varepsilon}, and M\mat{M} is symmetric and idempotent. Thus E[ε⊤Mε]=tr⁡(M E[εε⊤])=σ2tr⁡(M)=σ2(n−tr⁡H)=σ2(n−p)\E[\vb{\varepsilon}\T\mat{M}\vb{\varepsilon}] = \tr(\mat{M}\,\E[\vb{\varepsilon}\vb{\varepsilon}\T]) = \sigma^2\tr(\mat{M}) = \sigma^2(n - \tr\mat{H}) = \sigma^2(n - p), since tr⁡(H)=rank⁡(H)=p\tr(\mat{H}) = \rank(\mat{H}) = p (projection trace).

∎

The geometry is least squares in observation space Rn\R^n: y\vb{y} lives in Rn\R^n, the model is the pp-dimensional subspace generated by the columns, and the fit is the shadow of y\vb{y} on it. The n−pn - p residual degrees of freedom are the dimension of the orthogonal complement, where residuals live; in the next section noise is measured exactly there.

A numerical warning anticipates implementation. Calculating β^\hat{\vb{\beta}} by solving the normal equations with an explicit inverse squares the condition number, κ(X⊤X)=κ(X)2\kappa(\mat{X}\T\mat{X}) = \kappa(\mat{X})^2. The alternative is X=QR\mat{X} = \mat{Q}\mat{R}: with Q\mat{Q} having orthonormal columns and R\mat{R} triangular, β^\hat{\vb{\beta}} solves triangular system Rβ^=Q⊤y\mat{R}\hat{\vb{\beta}} = \mat{Q}\T\vb{y}, and H=QQ⊤\mat{H} = \mat{Q}\mat{Q}\T needs no inverse. The cell checks the theorem’s facts with service data and maximizes likelihood blindly from scratch to see agreement.

[ ]Projection, hat matrix and Gaussian likelihoodBrowser
H = X @ np.linalg.inv(X.T @ X) @ X.T
print("H simétrica:", np.allclose(H, H.T), "| idempotente:", np.allclose(H @ H, H))
print("traza de H:", round(np.trace(H), 6), "= rango de X:", np.linalg.matrix_rank(X))
print("H y coincide con X beta_hat:", np.allclose(H @ y, X @ beta))
print("máx |X' e| (residuos ortogonales a las columnas):", f"{np.abs(X.T @ e).max():.2e}")

from scipy.optimize import minimize
def nll(theta):                      # menos la log-verosimilitud gaussiana, con theta = (beta, log sigma)
    b, ls = theta[:4], theta[4]
    r = y - X @ b
    return n * ls + 0.5 * r @ r / np.exp(2 * ls) + 0.5 * n * np.log(2 * np.pi)
sol = minimize(nll, np.r_[np.zeros(4), 3.0], method="BFGS", options={"gtol": 1e-8})
print("\nbeta por mínimos cuadrados:", np.round(beta, 4))
print("beta por máxima verosimilitud:", np.round(sol.x[:4], 4))
rss = e @ e
print(f"sigma^2 EMV = {np.exp(2 * sol.x[4]):.3f}  frente a RSS/n = {rss / n:.3f}  y s^2 = RSS/(n-p) = {s2:.3f}")

The optimizer, starting from β=0\vb{\beta} = \vb{0} without knowing least squares, reaches the same four coefficients. The MLE variance, 128.6128.6, is 116/120=0.967116/120 = 0.967 times unbiased s2=133.0s^2 = 133.0: MLE underestimates σ2\sigma^2 because fitting has “spent” p=4p = 4 degrees of freedom approaching the data then used to measure error.

The exact distribution of coefficients

Everything that follows comes from one theorem, whose proof is pure geometry in Rn\R^n.

Proof

Complete the orthonormal columns of X=Q1R\mat{X} = \mat{Q}_1\mat{R} to an orthogonal matrix Q=[Q1 Q2]\mat{Q} = [\mat{Q}_1\ \mat{Q}_2] of Rn\R^n (Q1∈Rn×p\mat{Q}_1 \in \R^{n \times p}, Q2∈Rn×(n−p)\mat{Q}_2 \in \R^{n \times (n-p)}). Since Q⊤\mat{Q}\T is an orthogonal linear transformation, ζ=Q⊤ε/σ∼N(0,Q⊤Q)=N(0,In)\vb{\zeta} = \mat{Q}\T\vb{\varepsilon}/\sigma \sim \Normal(\vb{0}, \mat{Q}\T\mat{Q}) = \Normal(\vb{0}, \mat{I}_n) (Gaussian affine transformation). Its two blocks, u=Q1⊤ε/σ∈Rp\vb{u} = \mat{Q}_1\T\vb{\varepsilon}/\sigma \in \R^p and w=Q2⊤ε/σ∈Rn−p\vb{w} = \mat{Q}_2\T\vb{\varepsilon}/\sigma \in \R^{n-p}, are therefore independent standard Gaussians.

(1) β^=(X⊤X)−1X⊤(Xβ+ε)=β+R−1Q1⊤ε=β+σR−1u\hat{\vb{\beta}} = (\mat{X}\T\mat{X})\inv\mat{X}\T(\mat{X}\vb{\beta} + \vb{\varepsilon}) = \vb{\beta} + \mat{R}\inv\mat{Q}_1\T\vb{\varepsilon} = \vb{\beta} + \sigma\mat{R}\inv\vb{u}, an affine transformation of u\vb{u}: Gaussian with mean β\vb{\beta} and covariance σ2R−1R−T=σ2(X⊤X)−1\sigma^2\mat{R}\inv\mat{R}^{-\mathsf{T}} = \sigma^2(\mat{X}\T\mat{X})\inv.

(2) Residuals are e=Mε=Q2Q2⊤ε\vb{e} = \mat{M}\vb{\varepsilon} = \mat{Q}_2\mat{Q}_2\T\vb{\varepsilon}, so RSS=∥Q2⊤ε∥2=σ2∥w∥2∼σ2χn−p2\mathrm{RSS} = \norm{\mat{Q}_2\T\vb{\varepsilon}}^2 = \sigma^2\norm{\vb{w}}^2 \sim \sigma^2\chi^2_{n-p}.

(3) β^\hat{\vb{\beta}} is a function of u\vb{u} and RSS\mathrm{RSS} is a function of w\vb{w}, and u⊥ ⁣ ⁣ ⁣⊥w\vb{u} \indep \vb{w}.

(4) The standardized numerator, c⊤(β^−β)/(σc⊤(X⊤X)−1c)\vb{c}\T(\hat{\vb{\beta}} - \vb{\beta})/(\sigma\sqrt{\vb{c}\T(\mat{X}\T\mat{X})\inv\vb{c}}), is N(0,1)\Normal(0, 1) by (1). Dividing by s/σ=(RSS/σ2)/(n−p)s/\sigma = \sqrt{(\mathrm{RSS}/\sigma^2)/(n-p)}, which by (2) is the square root of χn−p2\chi^2_{n-p} divided by its degrees of freedom and independent by (3), gives the definition of tn−pt_{n-p}.

∎

The final proof exercise offers another, algebraic route to (1)–(3). The geometry is the same: the part of ε\vb{\varepsilon} inside the model determines β^\hat{\vb{\beta}}, the outside part determines s2s^2, and the parts are independent because they are orthogonal projections of a spherical Gaussian vector.

From (4) construct intervals and tests together. The level-1−α1 - \alpha confidence interval for βj\beta_j is

β^j±tn−p, 1−α/2  scjj,\hat\beta_j \pm t_{n-p,\,1-\alpha/2}\; s\sqrt{c_{jj}},

and the tt test of H0 ⁣:βj=0H_0\!: \beta_j = 0 rejects when ∣Tj∣=∣β^j∣/EE(β^j)>tn−p, 1−α/2\abs{T_j} = \abs{\hat\beta_j}/\mathrm{EE}(\hat\beta_j) > t_{n-p,\,1-\alpha/2}; by test–interval duality from lesson 10, this coincides with 0 lying outside the interval. Full covariance is Cov⁡(β^)=σ2(X⊤X)−1\Cov(\hat{\vb{\beta}}) = \sigma^2(\mat{X}\T\mat{X})\inv: coefficients are not independent of one another, and that correlation will star in collinearity. First, a simulation check with small size (n=15n = 15, p=3p = 3), where using 1.961.96 instead of tt makes a difference.

[ ]The theorem's four results, by simulationBrowser
from scipy import stats
rng = np.random.default_rng(17)
n3, p3, R = 15, 3, 20000
X3 = np.column_stack([np.ones(n3), rng.normal(size=n3), rng.normal(size=n3)])
b0, sg = np.array([1.0, 2.0, 0.0]), 2.0                       # beta_2 = 0 de verdad
A3 = np.linalg.pinv(X3)
Y = X3 @ b0 + rng.normal(0, sg, (R, n3))
Bh = Y @ A3.T
E = Y - Bh @ X3.T
S2 = (E ** 2).sum(1) / (n3 - p3)
c = np.diag(np.linalg.inv(X3.T @ X3))
t = Bh[:, 2] / np.sqrt(S2 * c[2])                             # estadístico t de beta_2 con H0 cierta
q = (n3 - p3) * S2 / sg ** 2
print(f"cuantil 97.5 % de t:  simulado {np.quantile(t, .975):.3f}   t_{{{n3-p3}}} {stats.t.ppf(.975, n3 - p3):.3f}   normal {stats.norm.ppf(.975):.3f}")
print(f"P(|t| > 1.96) = {np.mean(np.abs(t) > 1.96):.4f}   P(|t| > t_12) = {np.mean(np.abs(t) > stats.t.ppf(.975, 12)):.4f}")
print(f"KS de t contra t_12: p = {stats.kstest(t, 't', args=(12,)).pvalue:.3f}")
print(f"(n-p)s^2/sigma^2: media {q.mean():.3f} (teoría {n3 - p3}), varianza {q.var():.2f} (teoría {2 * (n3 - p3)}); KS contra chi2_12: p = {stats.kstest(q, 'chi2', args=(12,)).pvalue:.3f}")
print(f"correlación entre beta_hat_1 y s^2: {np.corrcoef(Bh[:, 1], S2)[0, 1]:+.4f}   (independientes)")
print(f"correlación entre beta_hat_1 y beta_hat_2: {np.corrcoef(Bh[:, 1], Bh[:, 2])[0, 1]:+.4f}   teoría: {np.linalg.inv(X3.T @ X3)[1, 2] / np.sqrt(c[1] * c[2]):+.4f}")

The tt statistic has exactly t12t_{12} (the Kolmogorov–Smirnov test does not distinguish the simulated sample from it), and the 97.5 %97.5\ \% quantile is 2.182.18, not 1.961.96. With normal, a “5%” test would reject a true null 7.2 %7.2\ \% of the time. Normalized residual sum of squares has the mean 1212 and variance 2424 of χ122\chi^2_{12}, is independent of β^\hat{\vb{\beta}} (correlation +0.002+0.002, within Monte Carlo error 1/20000≈0.0071/\sqrt{20000} \approx 0.007), and coefficients are correlated with each other (+0.572+0.572, versus theory +0.574+0.574).

The Gauss–Markov theorem and its limits

Normality gives exactness, but is not why least squares is used. Its historical rationale is an optimality result that does not need normality.

Proof

Let β~=Ay\tilde{\vb{\beta}} = \mat{A}\vb{y} be unbiased: E[β~]=AXβ=β\E[\tilde{\vb{\beta}}] = \mat{A}\mat{X}\vb{\beta} = \vb{\beta} for all β\vb{\beta}, so AX=Ip\mat{A}\mat{X} = \mat{I}_p. Write A=(X⊤X)−1X⊤+D\mat{A} = (\mat{X}\T\mat{X})\inv\mat{X}\T + \mat{D}. Then AX=I+DX\mat{A}\mat{X} = \mat{I} + \mat{D}\mat{X}, so DX=0\mat{D}\mat{X} = \mat{0}. Variance is

Var⁡(β~)=σ2AA⊤=σ2[(X⊤X)−1+(X⊤X)−1X⊤D⊤⏟= (DX)⊤ = 0+DX⏟= 0(X⊤X)−1+DD⊤]=Var⁡(β^)+σ2DD⊤.\Var(\tilde{\vb{\beta}}) = \sigma^2\mat{A}\mat{A}\T = \sigma^2\Big[(\mat{X}\T\mat{X})\inv + (\mat{X}\T\mat{X})\inv\underbrace{\mat{X}\T\mat{D}\T}_{=\,(\mat{D}\mat{X})\T\,=\,\mat{0}} + \underbrace{\mat{D}\mat{X}}_{=\,\mat{0}}(\mat{X}\T\mat{X})\inv + \mat{D}\mat{D}\T\Big] = \Var(\hat{\vb{\beta}}) + \sigma^2\mat{D}\mat{D}\T.

Matrix DD⊤\mat{D}\mat{D}\T is positive semidefinite (v⊤DD⊤v=∥D⊤v∥2≥0\vb{v}\T\mat{D}\mat{D}\T\vb{v} = \norm{\mat{D}\T\vb{v}}^2 \ge 0), proving the claim. For fixed c\vb{c}, Var⁡(c⊤β~)−Var⁡(c⊤β^)=σ2∥D⊤c∥2\Var(\vb{c}\T\tilde{\vb{\beta}}) - \Var(\vb{c}\T\hat{\vb{\beta}}) = \sigma^2\norm{\mat{D}\T\vb{c}}^2, zero only if D⊤c=0\mat{D}\T\vb{c} = \vb{0}, i.e. c⊤β~=c⊤β^\vb{c}\T\tilde{\vb{\beta}} = \vb{c}\T\hat{\vb{\beta}}.

∎

What the theorem does not say matters as much as what it does, and causes many misunderstandings:

  • It competes only with linear, unbiased estimators. A biased estimator can have smaller mean squared error, as in the estimators lesson: ridge regression, James–Stein or any shrinkage achieves this by sacrificing some unbiasedness, especially when X⊤X\mat{X}\T\mat{X} is ill-conditioned. Gauss–Markov does not forbid bias: it says that if unbiasedness is required, no improvement is possible.
  • With normality the result is stronger. With Gaussian errors, (β^,RSS)(\hat{\vb{\beta}}, \mathrm{RSS}) is a complete sufficient statistic of the model’s exponential family, and Lehmann–Scheffé makes least squares the minimum-variance unbiased estimator among all estimators, linear or not.
  • With heavy-tailed errors, a nonlinear estimator wins. For Laplace errors, least-absolute-deviation regression (without predictors, the median) is more efficient than least squares (without predictors, the mean). This is the territory of M-estimators and the Huber estimator.
  • It says nothing when homoscedasticity fails. With Var⁡(ε)=Σ≠σ2I\Var(\vb{\varepsilon}) = \mat{\Sigma} \ne \sigma^2\mat{I}, least squares remains unbiased but is no longer best (generalized least squares, which weights, is) and its variance is no longer σ2(X⊤X)−1\sigma^2(\mat{X}\T\mat{X})\inv.
[ ]Limits of Gauss–Markov: ridge and median win in mean squared errorBrowser
rng = np.random.default_rng(4)
n4 = 30
z1 = rng.normal(size=n4); z2 = 0.95 * z1 + np.sqrt(1 - 0.95 ** 2) * rng.normal(size=n4)
Xc = np.column_stack([z1 - z1.mean(), z2 - z2.mean()])      # dos predictores con correlación 0.95
G = Xc.T @ Xc
bt, sg4 = np.array([1.0, -1.0]), 2.0                        # el peor caso para la cresta: beta en la dirección débil
def ecm(lam):                                               # fórmulas exactas de varianza y sesgo^2 de la cresta
    M = np.linalg.inv(G + lam * np.eye(2))
    return sg4 ** 2 * np.trace(M @ G @ M), lam ** 2 * bt @ M @ M @ bt
v0 = ecm(0.0)[0]
lams = np.logspace(-2, 3, 400)
tot = np.array([sum(ecm(l)) for l in lams])
k = tot.argmin()
v, b2 = ecm(lams[k])
print(f"MCO: varianza {v0:.3f}, sesgo 0, ECM {v0:.3f}")
print(f"cresta con lambda = {lams[k]:.2f}: varianza {v:.3f}, sesgo^2 {b2:.3f}, ECM {v + b2:.3f}  ({(v + b2) / v0:.0%} del de MCO)")
print(f"el estimador constante 0 tiene ECM = |beta|^2 = {bt @ bt:.3f}, también menor que el de MCO")
# errores de Laplace: la media (MCO sin predictores) frente a la mediana (regresión LAD sin predictores)
n5 = 51
L = rng.laplace(0, 1, (20000, n5))
print(f"\nerrores de Laplace, n = {n5}: Var(media) = {L.mean(1).var():.4f}, Var(mediana) = {np.median(L, 1).var():.4f}, cociente {L.mean(1).var() / np.median(L, 1).var():.2f}  (tiende a 2 al crecer n)")

With two predictors correlated at 0.950.95 and n=30n = 30, least squares has mean squared error 3.913.91 from variance alone. Ridge with λ≈2\lambda \approx 2 lowers it to 1.371.37 (35 %35\ \%), at the cost of squared bias 0.870.87, even when the true parameter points in the least well-determined direction. With Laplace errors, the median has 1.61.6 times less variance than the mean at n=51n = 51 (ratio tends to 22). Gauss–Markov is not contradicted: neither competitor is both linear and unbiased.

Comparing models: the FF test

The tt test tests one coefficient. To test several simultaneously, or decide if a block of variables contributes, compare two nested models.

The numerator measures how much error falls when constraints are relaxed, per degree of freedom spent; the denominator is noise estimated with the larger model. If constraints were true, the reduction would be comparable to noise and F≈1F \approx 1.

Proof

Let H0⊂H1\mat{H}_0 \subset \mat{H}_1 be projections onto V0⊂V1V_0 \subset V_1. Then RSS0−RSS1=∥(H1−H0)y∥2\mathrm{RSS}_0 - \mathrm{RSS}_1 = \norm{(\mat{H}_1 - \mat{H}_0)\vb{y}}^2 (Pythagoras: H1−H0\mat{H}_1 - \mat{H}_0 projects onto the complement of V0V_0 within V1V_1, of dimension qq). If H0H_0 is true, X1β∈V0\mat{X}_1\vb{\beta}\in V_0, so (H1−H0)y=(H1−H0)ε(\mat{H}_1 - \mat{H}_0)\vb{y} = (\mat{H}_1 - \mat{H}_0)\vb{\varepsilon} and RSS1=∥(I−H1)ε∥2\mathrm{RSS}_1 = \norm{(\mat{I} - \mat{H}_1)\vb{\varepsilon}}^2. The two projections are mutually orthogonal, with ranks qq and n−p1n - p_1; applied to spherical ε\vb{\varepsilon} they give (as in the previous proof) two independent σ2χ2\sigma^2\chi^2 variables with those degrees of freedom, and their normalized ratio is Fq, n−p1F_{q,\,n-p_1}. For likelihood ratio, maximizing over σ2\sigma^2 in each model gives σ^i2=RSSi/n\hat\sigma^2_i = \mathrm{RSS}_i/n and ℓi=−n2log⁡(2πσ^i2)−n2\ell_i = -\frac{n}{2}\log(2\pi\hat\sigma^2_i) - \frac{n}{2}, so −2log⁡Λ=2(ℓ1−ℓ0)=nlog⁡(RSS0/RSS1)-2\log\Lambda = 2(\ell_1 - \ell_0) = n\log(\mathrm{RSS}_0/\mathrm{RSS}_1). Since RSS0/RSS1=1+qn−p1F\mathrm{RSS}_0/\mathrm{RSS}_1 = 1 + \frac{q}{n - p_1}F, we obtain −2log⁡Λ=nlog⁡(1+qn−p1F)-2\log\Lambda = n\log\big(1 + \frac{q}{n-p_1}F\big), increasing in FF; solve to obtain the stated formula.

∎

Three special cases appear in every regression summary:

  • One coefficient (q=1q = 1): F=Tj2F = T_j^2, and the FF and two-sided tt tests coincide. If T∼tνT \sim t_\nu, then T2∼F1,νT^2 \sim F_{1,\nu}.
  • Global test, M0\mathcal{M}_0 with intercept only: with TSS=∑i(yi−yˉ)2\mathrm{TSS} = \sum_i (y_i - \bar y)^2 and coefficient of determination R2=1−RSS/TSSR^2 = 1 - \mathrm{RSS}/\mathrm{TSS}, F=R2/(p−1)(1−R2)/(n−p)F = \dfrac{R^2/(p-1)}{(1 - R^2)/(n-p)}. It tests “no variable explains anything.”
  • Variable blocks, e.g. all columns encoding a categorical variable: test qq coefficients simultaneously, which qq separate tt tests do poorly (they neither control global error nor account for estimator correlation).

R2R^2 never decreases when adding a variable, informative or not; hence adjusted R2R^2, Raj2=1−(1−R2)n−1n−pR^2_{\mathrm{aj}} = 1 - (1 - R^2)\frac{n-1}{n-p}, which compares s2s^2 with sample variance of y\vb{y}. Adding one variable raises Raj2R^2_{\mathrm{aj}} if and only if its FF statistic (i.e. T2T^2) exceeds 11: from RSS1/(n−p1)<RSS0/(n−p0)\mathrm{RSS}_1/(n-p_1) < \mathrm{RSS}_0/(n-p_0) with p1=p0+1p_1 = p_0 + 1, rearrange to (RSS0−RSS1)(n−p1)>RSS1(\mathrm{RSS}_0 - \mathrm{RSS}_1)(n-p_1) > \mathrm{RSS}_1, which is F>1F > 1. This is lax (not equivalent to 5 %5\ \% significance, requiring F≳4F \gtrsim 4); useful for description, not selection.

[ ]F test, likelihood ratio and service R²Browser
def rss_of(Xm):
    b = np.linalg.lstsq(Xm, y, rcond=None)[0]
    r = y - Xm @ b
    return r @ r, Xm.shape[1]
rss1, p1 = rss_of(X)                                  # modelo completo: constante, kb, caché, carga
rss0, p0 = rss_of(X[:, [0, 3]])                       # anidado: solo constante y carga
F = ((rss0 - rss1) / (p1 - p0)) / (rss1 / (n - p1))
pF = stats.f.sf(F, p1 - p0, n - p1)
lrt = n * np.log(rss0 / rss1)
print(f"RSS completo {rss1:.1f} ({p1} parámetros), RSS anidado {rss0:.1f} ({p0} parámetros)")
print(f"F = {F:.3f} con ({p1 - p0}, {n - p1}) gl, p = {pF:.2e}")
print(f"-2 log Lambda = n log(RSS0/RSS1) = {lrt:.3f}, p chi2_{p1-p0} = {stats.chi2.sf(lrt, p1 - p0):.2e}")
print(f"F recuperada de -2 log Lambda: {(n - p1) / (p1 - p0) * (np.exp(lrt / n) - 1):.3f}")
# un solo coeficiente: F = t^2
rss_nc, _ = rss_of(X[:, [0, 1, 3]])
F1 = (rss_nc - rss1) / (rss1 / (n - p1))
t_hit = beta[2] / se[2]
print(f"\nquitar solo 'caché': F = {F1:.3f}, t^2 = {t_hit ** 2:.3f}")
tss = ((y - y.mean()) ** 2).sum()
r2 = 1 - rss1 / tss
print(f"R^2 = {r2:.4f}, R^2 ajustado = {1 - (1 - r2) * (n - 1) / (n - p1):.4f}, F global = {((tss - rss1) / (p1 - 1)) / (rss1 / (n - p1)):.2f}")

For the service, removing kb and caché together substantially worsens fit: F=44.8F = 44.8 with (2,116)(2, 116) degrees of freedom, pp-value of order 10−1510^{-15}. The likelihood ratio gives 68.768.7 and, converted using the theorem’s formula, exactly the same FF; its asymptotic pp-value (χ22\chi^2_2, 1.2×10−151.2 \times 10^{-15}) is similar here because n=120n = 120, but optimistic for small samples. For one coefficient, caché, F=t2=78.4F = t^2 = 78.4. The model explains 43.9 %43.9\ \% of variability (Raj2=0.424R^2_{\mathrm{aj}} = 0.424): moderate R2R^2 with clearly significant effects is normal in noisy data, reminding us significance is not predictive ability.

Confidence for the line versus prediction for one case

Two distinct questions share the fitted line. What is mean latency for requests with certain characteristics? This is a parameter, μ(x0)=x0⊤β\mu(\vb{x}_0) = \vb{x}_0\T\vb{\beta}. How long will the next request with those characteristics take? This is a random variable, y0=x0⊤β+ε0y_0 = \vb{x}_0\T\vb{\beta} + \varepsilon_0. The second includes observation noise as well as uncertainty about the line.

Proof

(1) Var⁡(y^0)=σ2h0\Var(\hat y_0) = \sigma^2 h_0 and y^0∼N(μ0,σ2h0)\hat y_0 \sim \Normal(\mu_0, \sigma^2 h_0) is independent of s2s^2, so (y^0−μ0)/(sh0)(\hat y_0 - \mu_0)/(s\sqrt{h_0}) is tn−pt_{n-p} (the c=x0\vb{c} = \vb{x}_0 case of the exact-distribution theorem). (2) y0−y^0y_0 - \hat y_0 is Gaussian with mean zero and, since y0y_0 is independent of y^0\hat y_0, variance σ2+σ2h0=σ2(1+h0)\sigma^2 + \sigma^2 h_0 = \sigma^2(1 + h_0); the ratio to s1+h0s\sqrt{1+h_0} is again tn−pt_{n-p} by independence of y0−y^0y_0 - \hat y_0 and s2s^2. (3) By Cauchy–Schwarz, sup⁡x[x⊤(β^−β)]2x⊤(X⊤X)−1x=(β^−β)⊤X⊤X(β^−β)\sup_{\vb{x}}\dfrac{[\vb{x}\T(\hat{\vb{\beta}} - \vb{\beta})]^2}{\vb{x}\T(\mat{X}\T\mat{X})\inv\vb{x}} = (\hat{\vb{\beta}} - \vb{\beta})\T\mat{X}\T\mat{X}(\hat{\vb{\beta}} - \vb{\beta}), and divided by p s2p\,s^2 this square follows Fp,n−pF_{p,n-p} (a pp-dimensional Gaussian quadratic form divided by its covariance and by pp, over independent χn−p2/(n−p)\chi^2_{n-p}/(n-p)). The probability the supremum does not exceed pFp,n−p,1−αs2pF_{p,n-p,1-\alpha}s^2 is 1−α1-\alpha, equivalent to all pointwise inequalities holding simultaneously.

∎

The two formulas differ by the 11 under the square root; that 11 represents observation noise, and its consequences are enormous. As n→∞n \to \infty, h0→0h_0 \to 0: the confidence interval collapses onto the line, since infinite data determine the mean without error. The prediction interval approaches ±1.96 σ\pm 1.96\,\sigma, not zero: no model, however well estimated, can predict noise. Unlike confidence for a coefficient, prediction is not rescued by the central limit theorem: it depends on ε0\varepsilon_0 being Gaussian (or its actual shape) and having the same variance at x0\vb{x}_0 as in the data.

InteractiveConfidence band versus prediction band
Fit with n=20n = 20 points: 95 % bands (truth: y=1+0.8 xy = 1 + 0.8\,x)
x₀
Actual coverage (%) of prediction band for a new observation at each xx
  • prediction y^±t s1+h\hat y \pm t\,s\sqrt{1 + h}
  • confidence y^±t sh\hat y \pm t\,s\sqrt{h}
  • simultaneous (Working and Hotelling)
  • fitted line
  • true line and ±1.96 σ(x)\pm 1.96\,\sigma(x)
20
1.5
9.0
Half-width at x0=9.0x_0 = 9.0: confidence | prediction1.64 | 4.01
Prediction limit as n→∞n \to \infty: 1.96 σ(x0)1.96\,\sigma(x_0)2.94
Estimate ss | true σ\sigma (averaged over xx)1.74 | 1.50
Actual prediction-band coverage: mean | minimum97.0 % | 92.5 %
With homoscedastic noise, coverage for a new observation is nearly 95 % at every xx (slightly sample-dependent and approaching 95 % as nn grows). The confidence band covers the true mean pointwise; the wider simultaneous band covers the whole true line with probability 95 %.
A fit to nn points from y=1+0.8 x+σ(x) εy = 1 + 0.8\,x + \sigma(x)\,\varepsilon. Orange is the confidence interval for the line and blue the prediction interval for a new observation, both 95%. Dotted lines are the true line and its ±1.96 σ(x)\pm 1.96\,\sigma(x), the prediction limit. Below, exact prediction-band coverage (calculated using the true normal distribution, not simulated) for a new observation at each xx. Increase nn to 400: which band narrows and which does not? Enable heteroscedastic noise: where does the prediction band undercover, and by how much? Enable simultaneous band: why is it wider than confidence? Press 'Another sample'.

Three things to inspect. The confidence band is hourglass-shaped, narrowest at xˉ\bar x (the square root of h(x)=1n+(x−xˉ)2Sxxh(x) = \frac1n + \frac{(x - \bar x)^2}{S_{xx}}), opening outside the data range; the prediction band barely curves because 11 dominates. With heteroscedasticity, 95 %95\ \% is roughly true averaged over xx but false at each point: band width is nearly constant, but actual noise grows with xx, so coverage is far above 95 %95\ \% at low noise and far below it at high noise, where it matters most. And the simultaneous band is wider than pointwise because it guarantees coverage of the whole line at once, not each point separately: the same logic as multiple testing.

The cell measures by simulation what each interval covers. A frequent mistake is to read confidence as “the range containing 95% of observations”:

[ ]What each interval contains: the mean or a new observationBrowser
rng = np.random.default_rng(6)
n6, R6 = 20, 20000
x6 = np.linspace(0, 10, n6)
X6 = np.column_stack([np.ones(n6), x6])
bt6, s6 = np.array([1.0, 0.8]), 1.5
x0 = np.array([1.0, 9.5])
A6 = np.linalg.pinv(X6)
Y6 = X6 @ bt6 + rng.normal(0, s6, (R6, n6))
Bh6 = Y6 @ A6.T
E6 = Y6 - Bh6 @ X6.T
S6 = np.sqrt((E6 ** 2).sum(1) / (n6 - 2))
h0 = x0 @ np.linalg.inv(X6.T @ X6) @ x0
tq = stats.t.ppf(.975, n6 - 2)
yh = Bh6 @ x0
ci_w, pi_w = tq * S6 * np.sqrt(h0), tq * S6 * np.sqrt(1 + h0)
mu0 = x0 @ bt6
ynew = mu0 + rng.normal(0, s6, R6)
print(f"h(x0) = {h0:.4f};  semianchura media: confianza {ci_w.mean():.3f}, predicción {pi_w.mean():.3f}")
print(f"El IC de la media contiene mu(x0):        {np.mean(np.abs(yh - mu0) <= ci_w):.4f}")
print(f"El IC de la media contiene y_nueva:       {np.mean(np.abs(yh - ynew) <= ci_w):.4f}")
print(f"El IC de predicción contiene y_nueva:     {np.mean(np.abs(yh - ynew) <= pi_w):.4f}")
print(f"límite con n -> infinito: confianza 0, predicción {1.96 * s6:.3f}")

Both intervals deliver: confidence contains the mean 95.1 %95.1\ \% of the time and prediction contains a new observation 95.0 %95.0\ \%. But confidence contains the new observation only 55.8 %55.8\ \% of the time. Used as an “expected latency range,” it excludes nearly half the requests.

Interpreting coefficients: categories, interactions and logarithms

Read a multiple regression coefficient as “expected change in yy per unit of xjx_j, holding other model variables fixed.” This is a statement about conditional association in data, not what happens if one intervenes on xjx_j (the latter is covered by causal versus descriptive regression). Precisely, the Frisch–Waugh–Lovell theorem says β^j\hat\beta_j is the slope of regressing y\vb{y} on the residual of xj\vb{x}_j after removing what other columns explain. The part of xjx_j already explained by other variables contributes nothing to β^j\hat\beta_j. We use this next.

Categorical variables. A variable with kk levels is encoded using k−1k - 1 indicator columns plus intercept (treatment coding): each coefficient is the mean difference between that level and reference, holding everything else fixed. Including all kk indicators and the intercept makes the columns sum to the ones column: X\mat{X} loses rank and β\vb{\beta} ceases to be identifiable (the “dummy variable trap”). Interactions. If the effect of xx varies by group g∈{0,1}g \in \{0, 1\}, add g xg\,x: the coefficient of xx becomes the reference group’s slope, that of g xg\,x the difference in slopes, and that of gg the shift at x=0x = 0, interpretable only if x=0x = 0 lies in the data range (centering xx helps). Logarithms. With log⁡y\log y and log⁡x\log x, slope is an elasticity: 1 %1\ \% more xx is associated with β %\beta\ \% more yy. With log⁡y\log y and xx in levels, a one-unit increase multiplies expected yy by eβ≈1+βe^{\beta} \approx 1 + \beta for small β\beta.

[ ]Encoding categories, interactions and elasticitiesBrowser
rng = np.random.default_rng(6)
m = 200
g = rng.integers(0, 2, m)                                  # 0 = servidor A, 1 = servidor B
xx = rng.uniform(0, 10, m)
yy = 5 + 2 * xx + 3 * g + 1.5 * g * xx + rng.normal(0, 2, m)
ones = np.ones(m)
trampa = np.column_stack([ones, 1 - g, g])
print("trampa de la variable ficticia: rango de [1, d_A, d_B] =", np.linalg.matrix_rank(trampa), "con 3 columnas; número de condición:", f"{np.linalg.cond(trampa):.1e}")
Xi = np.column_stack([ones, xx, g, g * xx])
bi = np.linalg.lstsq(Xi, yy, rcond=None)[0]
print("coeficientes [const, x, g, g*x]:", np.round(bi, 3), "   (verdad: 5, 2, 3, 1.5)")
print(f"pendiente en el servidor A: {bi[1]:.3f}; en el B: {bi[1] + bi[3]:.3f} (la interacción es la DIFERENCIA de pendientes)")
print(f"desplazamiento de B frente a A en x = 0: {bi[2]:.3f}; en x = 5: {bi[2] + 5 * bi[3]:.3f}")
# logaritmos
a_, b_ = 3.0, 0.7
xl = rng.lognormal(2, 0.8, m)
yl = a_ * xl ** b_ * np.exp(rng.normal(0, 0.3, m))
bl = np.polyfit(np.log(xl), np.log(yl), 1)
print(f"\nlog-log: pendiente {bl[0]:.3f} (verdad {b_}): un 1 % más de x se asocia a un {bl[0]:.2f} % más de y")

The “trap” appears in rank (2, not 3) and condition number of order 101510^{15}, practically infinite. The interaction recovers group slopes and shows why the coefficient of gg alone misleads: server B does not “cost 3.13.1” ms more, but 3.09+1.53 x3.09 + 1.53\,x, which at x=5x = 5 is 10.710.7 ms. (Estimates 4.954.95, 1.981.98, 3.093.09 and 1.531.53 are within half a standard error of truth, 55, 22, 33 and 1.51.5. The shift at x=0x = 0 is least well determined, with standard error 0.600.60 versus 0.100.10 for interaction, because x=0x = 0 is at the edge of the range.) With log⁡y\log y and log⁡x\log x, estimated slope is 0.710.71 (truth 0.70.7): 1 %1\ \% more xx is associated with 0.71 %0.71\ \% more yy.

Collinearity and variance inflation factor

Coefficients β^1\hat\beta_1 and β^2\hat\beta_2 of two almost identical predictors cannot be separated: data know only their sum. Measuring this requires an exact coefficient-variance formula.

Proof

Partition X=[Z  xj]\mat{X} = [\mat{Z}\ \ \vb{x}_j] and let x~j=(I−HZ)xj\tilde{\vb{x}}_j = (\mat{I} - \mat{H}_Z)\vb{x}_j be the residual from regressing xj\vb{x}_j on Z\mat{Z}. By block inversion (Schur complement), the corresponding jj diagonal element of (X⊤X)−1(\mat{X}\T\mat{X})\inv is (xj⊤(I−HZ)xj)−1=1/∥x~j∥2(\vb{x}_j\T(\mat{I} - \mat{H}_Z)\vb{x}_j)\inv = 1/\norm{\tilde{\vb{x}}_j}^2. By definition of Rj2R_j^2 (with intercept in Z\mat{Z}), ∥x~j∥2=(1−Rj2) Sjj\norm{\tilde{\vb{x}}_j}^2 = (1 - R_j^2)\,S_{jj}. Substitute into Var⁡(β^j)=σ2[(X⊤X)−1]jj\Var(\hat\beta_j) = \sigma^2[(\mat{X}\T\mat{X})\inv]_{jj}. For the inverse correlation matrix, the same argument on standardized columns gives 1/(1−Rj2)1/(1 - R_j^2). This also yields Frisch–Waugh–Lovell: β^j=x~j⊤y/∥x~j∥2\hat\beta_j = \tilde{\vb{x}}_j\T\vb{y}/\norm{\tilde{\vb{x}}_j}^2, the slope of y\vb{y} on x~j\tilde{\vb{x}}_j.

∎

With VIFj=10\mathrm{VIF}_j = 10, standard error is multiplied by 10≈3.2\sqrt{10} \approx 3.2. Two predictors with correlation ρ\rho have VIF=1/(1−ρ2)\mathrm{VIF} = 1/(1 - \rho^2) (for ρ=0.9\rho = 0.9, 5.35.3; for 0.990.99, 5050). Collinearity does not bias anything or invalidate the model: it inflates each coefficient’s variance separately. What is lost is the ability to allocate effects among variables moving together, so damage concentrates in individual tt tests. The joint FF test retains power against alternatives in the direction data do determine (in the figure, β1+β2\beta_1 + \beta_2), and predictions within the region of similar predictors barely suffer. The figure shows this with a confidence ellipse.

InteractiveCollinearity and the confidence ellipse
95% joint confidence ellipse for (β1,β2)(\beta_1, \beta_2) and experimental replications
H₀: (0, 0)true value
  • 95% joint ellipse
  • CI for β1\beta_1
  • CI for β2\beta_2
  • 150 replications of (β^1,β^2)(\hat\beta_1, \hat\beta_2)
The design: x1x_1 versus x2x_2 (n=40n = 40, ρ=0.90\rho = 0.90)
Standard error of each coefficient: σVIF/(n−1)≈0.367\sigma\sqrt{\mathrm{VIF}/(n-1)} \approx 0.367.
0.90
40
1.0
Variance inflation factor VIF=1/(1−ρ2)\mathrm{VIF} = 1/(1 - \rho^2)5.3
β^1\hat\beta_1 (SE) | t1t_1 | p1p_10.50 (0.37) | 1.36 | 0.182
β^2\hat\beta_2 (SE) | t2t_2 | p2p_20.50 (0.37) | 1.36 | 0.182
Joint FF test of β1=β2=0\beta_1 = \beta_2 = 0 (df 2, 37)18.52 | p < 0.001
Neither β1\beta_1 nor β2\beta_2 is individually significant (p1=0.182p_1 = 0.182 and p2=0.182p_2 = 0.182), but the joint FF test is (F=18.5F = 18.5, pF<0.001p_F < 0.001). The ellipse excludes the origin while each strip contains it: the data indicate that the sum β1+β2\beta_1 + \beta_2 is positive, but not how it is divided between the two.
Two standardized predictors with exact sample correlation ρ\rho, and y=β0+0.5 x1+0.5 x2+εy = \beta_0 + 0.5\,x_1 + 0.5\,x_2 + \varepsilon. The blue ellipse is the joint 95% confidence region for (β1,β2)(\beta_1, \beta_2); orange and aqua strips are separate 95% intervals for each coefficient; gray points are 150 experimental replicates with the same design; the red circle is the origin H0 ⁣:β1=β2=0H_0\!: \beta_1 = \beta_2 = 0. 'Typical sample' projects noise so β^=β\hat{\vb{\beta}} = \vb{\beta} exactly, showing only effects of ρ\rho and nn. Raise ρ\rho from 0 to 0.95: what happens to ellipse and cloud shape? When does the origin fall outside the ellipse but inside both strips? With ρ=0.95\rho = 0.95, how much data is needed for each strip to exclude 0?

The ellipse is the geometric form of Cov⁡(β^)=σ2(X⊤X)−1\Cov(\hat{\vb{\beta}}) = \sigma^2(\mat{X}\T\mat{X})\inv. With orthogonal predictors it is nearly circular; at high ρ\rho it stretches along β1−β2\beta_1 - \beta_2 (where data cannot distinguish) and narrows along β1+β2\beta_1 + \beta_2 (where they can). The replicate cloud has the same shape, confirming it is not a fitting artifact. With ρ=0.9\rho = 0.9, n=40n = 40 and σ=1\sigma = 1, both coefficients have pp-value 0.180.18 (neither significant separately), yet the joint test gives F=18.5F = 18.5, p<0.001p < 0.001: the origin is clearly outside the ellipse. Reading only the pp-value table would conclude “neither x1 nor x2 matters,” when the truth is “one matters, and I do not know which.”

[ ]VIF calculated three waysBrowser
rng = np.random.default_rng(8)
N8 = 200
a1 = rng.normal(size=N8)
a2 = 0.95 * a1 + np.sqrt(1 - 0.95 ** 2) * rng.normal(size=N8)
a3 = rng.normal(size=N8)
Z = np.column_stack([a1, a2, a3])
vif_r2 = []
for j in range(3):
    otros = np.column_stack([np.ones(N8), np.delete(Z, j, axis=1)])
    bj = np.linalg.lstsq(otros, Z[:, j], rcond=None)[0]
    rj = Z[:, j] - otros @ bj
    r2j = 1 - rj @ rj / ((Z[:, j] - Z[:, j].mean()) ** 2).sum()
    vif_r2.append(1 / (1 - r2j))
print("VIF por 1/(1 - R_j^2):          ", np.round(vif_r2, 3))
print("VIF por diag de la inversa de R:", np.round(np.diag(np.linalg.inv(np.corrcoef(Z.T))), 3))
print(f"número de condición de la matriz de diseño estandarizada: {np.linalg.cond((Z - Z.mean(0)) / Z.std(0)):.2f}")

The first two predictors have VIF≈10.4\mathrm{VIF} \approx 10.4 (correlation 0.950.95: 1/(1−0.952)=10.31/(1 - 0.95^2) = 10.3) and the third, independent, 1.01.0. Both formulas agree to three decimals. What to do depends on the question: to predict for x\vb{x} values like those observed, nothing (ridge if stabilization is needed, ridge regression); for a joint effect, use the FF test; to separate effects, only more data or a design decorrelating predictors helps, never a computational trick. VIF 55–1010 is often a warning sign, but not a statistical threshold: resulting standard error is what matters.

Diagnostics: residuals, leverage and influence

The above intervals and tests hold if the model is reasonable. Diagnostics check it is not badly wrong, using residuals and quantities depending only on design.

The first fact to internalize: residuals do not have equal variance even with homoscedastic errors: Var⁡(e)=σ2M\Var(\vb{e}) = \sigma^2\mat{M}, so Var⁡(ei)=σ2(1−hii)\Var(e_i) = \sigma^2(1 - h_{ii}). High-leverage points pull the line toward themselves and leave small residuals; inspecting raw residuals hides them. Leverage properties are 1/n≤hii≤11/n \le h_{ii} \le 1 (lower bound with an intercept), ∑ihii=tr⁡(H)=p\sum_i h_{ii} = \tr(\mat{H}) = p (average p/np/n; hence attention to values above 2p/n2p/n or 3p/n3p/n), and in simple regression hii=1n+(xi−xˉ)2Sxxh_{ii} = \frac1n + \frac{(x_i - \bar x)^2}{S_{xx}}: it depends only on how far xix_i is from center, not yiy_i.

Exact deletion formulas avoid refitting the model nn times:

Proof

Let C=(X⊤X)−1\mat{C} = (\mat{X}\T\mat{X})\inv. Since X(i)⊤X(i)=X⊤X−xixi⊤\mat{X}_{(i)}\T\mat{X}_{(i)} = \mat{X}\T\mat{X} - \vb{x}_i\vb{x}_i\T, Sherman–Morrison (rank-one case of the Woodbury identity) gives (X(i)⊤X(i))−1=C+Cxixi⊤C/(1−hii)(\mat{X}_{(i)}\T\mat{X}_{(i)})\inv = \mat{C} + \mat{C}\vb{x}_i\vb{x}_i\T\mat{C}/(1 - h_{ii}). Since X(i)⊤y(i)=X⊤y−xiyi\mat{X}_{(i)}\T\vb{y}_{(i)} = \mat{X}\T\vb{y} - \vb{x}_i y_i,

β^(i)=[C+Cxixi⊤C1−hii](X⊤y−xiyi)=β^−Cxiyi+Cxiy^i1−hii−hii Cxiyi1−hii=β^−Cxi(yi−y^i)1−hii.\hat{\vb{\beta}}_{(i)} = \Big[\mat{C} + \tfrac{\mat{C}\vb{x}_i\vb{x}_i\T\mat{C}}{1 - h_{ii}}\Big](\mat{X}\T\vb{y} - \vb{x}_i y_i) = \hat{\vb{\beta}} - \mat{C}\vb{x}_i y_i + \tfrac{\mat{C}\vb{x}_i\hat y_i}{1 - h_{ii}} - \tfrac{h_{ii}\,\mat{C}\vb{x}_i y_i}{1 - h_{ii}} = \hat{\vb{\beta}} - \frac{\mat{C}\vb{x}_i(y_i - \hat y_i)}{1 - h_{ii}}.

For RSS(i)\mathrm{RSS}_{(i)}, note fitting without observation ii is equivalent to fitting all observations with an added column di\vb{d}_i equal to 11 at ii and 00 elsewhere (this absorbs observation ii without error). By Frisch–Waugh–Lovell, the reduction in sum of squares from adding di\vb{d}_i is (di⊤My)2/(di⊤Mdi)=ei2/(1−hii)(\vb{d}_i\T\mat{M}\vb{y})^2/(\vb{d}_i\T\mat{M}\vb{d}_i) = e_i^2/(1 - h_{ii}). Then DiD_i follows by substituting the first formula into its definition and using xi⊤Cxi=hii\vb{x}_i\T\mat{C}\vb{x}_i = h_{ii}: Di=ei2hii/[p s2(1−hii)2]=ri2hii/[p(1−hii)]D_i = e_i^2h_{ii}/[p\,s^2(1-h_{ii})^2] = r_i^2h_{ii}/[p(1 - h_{ii})]. The relation between tit_i and rir_i is algebra from s(i)2s^2_{(i)}. Finally, ti2t_i^2 is the FF statistic for testing δ=0\delta = 0 in the model with column di\vb{d}_i and follows F1,n−p−1F_{1,n-p-1} under the model, so ti∼tn−p−1t_i \sim t_{n-p-1}.

∎

Cook’s distance factors influence into two parts: Di=ri2p⋅hii1−hiiD_i = \frac{r_i^2}{p}\cdot\frac{h_{ii}}{1 - h_{ii}}. The first is how misaligned the point is (residual); the second, how far it lies in xx space (leverage). Both are needed. Explore them directly in the figure.

InteractiveLeverage and influence
Thirteen points, one movable: the line with and without it
fixed points: x from 1.2 to 8.9
  • movable point
  • line with it
  • line without it
Studentized residual versus leverage; curves Di=0.5D_i = 0.5 and 11
D = 1D = 0.5large h
  • movable point
  • fixed points
  • Cook's contours
Leverage hiih_{ii} (threshold 2p/n=0.312p/n = 0.31)0.508
Residual eie_i | internally studentized rir_i0.25 | 0.58
Externally studentized residual tit_i0.56
Cook's distance DiD_i0.173
Slope with the point | without it0.702 | 0.673
High leverage, but aligned. It is far away in xx and on the trend: the line passes almost through it, the residual is small, and removing it barely changes the slope (0.67 without it, 0.70 with it). However, it narrows uncertainty in the line: this point is highly informative.
Twelve fixed points (blue) and one movable point (red), dragged, clicked into place or moved with arrow keys. Left: fitted line with the movable point (orange) and without it (dashed gray). Right: studentized residual versus leverage for all thirteen points, with Cook's distance curves D=0.5D = 0.5 and D=1D = 1 and shaded high-leverage region. Press 'far and aligned', then 'far and misaligned': same leverage, what changes in residual, DiD_i, and slope? With 'center and misaligned': is a point with huge residual but central xx influential? Drag it until DiD_i crosses 0.5: in which (x,y)(x, y) region does this happen?

The figure covers all four cases, identified on residual versus leverage: ordinary (left and near zero), outlier without leverage (left and far from zero: large residual, slope barely changes, line shifts slightly and ss inflates), aligned high leverage (right and near zero: line passes through point, which narrows uncertainty), and influential (right and far from zero, beyond Cook curves: pulls the line). With few data there is a nuance: the internally studentized residual is bounded, ri2≤n−pr_i^2 \le n - p, so a central point cannot exceed a certain Cook distance however large its residual (with the figure’s thirteen points and central xx, Di<0.47D_i < 0.47). The practical conclusion: a “distant” point is not a problem just because it is distant, nor is a large residual; the combination matters, detectable using hiih_{ii}, tit_i, DiD_i.

The cell checks the factorization with 30 points and one far, misaligned point, comparing Cook’s distance from its definition (refitting nn times) with the formula:

[ ]Cook's distance by refitting and formulaBrowser
rng = np.random.default_rng(9)
n9 = 30
x9 = rng.uniform(0, 10, n9)
X9 = np.column_stack([np.ones(n9), x9])
y9 = 2 + 0.5 * x9 + rng.normal(0, 1, n9)
x9[-1], y9[-1] = 16, 3                                      # un punto lejano y desalineado
X9[-1, 1] = 16
def fitm(Xm, ym):
    return np.linalg.solve(Xm.T @ Xm, Xm.T @ ym)
b9 = fitm(X9, y9); e9 = y9 - X9 @ b9; p9 = 2
s29 = e9 @ e9 / (n9 - p9)
h9 = np.einsum("ij,jk,ik->i", X9, np.linalg.inv(X9.T @ X9), X9)
D_def = np.empty(n9)
for i in range(n9):                                         # n reajustes: lo que se evita con las fórmulas de eliminación
    keep = np.arange(n9) != i
    bi_ = fitm(X9[keep], y9[keep])
    D_def[i] = np.sum((X9 @ b9 - X9 @ bi_) ** 2) / (p9 * s29)
r9 = e9 / np.sqrt(s29 * (1 - h9))
D_form = r9 ** 2 * h9 / (p9 * (1 - h9))
print(f"suma de apalancamientos: {h9.sum():.6f} (= p = {p9}); media p/n = {p9 / n9:.4f}")
print(f"Cook por reajuste y por fórmula coinciden: {np.allclose(D_def, D_form)}  (máx dif {np.abs(D_def - D_form).max():.1e})")
i = D_form.argmax()
print(f"punto más influyente: i = {i}, h = {h9[i]:.3f}, r = {r9[i]:.2f}, D = {D_form[i]:.3f}; el siguiente mayor D es {np.sort(D_form)[-2]:.3f}")

The distant point has leverage 0.280.28 (four times the 0.0670.067 average) and studentized residual −4.2-4.2, and Cook distance 3.393.39, about sixty times the next point’s (0.0570.057). The formula reproduces refitting to error of order 10−1510^{-15}.

The four standard diagnostic plots each seek a different defect. Residuals versus fitted values: a curve indicates nonlinearity (assumption 1); a funnel, heteroscedasticity (assumption 3). QQ plot of tit_i versus normal: tails or skew (assumption 5). Scale–location (∣ti∣\sqrt{\abs{t_i}} versus y^\hat y): variance versus level. Residual versus leverage with Cook contours: the previous figure. The cell draws them for an intentionally misspecified model (a line fitted to curved data with growing variance) to show each defect and accompanies them with a formal test.

[ ]Four diagnostic plots with a misspecified modelBrowser
import matplotlib.pyplot as plt
from scipy.stats import spearmanr

rng = np.random.default_rng(11)
nd = 150
xd = rng.uniform(0, 10, nd)
yd = 2 + 0.5 * xd + 0.08 * xd ** 2 + (0.3 + 0.25 * xd) * rng.normal(size=nd)   # curvatura y varianza creciente
Xd = np.column_stack([np.ones(nd), xd])                                          # pero ajustamos una RECTA
Qd, _ = np.linalg.qr(Xd)
fit = Qd @ (Qd.T @ yd)
ed = yd - fit
hd = (Qd ** 2).sum(1)
s2d = ed @ ed / (nd - 2)
rd = ed / np.sqrt(s2d * (1 - hd))
td = rd * np.sqrt((nd - 3) / (nd - 2 - rd ** 2))

fig, ax = plt.subplots(2, 2, figsize=(9, 7))
ax[0, 0].scatter(fit, td, s=9, alpha=0.7)
ax[0, 0].axhline(0, color="gray", lw=1)
ax[0, 0].set(title="Residuos frente a ajustados", xlabel="valor ajustado", ylabel="residuo estudentizado externo")
qq = stats.norm.ppf((np.arange(1, nd + 1) - 0.5) / nd)
ax[0, 1].scatter(qq, np.sort(td), s=9, alpha=0.7)
ax[0, 1].plot([-3, 3], [-3, 3], color="gray", lw=1)
ax[0, 1].set(title="QQ normal", xlabel="cuantiles teóricos", ylabel="residuos ordenados")
orden = np.argsort(fit)
ax[1, 0].scatter(fit, np.sqrt(np.abs(td)), s=9, alpha=0.7)
ax[1, 0].plot(fit[orden], np.convolve(np.sqrt(np.abs(td))[orden], np.ones(25) / 25, mode="same"), color="C1", lw=2)
ax[1, 0].set(title="Escala y localización", xlabel="valor ajustado", ylabel="raíz de |residuo|")
ax[1, 1].scatter(hd, td, s=9, alpha=0.7)
ax[1, 1].axhline(0, color="gray", lw=1)
ax[1, 1].set(title="Residuo frente a apalancamiento", xlabel="apalancamiento", ylabel="residuo estudentizado externo")
plt.tight_layout()
plt.show()

X2 = np.column_stack([Xd, xd ** 2])
r2s = np.linalg.lstsq(X2, yd, rcond=None)[0]
rss_q = np.sum((yd - X2 @ r2s) ** 2)
Fq = (ed @ ed - rss_q) / (rss_q / (nd - 3))
print(f"curvatura: F de añadir x^2 = {Fq:.1f}, p = {stats.f.sf(Fq, 1, nd - 3):.1e}")
print(f"heterocedasticidad: Spearman entre |t_i| y x = {spearmanr(np.abs(td), xd)[0]:.2f} (p = {spearmanr(np.abs(td), xd)[1]:.1e})")
print(f"apalancamiento máximo {hd.max():.3f} frente a 2p/n = {4 / nd:.3f}; |t_i| máximo {np.abs(td).max():.2f}")

Both defects are clear: residuals form a ∪\cup (the line underestimates extremes), the funnel opens right and scale–location curve rises, and QQ departs from the diagonal in tails. The FF test for adding x2x^2 confirms it (F=27.1F = 27.1, p≈6×10−7p \approx 6 \times 10^{-7}), as does Spearman correlation between ∣ti∣\abs{t_i} and xx (0.400.40, p≈5×10−7p \approx 5 \times 10^{-7}). Uniform design has no high-leverage points (maximum 0.0280.028 barely exceeds 2p/n=0.0272p/n = 0.027). A plot without a pattern does not prove correctness, only that this analysis did not find what it sought. Three professional rules: if a point is removed for influence, report fits with and without it; if testing the largest residual, comparison with tn−p−1t_{n-p-1} must account for inspecting nn residuals (Bonferroni, tn−p−1, 1−α/(2n)t_{n-p-1,\,1-\alpha/(2n)}; disguised multiple testing); and legitimate influential points are data the model does not understand, not garbage to discard.

When assumptions fail: sandwich standard errors and bootstrap

When error variance is not constant (the most common failure), least squares remains unbiased and consistent, but σ2(X⊤X)−1\sigma^2(\mat{X}\T\mat{X})\inv is no longer its variance. With independent errors and Var⁡(εi)=σi2\Var(\varepsilon_i) = \sigma_i^2, correct variance is

Var⁡(β^)=(X⊤X)−1(∑iσi2 xixi⊤)(X⊤X)−1,\Var(\hat{\vb{\beta}}) = (\mat{X}\T\mat{X})\inv\Big(\sum_i \sigma_i^2\,\vb{x}_i\vb{x}_i\T\Big)(\mat{X}\T\mat{X})\inv,

the sandwich form of the M-estimator variance from lesson 8: “bread” is (X⊤X)−1(\mat{X}\T\mat{X})\inv and “filling” is score variance. Estimate it by replacing each σi2\sigma_i^2 with a version of squared residual, V^HC=(X⊤X)−1(∑iωiei2xixi⊤)(X⊤X)−1\hat{\vb{V}}_{\mathrm{HC}} = (\mat{X}\T\mat{X})\inv\big(\sum_i \omega_i e_i^2\vb{x}_i\vb{x}_i\T\big)(\mat{X}\T\mat{X})\inv. Each ei2e_i^2 is a poor estimator of σi2\sigma_i^2 (inconsistent from one observation), but the weighted sum converges, which supports the method (White, 1980). Variants differ by weight ωi\omega_i:

Variantωi\omega_iIdea
HC011White’s sandwich; downward bias at small nn
HC1n/(n−p)n/(n - p)degrees-of-freedom correction
HC21/(1−hii)1/(1 - h_{ii})unbiased under homoscedasticity, because E[ei2]=σ2(1−hii)\E[e_i^2] = \sigma^2(1 - h_{ii})
HC31/(1−hii)21/(1 - h_{ii})^2approximates jackknife; most conservative of HC0, HC2 and HC3, recommended by default at moderate nn (MacKinnon and White, 1985; Long and Ervin, 2000)

Bootstrap offers another route, and the previous resampling lesson, nonparametric bootstrap, leaves a regression question: what is resampled? There are three answers under different assumptions.

Wild bootstrap is not merely clever: it contains the sandwich.

Proof

A replicate is β^∗=(X⊤X)−1X⊤y∗=β^+(X⊤X)−1∑ixi eivi\hat{\vb{\beta}}^\ast = (\mat{X}\T\mat{X})\inv\mat{X}\T\vb{y}^\ast = \hat{\vb{\beta}} + (\mat{X}\T\mat{X})\inv\sum_i \vb{x}_i\,e_i v_i, because X⊤Xβ^\mat{X}\T\mat{X}\hat{\vb{\beta}} cancels. Conditional on data, E∗[vi]=0\E^\ast[v_i] = 0 and E∗[vivk]=δik\E^\ast[v_iv_k] = \delta_{ik}, so Cov⁡∗(∑ixieivi)=∑iei2xixi⊤\Cov^\ast\big(\sum_i \vb{x}_ie_iv_i\big) = \sum_i e_i^2\vb{x}_i\vb{x}_i\T.

∎

The cell checks this with 100,000 replicates under strongly increasing variance, where the difference from classical standard error is already visible:

[ ]Rademacher wild bootstrap is the HC0 sandwichBrowser
rng = np.random.default_rng(10)
n10 = 40
x10 = rng.uniform(0, 10, n10)
X10 = np.column_stack([np.ones(n10), x10])
y10 = 1 + 0.8 * x10 + rng.normal(0, 0.2 + 0.1 * x10 ** 2)
Ainv = np.linalg.inv(X10.T @ X10)
b10 = Ainv @ X10.T @ y10
e10 = y10 - X10 @ b10
hc0 = Ainv @ (X10.T * e10 ** 2) @ X10 @ Ainv
v = rng.choice([-1.0, 1.0], size=(100000, n10))               # pesos de Rademacher
Bw = b10 + (v * e10) @ (X10 @ Ainv)                           # beta* = beta_hat + (X'X)^-1 X' (e * v)
print("HC0 (sándwich):\n", np.round(hc0, 4))
print("covarianza del bootstrap salvaje (100000 réplicas):\n", np.round(np.cov(Bw.T), 4))
print(f"EE de la pendiente: clásico {np.sqrt((e10 @ e10 / (n10 - 2)) * Ainv[1, 1]):.4f}, HC0 {np.sqrt(hc0[1, 1]):.4f}, salvaje {Bw[:, 1].std():.4f}")

Slope standard error is 0.23250.2325 with the classical formula and 0.26530.2653 with HC0 (14 %14\ \% higher because noise grows where xx leverage is greatest); wild bootstrap gives 0.26520.2652 and its full covariance matrix agrees with the sandwich to a few thousandths (0.64750.6475 versus 0.64920.6492 for intercept variance), the Monte Carlo error of 10510^5 replicates.

Which default method? A simulation study

The honest answer to “which method?” is it depends, and a simulation study measures what it depends on. Follow ADEMP from simulation studies. Aim: coverage and width of 95% slope intervals. Data-generating mechanism: y=1+2x+σ(x) εy = 1 + 2x + \sigma(x)\,\varepsilon with x∼lognormal(0,0.62)x \sim \mathrm{lognormal}(0, 0.6^2), one homoscedastic scenario (σ=1.5\sigma = 1.5) and one heteroscedastic (σ(x)=0.4+0.8 x\sigma(x) = 0.4 + 0.8\,x), with n=30n = 30 and n=100n = 100. Estimand: true slope, 22. Methods: classic tt interval, HC0 with normal quantiles, HC3 with tn−pt_{n-p} quantiles, pairs bootstrap and Rademacher wild bootstrap, both percentile with B=299B = 299 replicates, and studentized wild bootstrap (quantiles of t∗t^\ast with HC0 standard error). Performance measures: coverage and mean width over 300300 replicates, so each coverage has Monte Carlo error about 1.31.3 points.

[ ]Coverage of six slope inference methods, n = 30Browser
def datos(rng, n, hetero):
    x = rng.lognormal(0, 0.6, n)
    sd = 0.4 + 0.8 * x if hetero else np.full(n, 1.5)
    y = 1 + 2 * x + sd * rng.normal(size=n)
    return np.column_stack([np.ones(n), x]), y

def intervalos(X, y, rng, B=299, alpha=0.05):
    n, p = X.shape
    C = np.linalg.inv(X.T @ X)
    A = C @ X.T                                                        # beta_hat = A y
    b = A @ y
    e = y - X @ b
    h = np.einsum("ij,jk,ik->i", X, C, X)
    tq, zq = stats.t.ppf(1 - alpha / 2, n - p), stats.norm.ppf(1 - alpha / 2)
    sandwich = lambda w: np.sqrt((C @ ((X.T * (w * e ** 2)) @ X) @ C)[1, 1])
    se_cl, se0, se3 = np.sqrt(e @ e / (n - p) * C[1, 1]), sandwich(1.0), sandwich(1 / (1 - h) ** 2)
    out = {"clásico": (b[1] - tq * se_cl, b[1] + tq * se_cl),
           "HC0": (b[1] - zq * se0, b[1] + zq * se0),
           "HC3": (b[1] - tq * se3, b[1] + tq * se3)}
    idx = rng.integers(0, n, (B, n))                                   # pares: remuestrear filas (x_i, y_i)
    Xb, yb = X[idx], y[idx]
    bb = np.linalg.solve(np.einsum("bni,bnj->bij", Xb, Xb), np.einsum("bni,bn->bi", Xb, yb)[..., None])[:, 1, 0]
    out["pares"] = tuple(np.quantile(bb, [alpha / 2, 1 - alpha / 2]))
    ve = rng.choice([-1.0, 1.0], (B, n)) * e                           # salvaje: y* = X beta_hat + e_i v_i
    bw = b[1] + ve @ A[1]
    out["salvaje"] = tuple(np.quantile(bw, [alpha / 2, 1 - alpha / 2]))
    estar = ve - (ve @ X) @ A                                          # residuos del ajuste de cada y*
    tstar = (bw - b[1]) / np.sqrt((estar ** 2) @ (A[1] ** 2))          # estudentizado con HC0
    qlo, qhi = np.quantile(tstar, [alpha / 2, 1 - alpha / 2])
    out["salvaje-t"] = (b[1] - qhi * se0, b[1] - qlo * se0)
    return out

def simula(hetero, n, R=300, seed=2024):
    rng = np.random.default_rng(seed)
    cub, anc = {}, {}
    for _ in range(R):
        X, y = datos(rng, n, hetero)
        for k, (lo, hi) in intervalos(X, y, rng).items():
            cub[k] = cub.get(k, 0) + (lo <= 2.0 <= hi)
            anc[k] = anc.get(k, 0) + (hi - lo)
    print(f"{'heterocedástico' if hetero else 'homocedástico'}, n = {n}")
    for k in cub:
        print(f"  {k:10s} cobertura {cub[k] / R:.3f}  anchura media {anc[k] / R:.3f}")

simula(False, 30)
simula(True, 30)
[ ]Coverage of six slope inference methods, n = 100Browser
simula(True, 100)

Results are fairly clear, though not to be overinterpreted (one generating mechanism, strong leverage from the lognormal tail). With homoscedasticity, the classical interval is best (96 %96\ \% with n=30n = 30, somewhat conservative), and robust methods pay a small price: HC3 (94 %94\ \%) with intervals 9 %9\ \% wider, pairs (94 %94\ \%) with equal width, and HC0, wild percentile and studentized wild fall short (9090 to 91 %91\ \%). With heteroscedasticity, the classical interval collapses (75 %75\ \% with n=30n = 30 and 67 %67\ \% with n=100n = 100: increasing nn does not fix it and even worsens it, because error is an incorrect formula, not small sample), and simple percentile wild gives 78 %78\ \% and 83 %83\ \%. HC3 (91 %91\ \% and 93 %93\ \%), pairs (89 %89\ \% and 91 %91\ \%) and studentized wild (87 %87\ \% and 91 %91\ \%) come closest to nominal, with correspondingly wider intervals: the short classical interval was short from optimism. None reaches 95 %95\ \% with such extreme leverage and n≤100n \le 100.

This yields a reasoned rule, not dogma. By default report HC3 standard errors (with tn−pt_{n-p} quantiles), because they cost little under homoscedasticity and rescue coverage under heteroscedasticity. Use bootstrap when the statistic is not a coefficient (coefficient ratio, point prediction, R2R^2) or nn is small: use pairs if design is random and studentized wild if conditioning on X\mat{X}; not residual or simple percentile wild if heteroscedasticity is suspected. Always inspect residuals: variance robustness does not fix nonlinearity or omitted variables.

With libraries: the statsmodels summary, line by line

So far each formula had its own cell. The following implementation combines everything in a QR least-squares class, without forming or inverting X⊤X\mat{X}\T\mat{X} during fitting, and checks against statsmodels, what will be used in practice.

[ ]Least squares with inference, from scratch and by QRBrowser
from scipy.linalg import solve_triangular

class MCO:
    """Mínimos cuadrados por QR. X debe llevar la columna de unos como primera columna."""
    def __init__(self, X, y):
        self.X, self.y = np.asarray(X, float), np.asarray(y, float)
        self.n, self.p = self.X.shape
        self.df = self.n - self.p
        self.Q, self.R = np.linalg.qr(self.X)                      # X = Q R
        self.beta = solve_triangular(self.R, self.Q.T @ self.y)     # R beta = Q' y
        self.fitted = self.Q @ (self.Q.T @ self.y)                  # H y sin construir H
        self.resid = self.y - self.fitted
        self.rss = self.resid @ self.resid
        self.s2 = self.rss / self.df
        Ri = solve_triangular(self.R, np.eye(self.p))
        self.XtXi = Ri @ Ri.T                                       # (X'X)^-1 = R^-1 R^-T
        self.se = np.sqrt(self.s2 * np.diag(self.XtXi))
        self.h = (self.Q ** 2).sum(axis=1)                          # h_ii = norma al cuadrado de la fila i de Q
        self.tss = ((self.y - self.y.mean()) ** 2).sum()

    def t(self):
        return self.beta / self.se
    def pvalues(self):
        return 2 * stats.t.sf(np.abs(self.t()), self.df)
    def conf_int(self, alpha=0.05):
        q = stats.t.ppf(1 - alpha / 2, self.df)
        return np.column_stack([self.beta - q * self.se, self.beta + q * self.se])
    def r2(self):
        return 1 - self.rss / self.tss
    def r2_adj(self):
        return 1 - (1 - self.r2()) * (self.n - 1) / self.df
    def f_global(self):
        F = ((self.tss - self.rss) / (self.p - 1)) / self.s2
        return F, stats.f.sf(F, self.p - 1, self.df)
    def f_nested(self, quitar):
        """Test F de H0: los coeficientes de las columnas `quitar` son cero."""
        sub = MCO(np.delete(self.X, quitar, axis=1), self.y)
        q = len(quitar)
        F = ((sub.rss - self.rss) / q) / self.s2
        return F, stats.f.sf(F, q, self.df), q
    def predict(self, x0, alpha=0.05):
        x0 = np.asarray(x0, float)
        mu = x0 @ self.beta
        h0 = x0 @ self.XtXi @ x0
        q, s = stats.t.ppf(1 - alpha / 2, self.df), np.sqrt(self.s2)
        return mu, (mu - q * s * np.sqrt(h0), mu + q * s * np.sqrt(h0)), (mu - q * s * np.sqrt(1 + h0), mu + q * s * np.sqrt(1 + h0))
    def influence(self):
        r = self.resid / np.sqrt(self.s2 * (1 - self.h))                       # estudentizado interno
        s2_i = (self.rss - self.resid ** 2 / (1 - self.h)) / (self.df - 1)     # sigma^2 sin la observación i
        t = self.resid / np.sqrt(s2_i * (1 - self.h))                          # estudentizado externo
        D = r ** 2 * self.h / (self.p * (1 - self.h))                          # Cook
        return r, t, D
    def hc3(self):
        meat = (self.X.T * (self.resid ** 2 / (1 - self.h) ** 2)) @ self.X
        return self.XtXi @ meat @ self.XtXi
    def loglik(self):
        return -0.5 * self.n * (np.log(2 * np.pi) + np.log(self.rss / self.n) + 1)

m = MCO(X, y)
print(f"{'':10s} {'coef':>9s} {'std err':>9s} {'t':>8s} {'P>|t|':>8s} {'[0.025':>9s} {'0.975]':>9s}")
ci95 = m.conf_int()
for j, nm in enumerate(names):
    print(f"{nm:10s} {m.beta[j]:9.4f} {m.se[j]:9.3f} {m.t()[j]:8.3f} {m.pvalues()[j]:8.3f} {ci95[j, 0]:9.3f} {ci95[j, 1]:9.3f}")
F_g, pF_g = m.f_global()
print(f"\nR2 {m.r2():.3f}   R2 ajustado {m.r2_adj():.3f}   F {F_g:.2f}   Prob(F) {pF_g:.2e}   gl residuales {m.df}")
[ ]Reproduce statsmodels summary number by numberBrowser
import statsmodels.api as sm

res = sm.OLS(y, X).fit()
print(res.summary(xname=names))

Read top to bottom: every cell has a formula from the lesson. Left header: R-squared is R2=1−RSS/TSSR^2 = 1 - \mathrm{RSS}/\mathrm{TSS} and Adj. R-squared adjusted; F-statistic and Prob (F-statistic) are the global test (the FF test with intercept-only M0\mathcal{M}_0); Df Residuals is n−pn - p and Df Model is p−1p - 1. Right header: Log-Likelihood is −n2[log⁡2π+log⁡(RSS/n)+1]-\frac n2[\log 2\pi + \log(\mathrm{RSS}/n) + 1], Gaussian likelihood at its maximum (using the MLE of σ2\sigma^2, not s2s^2); AIC and BIC are −2ℓ+2p-2\ell + 2p and −2ℓ+plog⁡n-2\ell + p\log n. Coefficient table: coef is β^\hat{\vb{\beta}}; std err is scjjs\sqrt{c_{jj}}; t their ratio; P>|t| the two-sided pp-value with tn−pt_{n-p}; and the last two are interval β^j±tn−p,0.975 EE\hat\beta_j \pm t_{n-p,0.975}\,\mathrm{EE}. Footer: Omnibus and Jarque-Bera test residual normality (skewness and kurtosis), Durbin-Watson first-order autocorrelation (≈2\approx 2 if absent), and Cond. No. is κ(X)\kappa(\mat{X}), the numerical collinearity alarm. Note [1] is most important and least read: standard errors assume the error covariance is correctly specified; these are assumptions 3 and 4 in the initial table.

The custom class and statsmodels should agree to rounding error for every quantity in the lesson, including those summary does not print:

[ ]Full comparison, including prediction intervals and influenceBrowser
ll = m.loglik()
dif = lambda a, b: float(np.max(np.abs(np.asarray(a) - np.asarray(b))))
infl = res.get_influence()
r_in, t_ex, D = m.influence()
x0 = np.array([1.0, 25.0, 1.0, 5.0])
mu, ci, pi = m.predict(x0)
sf = res.get_prediction(x0[None, :]).summary_frame(alpha=0.05)
Fn, pn, qn = m.f_nested([1, 2])
fa = res.compare_f_test(sm.OLS(y, X[:, [0, 3]]).fit())
res3 = sm.OLS(y, X).fit(cov_type="HC3")
filas = [
    ("coeficientes", dif(m.beta, res.params)),
    ("errores estándar", dif(m.se, res.bse)),
    ("estadísticos t", dif(m.t(), res.tvalues)),
    ("valores p", dif(m.pvalues(), res.pvalues)),
    ("intervalos de confianza", dif(m.conf_int(), res.conf_int())),
    ("R2 y R2 ajustado", dif([m.r2(), m.r2_adj()], [res.rsquared, res.rsquared_adj])),
    ("F global y su p", dif([F_g, pF_g], [res.fvalue, res.f_pvalue])),
    ("log-verosimilitud, AIC, BIC", dif([ll, -2 * ll + 2 * m.p, -2 * ll + np.log(m.n) * m.p], [res.llf, res.aic, res.bic])),
    ("F de anidados", dif([Fn, pn, qn], [fa[0], fa[1], fa[2]])),
    ("IC de la media", dif(ci, [sf["mean_ci_lower"][0], sf["mean_ci_upper"][0]])),
    ("IC de predicción", dif(pi, [sf["obs_ci_lower"][0], sf["obs_ci_upper"][0]])),
    ("apalancamientos", dif(m.h, infl.hat_matrix_diag)),
    ("estudentizados internos", dif(r_in, infl.resid_studentized_internal)),
    ("estudentizados externos", dif(t_ex, infl.resid_studentized_external)),
    ("distancia de Cook", dif(D, infl.cooks_distance[0])),
    ("errores estándar HC3", dif(np.sqrt(np.diag(m.hc3())), res3.bse)),
]
print(f"{'cantidad':28s} máx |propio - statsmodels|")
for nom, d in filas:
    print(f"{nom:28s} {d:.2e}")
print(f"\nEE clásico y HC3 de 'caché': {m.se[2]:.3f} y {np.sqrt(m.hc3()[2, 2]):.3f}")

All sixteen quantities agree to rounding error (largest difference is order 4×10−144 \times 10^{-14}). A deeper detail: statsmodels also avoids normal equations; by default it solves with the pseudoinverse of X\mat{X} (based on SVD), for the same numerical reason. With service data, HC3 standard error for caché barely differs from classical (2.242.24 versus 2.152.15): noise is homoscedastic by construction. Robustness is nearly free here. Obtain the robust version with fit(cov_type="HC3"); pairs bootstrap must be written, as in the simulation study.

Common mistakes

Exercises

ProofGauss–Markov for a linear combination
Prove: Let y=Xβ+ε\vb{y} = \mat{X}\vb{\beta} + \vb{\varepsilon}, with X\mat{X} of rank pp, E[ε]=0\E[\vb{\varepsilon}] = \vb{0} and Var⁡(ε)=σ2I\Var(\vb{\varepsilon}) = \sigma^2\mat{I}. If a⊤y\vb{a}\T\vb{y} unbiasedly estimates c⊤β\vb{c}\T\vb{\beta}, then Var⁡(a⊤y)≥Var⁡(c⊤β^)\Var(\vb{a}\T\vb{y}) \ge \Var(\vb{c}\T\hat{\vb{\beta}}), with equality only if a⊤y=c⊤β^\vb{a}\T\vb{y} = \vb{c}\T\hat{\vb{\beta}}.
0
Unlike the lesson's route, decompose the estimator into least squares plus a part uncorrelated with it, rather than using the full matrix A\mat{A}. Let a0=X(X⊤X)−1c\vb{a}_0 = \mat{X}(\mat{X}\T\mat{X})\inv\vb{c}, so c⊤β^=a0⊤y\vb{c}\T\hat{\vb{\beta}} = \vb{a}_0\T\vb{y}, and d=a−a0\vb{d} = \vb{a} - \vb{a}_0.

Step 1 of 5. What does unbiasedness of a⊤y\vb{a}\T\vb{y} for c⊤β\vb{c}\T\vb{\beta} for every β\vb{\beta} imply?

ProofThe distribution of beta_hat and s² by the algebraic route
Prove: Under the Gaussian linear model, β^∼N(β,σ2(X⊤X)−1)\hat{\vb{\beta}} \sim \Normal(\vb{\beta}, \sigma^2(\mat{X}\T\mat{X})\inv), RSS/σ2∼χn−p2\mathrm{RSS}/\sigma^2 \sim \chi^2_{n-p}, and the two quantities are independent.
0
The lesson proved this with an orthonormal basis completed by Q2\mat{Q}_2. Now use matrices H=X(X⊤X)−1X⊤\mat{H} = \mat{X}(\mat{X}\T\mat{X})\inv\mat{X}\T and M=I−H\mat{M} = \mat{I} - \mat{H}, symmetric and idempotent, with MX=0\mat{M}\mat{X} = \mat{0} and tr⁡(M)=n−p\tr(\mat{M}) = n - p.

Step 1 of 5. Express β^−β\hat{\vb{\beta}} - \vb{\beta} and residual vector e\vb{e} in terms of ε\vb{\varepsilon}.

NumericAn F test for nested models
Compare two models with n=60n = 60. The full model has 5 parameters and RSS1=120\mathrm{RSS}_1 = 120. The nested model has 3 parameters and RSS0=150\mathrm{RSS}_0 = 150. What is the FF statistic?
NumericHow much is variance inflated?
Regressing a predictor on all others gives Rj2=0.9R_j^2 = 0.9. What is its variance inflation factor?
NumericPrediction interval half-width
In simple regression with n=22n = 22 observations, s=3s = 3 ms. At point x0x_0 leverage is h0=0.1h_0 = 0.1. What is the half-width (ms) of the 95% prediction interval for a new observation at x0x_0? Use t20, 0.975=2.086t_{20,\,0.975} = 2.086.
CodeStudentized residuals and Cook's distance without refitting
Complete diagnosticos(X, y), which receives design matrix X (including the ones column) and response y, returning four vectors (h, r, t, D): leverage hiih_{ii}, internally studentized residuals rir_i, externally studentized residuals tit_i, and Cook's distances DiD_i. Do not refit the model $n$ times: use deletion formulas (with s(i)2=(RSS−ei2/(1−hii))/(n−p−1)s_{(i)}^2 = (\mathrm{RSS} - e_i^2/(1 - h_{ii}))/(n - p - 1), ti=ei/(s(i)1−hii)t_i = e_i/(s_{(i)}\sqrt{1 - h_{ii}}) and Di=ri2hii/(p(1−hii))D_i = r_i^2 h_{ii}/(p(1 - h_{ii}))). Compute leverage using QR without constructing the n×nn \times n matrix.
import numpy as np

def diagnosticos(X, y):
  """Devuelve (h, r, t, D): apalancamiento, estudentizado interno, estudentizado externo y distancia de Cook."""
  X = np.asarray(X, dtype=float)
  y = np.asarray(y, dtype=float)
  n, p = X.shape
  # tu código: QR de X, ajuste, residuos, h, s2, r, s2 sin la observación i, t y D
  h = np.zeros(n)
  r = np.zeros(n)
  t = np.zeros(n)
  D = np.zeros(n)
  return h, r, t, D
Shift+Enter to run
QuizReading a log model with interaction
A team fits ln⁡(tiempo)=a+0.8 ln⁡(taman˜o)+0.3 B+0.5 B⋅ln⁡(taman˜o)+ε\ln(\text{tiempo}) = a + 0.8\,\ln(\text{tamaño}) + 0.3\,B + 0.5\,B\cdot\ln(\text{tamaño}) + \varepsilon, where B=1B = 1 for server B and 00 for A. Which interpretation is correct?
QuizWhat do you tell the on-call team?
The service model estimates expected latency of 42 ms for 5 KB cache-hit requests at average load, with 95% confidence interval [40,44][40, 44]. An on-call engineer concludes: '95% of those requests take between 40 and 44 ms.' With s=12s = 12 ms and large nn, what is correct?
QuizNonnormal residuals with large n
With n=500n = 500 observations and skewed errors of finite constant variance, the residual QQ plot clearly curves. What can still be claimed?

Summary

Key idea
The Gaussian linear model is one of few with exact estimator distributions: β^∼N(β,σ2(X⊤X)−1)\hat{\vb{\beta}} \sim \Normal(\vb{\beta}, \sigma^2(\mat{X}\T\mat{X})\inv) independently of s2s^2, with RSS/σ2∼χn−p2\mathrm{RSS}/\sigma^2 \sim \chi^2_{n-p}. From these follow tt and FF tests and confidence and prediction intervals; Gauss–Markov guarantees optimality among linear unbiased estimators without normality; diagnostics (leverage, studentized residuals, Cook’s distance), collinearity and robust standard errors reveal when and how assumptions fail.
  • Model and assumptions. y=Xβ+ε\vb{y} = \mat{X}\vb{\beta} + \vb{\varepsilon}, with ε∼N(0,σ2I)\vb{\varepsilon} \sim \Normal(\vb{0}, \sigma^2\mat{I}). Each conclusion uses a subset: unbiasedness (linearity and exogeneity), variance and Gauss–Markov (plus spherical errors), exact tt and FF (plus normality). Exogeneity determines whether coefficients admit causal reading and is untestable.
  • Least squares. Orthogonal projection of y\vb{y} onto col⁡(X)\col(\mat{X}) and MLE under Gaussian errors. s2=RSS/(n−p)s^2 = \mathrm{RSS}/(n-p) is unbiased; RSS/n\mathrm{RSS}/n is MLE and underestimates. Calculate using QR, not (X⊤X)−1(\mat{X}\T\mat{X})\inv.
  • Exact distribution. Tj=(β^j−βj)/EE(β^j)∼tn−pT_j = (\hat\beta_j - \beta_j)/\mathrm{EE}(\hat\beta_j) \sim t_{n-p}; interval β^j±tn−p,1−α/2 scjj\hat\beta_j \pm t_{n-p,1-\alpha/2}\,s\sqrt{c_{jj}}. Coefficients are correlated with matrix σ2(X⊤X)−1\sigma^2(\mat{X}\T\mat{X})\inv.
  • Gauss–Markov. Least squares has smallest variance among linear unbiased estimators (proof using A=(X⊤X)−1X⊤+D\mat{A} = (\mat{X}\T\mat{X})\inv\mat{X}\T + \mat{D}, DX=0\mat{D}\mat{X} = \mat{0}). It does not compete with biased estimators (ridge, shrinkage), or nonlinear ones with heavy-tailed errors, or say anything without homoscedasticity.
  • FF test. F=(RSS0−RSS1)/qRSS1/(n−p1)∼Fq,n−p1F = \frac{(\mathrm{RSS}_0 - \mathrm{RSS}_1)/q}{\mathrm{RSS}_1/(n - p_1)} \sim F_{q,n-p_1} under H0H_0; the exact likelihood-ratio test (−2log⁡Λ=nlog⁡(1+qn−p1F)-2\log\Lambda = n\log(1 + \frac{q}{n-p_1}F)). With q=1q = 1, F=t2F = t^2; adjusted R2R^2 rises if and only if F>1F > 1.
  • Confidence and prediction. y^0±t sh0\hat y_0 \pm t\,s\sqrt{h_0} for the mean, y^0±t s1+h0\hat y_0 \pm t\,s\sqrt{1 + h_0} for a new observation. The former collapses with nn; the latter tends to ±1.96 σ\pm 1.96\,\sigma and depends on normality and homoscedasticity. The Working–Hotelling simultaneous band uses pF\sqrt{pF}.
  • Interpretation. Coefficients are conditional associations (Frisch–Waugh–Lovell). Encode categorical variables with k−1k - 1 indicators, interaction as slope difference, log-log as elasticity.
  • Collinearity. Var⁡(β^j)=σ2 VIFj/Sjj\Var(\hat\beta_j) = \sigma^2\,\mathrm{VIF}_j/S_{jj} with VIFj=1/(1−Rj2)\mathrm{VIF}_j = 1/(1 - R_j^2). It inflates individual standard errors and stretches the confidence ellipse diagonally; it does not bias, and joint FF retains power in the data-determined direction.
  • Diagnostics. ∑ihii=p\sum_i h_{ii} = p; rir_i and tit_i correct unequal residual variance; Di=ri2phii1−hiiD_i = \frac{r_i^2}{p}\frac{h_{ii}}{1 - h_{ii}} requires leverage and misalignment; deletion formulas avoid refitting nn times.
  • Robustness. HC0 through HC3 replace σi2\sigma_i^2 by squared residuals (HC3 by default); pairs, residual and wild bootstrap resample different things, and Rademacher wild reproduces HC0. Under heteroscedasticity more data do not fix the classical interval.