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
- 05Maximum likelihood estimator (MLE)Normal sampling theory: chi-squared, Student t and F distributionsConfidence interval and coveragePrediction intervalHypothesis testGeneralized likelihood ratio testSandwich variance estimatorNonparametric bootstrapQuantile-quantile plot
- 02Projection matrixOrthogonal projectionColumn spaceRankMatrix inverseQR decomposition
- 04Multivariate Gaussian distributionAffine transformations of Gaussians
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.
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 ms, with standard error ms. That figure, , comes from one sample and a formula, and resembles the result of repeating the experiment five thousand times (; with true , ). 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 , we would not know whether 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.
Three readings of the figure that the lesson will prove:
- Lines rotate like a door. All pass near and spread out farther away. Uncertainty of the line at is smallest at , where it is , and grows with : extrapolation is costly, and the formula says how much.
- Three levers control slope precision: less noise , more data , and, often forgotten, more dispersion in . With , the slope’s standard deviation is . Experimental design is largely choosing the values.
- The form is exactly normal. Not asymptotically: it is so even with , provided noise is normal. This exactness is the Gaussian model’s gift and permits use of the 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 and ? From it come tests, intervals, and the 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 (, and ), 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 parameters, and is identifiable exactly when : if columns are linearly dependent, some have , both producing the same distribution. “Linear” means linear in , not variables: a column can be , 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:
- Linearity and exogeneity: , i.e. .
- Full rank: .
- Homoscedasticity: is equal for all .
- Uncorrelated errors (independent under the Gaussian model): if .
- Normality: .
| Assumptions satisfied | What can be claimed |
|---|---|
| 1 and 2 | is unbiased. Nothing about its variance. |
| 1 through 4 (“spherical” errors) | , unbiased, and Gauss–Markov theorem. |
| 1 through 5 | Exact distribution of , , and tests, exact confidence and prediction intervals. is the MLE and minimum-variance unbiased estimator. |
| 1 through 4 with independent errors, without 5, large | and 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 | 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, estimates something else and no -value reveals it. We return to this in common mistakes.
Least squares: projection and maximum likelihood
Proof
(1) Normal equations say is orthogonal to . For any , and the terms are orthogonal, so Pythagoras gives , minimal only if , i.e. because has independent columns. (2) Log-likelihood is
For any fixed it is maximized over by minimizing , so . Differentiating with respect to gives , i.e. . (3) , because and hence , and is symmetric and idempotent. Thus , since (projection trace).
∎The geometry is least squares in observation space : lives in , the model is the -dimensional subspace generated by the columns, and the fit is the shadow of on it. The 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 by solving the normal equations with an explicit inverse squares the condition number, . The alternative is : with having orthonormal columns and triangular, solves triangular system , and needs no inverse. The cell checks the theorem’s facts with service data and maximizes likelihood blindly from scratch to see agreement.
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 without knowing least squares, reaches the same four coefficients. The MLE variance, , is times unbiased : MLE underestimates because fitting has “spent” 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 .
Proof
Complete the orthonormal columns of to an orthogonal matrix of (, ). Since is an orthogonal linear transformation, (Gaussian affine transformation). Its two blocks, and , are therefore independent standard Gaussians.
(1) , an affine transformation of : Gaussian with mean and covariance .
(2) Residuals are , so .
(3) is a function of and is a function of , and .
(4) The standardized numerator, , is by (1). Dividing by , which by (2) is the square root of divided by its degrees of freedom and independent by (3), gives the definition of .
∎The final proof exercise offers another, algebraic route to (1)–(3). The geometry is the same: the part of inside the model determines , the outside part determines , and the parts are independent because they are orthogonal projections of a spherical Gaussian vector.
From (4) construct intervals and tests together. The level- confidence interval for is
and the test of rejects when ; by test–interval duality from lesson 10, this coincides with 0 lying outside the interval. Full covariance is : coefficients are not independent of one another, and that correlation will star in collinearity. First, a simulation check with small size (, ), where using instead of makes a difference.
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 statistic has exactly (the Kolmogorov–Smirnov test does not distinguish the simulated sample from it), and the quantile is , not . With normal, a “5%” test would reject a true null of the time. Normalized residual sum of squares has the mean and variance of , is independent of (correlation , within Monte Carlo error ), and coefficients are correlated with each other (, versus theory ).
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 be unbiased: for all , so . Write . Then , so . Variance is
Matrix is positive semidefinite (), proving the claim. For fixed , , zero only if , i.e. .
∎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 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, 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 , least squares remains unbiased but is no longer best (generalized least squares, which weights, is) and its variance is no longer .
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 and , least squares has mean squared error from variance alone. Ridge with lowers it to (), at the cost of squared bias , even when the true parameter points in the least well-determined direction. With Laplace errors, the median has times less variance than the mean at (ratio tends to ). Gauss–Markov is not contradicted: neither competitor is both linear and unbiased.
Comparing models: the test
The 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 .
Proof
Let be projections onto . Then (Pythagoras: projects onto the complement of within , of dimension ). If is true, , so and . The two projections are mutually orthogonal, with ranks and ; applied to spherical they give (as in the previous proof) two independent variables with those degrees of freedom, and their normalized ratio is . For likelihood ratio, maximizing over in each model gives and , so . Since , we obtain , increasing in ; solve to obtain the stated formula.
∎Three special cases appear in every regression summary:
- One coefficient (): , and the and two-sided tests coincide. If , then .
- Global test, with intercept only: with and coefficient of determination , . It tests “no variable explains anything.”
- Variable blocks, e.g. all columns encoding a categorical variable: test coefficients simultaneously, which separate tests do poorly (they neither control global error nor account for estimator correlation).
never decreases when adding a variable, informative or not; hence adjusted , , which compares with sample variance of . Adding one variable raises if and only if its statistic (i.e. ) exceeds : from with , rearrange to , which is . This is lax (not equivalent to significance, requiring ); useful for description, not selection.
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: with degrees of freedom, -value of order . The likelihood ratio gives and, converted using the theorem’s formula, exactly the same ; its asymptotic -value (, ) is similar here because , but optimistic for small samples. For one coefficient, caché, . The model explains of variability (): moderate 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, . How long will the next request with those characteristics take? This is a random variable, . The second includes observation noise as well as uncertainty about the line.
Proof
(1) and is independent of , so is (the case of the exact-distribution theorem). (2) is Gaussian with mean zero and, since is independent of , variance ; the ratio to is again by independence of and . (3) By Cauchy–Schwarz, , and divided by this square follows (a -dimensional Gaussian quadratic form divided by its covariance and by , over independent ). The probability the supremum does not exceed is , equivalent to all pointwise inequalities holding simultaneously.
∎The two formulas differ by the under the square root; that represents observation noise, and its consequences are enormous. As , : the confidence interval collapses onto the line, since infinite data determine the mean without error. The prediction interval approaches , 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 being Gaussian (or its actual shape) and having the same variance at as in the data.
Three things to inspect. The confidence band is hourglass-shaped, narrowest at (the square root of ), opening outside the data range; the prediction band barely curves because dominates. With heteroscedasticity, is roughly true averaged over but false at each point: band width is nearly constant, but actual noise grows with , so coverage is far above 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”:
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 of the time and prediction contains a new observation . But confidence contains the new observation only 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 per unit of , holding other model variables fixed.” This is a statement about conditional association in data, not what happens if one intervenes on (the latter is covered by causal versus descriptive regression). Precisely, the Frisch–Waugh–Lovell theorem says is the slope of regressing on the residual of after removing what other columns explain. The part of already explained by other variables contributes nothing to . We use this next.
Categorical variables. A variable with levels is encoded using indicator columns plus intercept (treatment coding): each coefficient is the mean difference between that level and reference, holding everything else fixed. Including all indicators and the intercept makes the columns sum to the ones column: loses rank and ceases to be identifiable (the “dummy variable trap”). Interactions. If the effect of varies by group , add : the coefficient of becomes the reference group’s slope, that of the difference in slopes, and that of the shift at , interpretable only if lies in the data range (centering helps). Logarithms. With and , slope is an elasticity: more is associated with more . With and in levels, a one-unit increase multiplies expected by for small .
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 , practically infinite. The interaction recovers group slopes and shows why the coefficient of alone misleads: server B does not “cost ” ms more, but , which at is ms. (Estimates , , and are within half a standard error of truth, , , and . The shift at is least well determined, with standard error versus for interaction, because is at the edge of the range.) With and , estimated slope is (truth ): more is associated with more .
Collinearity and variance inflation factor
Coefficients and of two almost identical predictors cannot be separated: data know only their sum. Measuring this requires an exact coefficient-variance formula.
Proof
Partition and let be the residual from regressing on . By block inversion (Schur complement), the corresponding diagonal element of is . By definition of (with intercept in ), . Substitute into . For the inverse correlation matrix, the same argument on standardized columns gives . This also yields Frisch–Waugh–Lovell: , the slope of on .
∎With , standard error is multiplied by . Two predictors with correlation have (for , ; for , ). 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 tests. The joint test retains power against alternatives in the direction data do determine (in the figure, ), and predictions within the region of similar predictors barely suffer. The figure shows this with a confidence ellipse.
The ellipse is the geometric form of . With orthogonal predictors it is nearly circular; at high it stretches along (where data cannot distinguish) and narrows along (where they can). The replicate cloud has the same shape, confirming it is not a fitting artifact. With , and , both coefficients have -value (neither significant separately), yet the joint test gives , : the origin is clearly outside the ellipse. Reading only the -value table would conclude “neither x1 nor x2 matters,” when the truth is “one matters, and I do not know which.”
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 (correlation : ) and the third, independent, . Both formulas agree to three decimals. What to do depends on the question: to predict for values like those observed, nothing (ridge if stabilization is needed, ridge regression); for a joint effect, use the test; to separate effects, only more data or a design decorrelating predictors helps, never a computational trick. VIF – 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: , so . High-leverage points pull the line toward themselves and leave small residuals; inspecting raw residuals hides them. Leverage properties are (lower bound with an intercept), (average ; hence attention to values above or ), and in simple regression : it depends only on how far is from center, not .
Exact deletion formulas avoid refitting the model times:
Proof
Let . Since , Sherman–Morrison (rank-one case of the Woodbury identity) gives . Since ,
For , note fitting without observation is equivalent to fitting all observations with an added column equal to at and elsewhere (this absorbs observation without error). By Frisch–Waugh–Lovell, the reduction in sum of squares from adding is . Then follows by substituting the first formula into its definition and using : . The relation between and is algebra from . Finally, is the statistic for testing in the model with column and follows under the model, so .
∎Cook’s distance factors influence into two parts: . The first is how misaligned the point is (residual); the second, how far it lies in space (leverage). Both are needed. Explore them directly in the figure.
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 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, , so a central point cannot exceed a certain Cook distance however large its residual (with the figure’s thirteen points and central , ). 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 , , .
The cell checks the factorization with 30 points and one far, misaligned point, comparing Cook’s distance from its definition (refitting times) with the formula:
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 (four times the average) and studentized residual , and Cook distance , about sixty times the next point’s (). The formula reproduces refitting to error of order .
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 versus normal: tails or skew (assumption 5). Scale–location ( versus ): 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.
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 (the line underestimates extremes), the funnel opens right and scale–location curve rises, and QQ departs from the diagonal in tails. The test for adding confirms it (, ), as does Spearman correlation between and (, ). Uniform design has no high-leverage points (maximum barely exceeds ). 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 must account for inspecting residuals (Bonferroni, ; 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 is no longer its variance. With independent errors and , correct variance is
the sandwich form of the M-estimator variance from lesson 8: “bread” is and “filling” is score variance. Estimate it by replacing each with a version of squared residual, . Each is a poor estimator of (inconsistent from one observation), but the weighted sum converges, which supports the method (White, 1980). Variants differ by weight :
| Variant | Idea | |
|---|---|---|
| HC0 | White’s sandwich; downward bias at small | |
| HC1 | degrees-of-freedom correction | |
| HC2 | unbiased under homoscedasticity, because | |
| HC3 | approximates jackknife; most conservative of HC0, HC2 and HC3, recommended by default at moderate (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 , because cancels. Conditional on data, and , so .
∎The cell checks this with 100,000 replicates under strongly increasing variance, where the difference from classical standard error is already visible:
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 with the classical formula and with HC0 ( higher because noise grows where leverage is greatest); wild bootstrap gives and its full covariance matrix agrees with the sandwich to a few thousandths ( versus for intercept variance), the Monte Carlo error of 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: with , one homoscedastic scenario () and one heteroscedastic (), with and . Estimand: true slope, . Methods: classic interval, HC0 with normal quantiles, HC3 with quantiles, pairs bootstrap and Rademacher wild bootstrap, both percentile with replicates, and studentized wild bootstrap (quantiles of with HC0 standard error). Performance measures: coverage and mean width over replicates, so each coverage has Monte Carlo error about points.
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)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 ( with , somewhat conservative), and robust methods pay a small price: HC3 () with intervals wider, pairs () with equal width, and HC0, wild percentile and studentized wild fall short ( to ). With heteroscedasticity, the classical interval collapses ( with and with : increasing does not fix it and even worsens it, because error is an incorrect formula, not small sample), and simple percentile wild gives and . HC3 ( and ), pairs ( and ) and studentized wild ( and ) come closest to nominal, with correspondingly wider intervals: the short classical interval was short from optimism. None reaches with such extreme leverage and .
This yields a reasoned rule, not dogma. By default report HC3 standard errors (with 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, ) or is small: use pairs if design is random and studentized wild if conditioning on ; 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 during fitting, and checks against statsmodels, what will be used in practice.
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}")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 and Adj. R-squared adjusted; F-statistic and Prob (F-statistic) are the global test (the test with intercept-only ); Df Residuals is and Df Model is . Right header: Log-Likelihood is , Gaussian likelihood at its maximum (using the MLE of , not ); AIC and BIC are and . Coefficient table: coef is ; std err is ; t their ratio; P>|t| the two-sided -value with ; and the last two are interval . Footer: Omnibus and Jarque-Bera test residual normality (skewness and kurtosis), Durbin-Watson first-order autocorrelation ( if absent), and Cond. No. is , 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:
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 ). A deeper detail: statsmodels also avoids normal equations; by default it solves with the pseudoinverse of (based on SVD), for the same numerical reason. With service data, HC3 standard error for caché barely differs from classical ( versus ): 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
Step 1 of 5. What does unbiasedness of for for every imply?
Step 1 of 5. Express and residual vector in terms of .
diagnosticos(X, y), which receives design matrix X (including the ones column) and response y, returning four vectors (h, r, t, D): leverage , internally studentized residuals , externally studentized residuals , and Cook's distances . Do not refit the model $n$ times: use deletion formulas (with , and ). Compute leverage using QR without constructing the 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, DSummary
- Model and assumptions. , with . Each conclusion uses a subset: unbiasedness (linearity and exogeneity), variance and Gauss–Markov (plus spherical errors), exact and (plus normality). Exogeneity determines whether coefficients admit causal reading and is untestable.
- Least squares. Orthogonal projection of onto and MLE under Gaussian errors. is unbiased; is MLE and underestimates. Calculate using QR, not .
- Exact distribution. ; interval . Coefficients are correlated with matrix .
- Gauss–Markov. Least squares has smallest variance among linear unbiased estimators (proof using , ). It does not compete with biased estimators (ridge, shrinkage), or nonlinear ones with heavy-tailed errors, or say anything without homoscedasticity.
- test. under ; the exact likelihood-ratio test (). With , ; adjusted rises if and only if .
- Confidence and prediction. for the mean, for a new observation. The former collapses with ; the latter tends to and depends on normality and homoscedasticity. The Working–Hotelling simultaneous band uses .
- Interpretation. Coefficients are conditional associations (Frisch–Waugh–Lovell). Encode categorical variables with indicators, interaction as slope difference, log-log as elasticity.
- Collinearity. with . It inflates individual standard errors and stretches the confidence ellipse diagonally; it does not bias, and joint retains power in the data-determined direction.
- Diagnostics. ; and correct unequal residual variance; requires leverage and misalignment; deletion formulas avoid refitting times.
- Robustness. HC0 through HC3 replace 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.