Asymptotic theory: normality of the MLE, the delta method and M-estimators
Derive consistency and asymptotic normality of maximum likelihood, propagate uncertainty with the delta method, and analyze sandwich variance, misspecification, robust estimation and failures of classical asymptotics.
After this lesson you can
- Explain consistency using identifiability and uniform convergence, and derive MLE asymptotic normality.
- Use the delta method to propagate uncertainty and recognize its limitations.
- Derive sandwich variance for estimating equations and interpret misspecified maximum likelihood.
- Analyze Huber estimation, contamination and influence functions.
- Identify boundary, nonregular and incidental-parameter failures of classical asymptotics.
Before you start
- 05Maximum likelihood estimator (MLE)Score functionFisher informationFisher information matrixObserved informationConsistent estimatorIdentifiabilityStandard errorRobust statistics and breakdown pointSimulation study (ADEMP)
- 04Convergence in distributionSlutsky's lemma and continuous mapping theoremMultivariate central limit theoremJensen's inequality
- 03Taylor remainderMean value theorem
Motivation: where standard errors come from
Fit a logistic regression with any statistical package and it will return a standard error, a statistic, and a 95 % interval with each coefficient. None comes from an exact formula: the distribution of the logistic maximum-likelihood estimator with has no closed form. What software prints is an asymptotic approximation: it assumes is approximately normal, centered on the true value, with covariance equal to the inverse observed information. The next cell verifies this: the statsmodels standard error is exactly the square root of the diagonal of the inverse negative log-likelihood Hessian.
import numpy as np
import statsmodels.api as sm
rng = np.random.default_rng(0)
n = 500
X = sm.add_constant(rng.normal(size=(n, 2)))
beta = np.array([-0.5, 1.0, -0.7])
y = rng.binomial(1, 1 / (1 + np.exp(-X @ beta)))
res = sm.Logit(y, X).fit(disp=0)
p = 1 / (1 + np.exp(-X @ res.params))
H = -(X.T * (p * (1 - p))) @ X # hessiano de la log-verosimilitud en el EMV
se_a_mano = np.sqrt(np.diag(np.linalg.inv(-H)))
print("coeficientes: ", np.round(res.params, 4))
print("SE de statsmodels: ", np.round(res.bse, 6))
print("sqrt(diag((-H)^-1)): ", np.round(se_a_mano, 6))This lesson justifies that approximation and marks its limits. It answers four questions everyone who builds models eventually asks:
- Why does approach the true value? Consistency, from Jensen’s inequality and the law of large numbers.
- Why the normal distribution and why ? A Taylor expansion of the score function, the central limit theorem, and Slutsky’s lemma.
- What if I care about a function of (a ratio, an odds ratio, a mean)? The delta method.
- What if the model is false? The estimator still converges, but to something else, and its variance is no longer : it is the sandwich variance of M-estimators, the same variance behind econometric “robust” standard errors and Huber’s estimator.
We finish with cases where asymptotics fail, because knowing when not to trust the normal approximation is as important as knowing how to use it.
Consistency of the MLE
Work with , a model with , and mean log-likelihood
The MLE maximizes . By the law of large numbers, for each fixed . If the maximum of approaches the maximum of , we only need to know where the latter is. Jensen’s inequality tells us.
Proof
Since is strictly concave, Jensen gives
Equality in Jensen requires the ratio to be constant almost surely under , and equality in the last inequality requires to assign no mass outside the support of . Together they force the constant to be 1, i.e. almost surely, and identifiability gives . The first expression with its sign reversed defines Kullback–Leibler divergence.
∎Maximizing likelihood is, in the limit, minimizing KL divergence between model and truth. This interpretation will matter when the model is misspecified. But pointwise convergence is not enough: the maximum of a sequence of functions can escape even though each value converges. Convergence must be uniform, and the maximum of must be well separated.
This is consistency of the MLE: the estimator is consistent in the sense of lesson 4. The proof sketch has three steps worth remembering because they apply to any estimator maximizing an empirical mean.
- Uniform law. Under (i), (iii), and (iv), in probability. Compactness lets us cover by finitely many balls where oscillates little, and the envelope allows the law of large numbers to be applied to those oscillations (a Glivenko–Cantelli-type theorem).
- Separation. is continuous (dominated convergence using the envelope), is compact, and is the unique maximum, so for every there is an with .
- Putting them together. Since , adding and subtracting gives . If , then , whose probability tends to zero.
Asymptotic normality
Consistency says where ends up; now we want its distribution around that point. The idea is that near , the score equation , with , is nearly linear, and the solution of a linear equation whose constant term is a sum of iid variables is normal. Start in one dimension.
Assumption (iii) is the information equality from lesson 6, which holds when we can differentiate twice under the integral. This is asymptotic normality of the MLE, with the practical approximation : the MLE attains the Cramér–Rao bound in the limit.
Proof
Expand around with a second-order Lagrange remainder and evaluate at , which lies in with probability tending to one:
where lies between and . Rearranging and multiplying by ,
Numerator. is a sum of iid variables with mean 0 and variance , so by the central limit theorem . First denominator term. By the law of large numbers, in probability. Remainder. , so it is bounded in probability, and in probability by consistency: their product tends to 0. By Slutsky’s lemma, the ratio converges in distribution to .
∎Remember the structure, which will recur three times: a CLT in the numerator, a law of large numbers in the denominator, and Slutsky to join them. The Taylor remainder only requires already to be close, which consistency supplies. In dimensions the argument is identical with vectors and matrices: with invertible Fisher information matrix , the multivariate CLT gives
(The mean value theorem does not hold for vector functions with a single intermediate point; apply it row by row, with a different for each score component, or use the integral form of the remainder. Neither changes the argument.)
When the approximation works well
The theorem is a limit: it says nothing about . The next interactive tests it with three models. For exponential rate , and ; the shape of the distribution of does not depend on , so we fix it at 1. For Poisson, and . For gamma with unknown shape and scale, solves , with the digamma function, and its asymptotic variance, accounting for scale estimation, is .
Three lessons from the interactive. Skewness is the last thing to disappear. The normal has skewness 0; for exponential has inverse-gamma skewness (1.6 at , 0.6 at ), and the two Wald interval ends fail at different rates even if total coverage seems reasonable. Total information matters, not . For Poisson, what matters is , the expected event count: with and there are 2.5 expected events, , and in those replicates estimated standard error is 0 and the interval a point. Shape parameters need more data than location parameters: the gamma MLE of has positive bias of order (with , about 16 % at and 3 % at ) and a longer right tail.
Asymptotic efficiency and the superefficiency trap
The MLE’s asymptotic variance, , equals the Cramér–Rao bound. The MLE is called asymptotically efficient. But Cramér–Rao applies to unbiased estimators in finite samples, and an asymptotically normal estimator may be biased. Can another estimator beat in the limit? Joseph Hodges constructed a troubling counterexample in 1951. With , define
If , with probability tending to one and behaves like : asymptotic variance 1. If , and : asymptotic variance 0, better than the bound. It is superefficient at . The price appears in the risk near 0, rather than at the exact point.
import numpy as np
from scipy.stats import norm
import matplotlib.pyplot as plt
def riesgo_hodges(theta, n):
"""n * E[(T_n - theta)^2] exacto, con Xbar ~ N(theta, 1/n) y umbral c = n^(-1/4)."""
c = n ** -0.25
a, b = np.sqrt(n) * (-c - theta), np.sqrt(n) * (c - theta)
masa = norm.cdf(b) - norm.cdf(a)
# parte de (Xbar - theta)^2 que se pierde al poner T = 0, y parte que se gana (theta^2)
perdida = masa - (b * norm.pdf(b) - a * norm.pdf(a))
return 1 - perdida + n * theta**2 * masa
for n in [100, 10_000, 1_000_000]:
t = np.linspace(0, 3 * n ** -0.25, 4001)
r = riesgo_hodges(t, n)
i = np.argmax(r)
print(f"n = {n:>9,}: riesgo normalizado en theta = 0: {r[0]:.4f}; máximo {r[i]:6.2f} en theta = {t[i]:.4f}")
plt.plot(t * n**0.25, r, label=f"n = {n:,}")
plt.axhline(1, color="gray", ls="--", label="EMV (media muestral)")
plt.yscale("log"); plt.xlabel("θ · n^(1/4) (el umbral está en 1)"); plt.ylabel("n · ECM"); plt.legend(); plt.show()The normalized risk of the sample mean is 1 for every . Hodges’ is nearly 0 at , but has a peak near whose height grows without bound, on the order of : the estimator bought its advantage at one point with enormous risk around it. Le Cam showed in 1953 that this is general: the set of superefficiency points has Lebesgue measure zero, and Hájek’s convolution theorem establishes that among regular estimators (whose limiting distribution does not change under perturbations ), none has asymptotic variance lower than . MLE efficiency is therefore local and uniform optimality, not pointwise optimality.
Standard errors in practice
The theorem gives , which depends on unknown . Three common substitutes are all consistent under the model:
| Covariance estimator | Formula | When |
|---|---|---|
| Expected information at | in closed form | |
| Observed information | , | used by almost all programs |
| Score outer product | needs only gradients (BHHH) |
The first two coincide for exponential families in their natural parameterization, since the Hessian does not depend on data there. Efron and Hinkley (1978) argued that observed information is more suitable for inference conditional on the sample at hand. The third is the sandwich “meat” we will see shortly and has greater variance in small samples.
Calculating needs the Hessian. There are three routes. By hand, for a small model. Centered finite differences: , with truncation error and rounding error ; the balance is at on a relative scale. And automatic differentiation, exact up to rounding and the only reasonable choice with thousands of parameters:
import torch
from torch.func import hessian
def nll(theta): # log-verosimilitud negativa de una gamma, theta = (log alfa, log escala)
a, s = theta.exp()
return -(torch.special.xlogy(a - 1, x) - x / s - torch.lgamma(a) - a * torch.log(s)).sum()
J = hessian(nll)(theta_hat) # información observada en (log alfa, log escala)
cov = torch.linalg.inv(J)
Standard errors depend on the parameterization in which they are calculated, but not arbitrarily: if , the covariance in is that of transformed by the Jacobian. This rule is the delta method, formalized in the next section. First, a complete gamma lab.
import numpy as np
from scipy import optimize, special
rng = np.random.default_rng(47)
alfa0, escala0, n = 2.5, 1.6, 80
x = rng.gamma(alfa0, escala0, size=n)
def nll(th):
"""Log-verosimilitud negativa en (alfa, escala)."""
a, s = th
if a <= 0 or s <= 0:
return np.inf
return -np.sum((a - 1) * np.log(x) - x / s - special.gammaln(a) - a * np.log(s))
# optimizar en logaritmos (sin restricciones) y volver
r = optimize.minimize(lambda u: nll(np.exp(u)), x0=np.log([1.0, x.mean()]), method="BFGS")
th = np.exp(r.x)
def hessiano(f, t, h=1e-4):
"""Hessiano por diferencias centradas con paso relativo h."""
d = len(t)
H = np.empty((d, d))
hs = h * np.maximum(np.abs(t), 1.0)
for j in range(d):
for k in range(d):
ej, ek = np.eye(d)[j] * hs[j], np.eye(d)[k] * hs[k]
H[j, k] = (f(t + ej + ek) - f(t + ej - ek) - f(t - ej + ek) + f(t - ej - ek)) / (4 * hs[j] * hs[k])
return H
J = hessiano(nll, th) # información observada
cov = np.linalg.inv(J)
a, s = th
I_esp = n * np.array([[special.polygamma(1, a), 1 / s], [1 / s, a / s**2]])
print("EMV (alfa, escala):", np.round(th, 4))
print("SE por hessiano numérico:", np.round(np.sqrt(np.diag(cov)), 5))
print("SE por información esperada:", np.round(np.sqrt(np.diag(np.linalg.inv(I_esp))), 5))
for nombre, est, se, verdad in [("alfa", a, np.sqrt(cov[0, 0]), alfa0), ("escala", s, np.sqrt(cov[1, 1]), escala0)]:
print(f"Wald 95 % para {nombre}: [{est - 1.96 * se:.3f}, {est + 1.96 * se:.3f}] (verdad {verdad})")
# método delta para la media mu = alfa * escala: gradiente (escala, alfa)
g = np.array([s, a])
se_mu = np.sqrt(g @ cov @ g)
print(f"\nmedia: EMV {a * s:.4f} = media muestral {x.mean():.4f}; SE delta {se_mu:.5f}; "
f"s/sqrt(n) = {x.std(ddof=0) / np.sqrt(n):.5f}")Two details. The numerical Hessian agrees with expected information to all printed digits: for gamma, second derivatives of log-likelihood in depend on data only through , and at the MLE , so observed and expected information coincide exactly at ; the small difference is finite-difference error. Also, the MLE of the mean is exactly : the scale score equation is . Its delta-method standard error, , is exactly , the fitted gamma standard deviation divided by (with the inverse Fisher matrix above, simplifies to ). It differs from , which uses sample standard deviation and does not assume gamma data: our first encounter with the contrast between model-based variance and a variance that is not model-based. Here “escala” denotes scale.
Do these intervals work? The only honest way to know is a simulation study. Using ADEMP: the aim is Wald interval coverage; data are generated from a gamma with and scale for several ; estimands are , scale, and mean; methods are Wald with expected information and the delta method; the performance measure is coverage with its Monte Carlo error.
import numpy as np
from scipy import optimize, special
def emv_gamma(x):
"""EMV (alfa, escala) resolviendo la ecuación de perfil en alfa."""
c = np.log(x.mean()) - np.log(x).mean()
f = lambda a: np.log(a) - special.digamma(a) - c
a = optimize.brentq(f, 1e-3, 1e4)
return a, x.mean() / a
def cov_esperada(a, s, n):
I = n * np.array([[special.polygamma(1, a), 1 / s], [1 / s, a / s**2]])
return np.linalg.inv(I)
rng = np.random.default_rng(1)
alfa0, escala0, R = 2.5, 1.6, 1000
verdad = np.array([alfa0, escala0, alfa0 * escala0])
for n in [15, 50, 200]:
cubre = np.zeros(3)
for _ in range(R):
x = rng.gamma(alfa0, escala0, size=n)
a, s = emv_gamma(x)
V = cov_esperada(a, s, n)
g = np.array([s, a])
est = np.array([a, s, a * s])
se = np.sqrt([V[0, 0], V[1, 1], g @ V @ g])
cubre += np.abs(est - verdad) <= 1.96 * se
cov = cubre / R
mc = np.sqrt(0.95 * 0.05 / R)
print(f"n = {n:3d}: cobertura alfa {cov[0]:.3f}, escala {cov[1]:.3f}, media {cov[2]:.3f} (error MC ±{1.96 * mc:.3f})")With each interval fails in its own way: scale coverage is about 82 %, mean about 91 %, and shape overshoots (97 %), because has positive bias and its estimated standard error increases with . With scale is still at 90 %, and only at are all three within Monte Carlo error. The practical rule is that sample size needed depends on the parameter and parameterization, not just the model, and the only way to know for your problem is simulation.
Finally, the library version. GenericLikelihoodModel from statsmodels needs only per-observation log-likelihood; it maximizes numerically and calculates standard errors with a numerical Hessian, as we did by hand.
import numpy as np
from scipy import special
from statsmodels.base.model import GenericLikelihoodModel
class Gamma(GenericLikelihoodModel):
def loglikeobs(self, params):
a, s = params
y = self.endog
return (a - 1) * np.log(y) - y / s - special.gammaln(a) - a * np.log(s)
rng = np.random.default_rng(47)
x = rng.gamma(2.5, 1.6, size=80) # los mismos datos que antes
mod = Gamma(x, exog=np.ones_like(x))
res = mod.fit(start_params=[1.0, x.mean()], method="nm", maxiter=2000, disp=0)
res = mod.fit(start_params=res.params, method="bfgs", disp=0)
print("parámetros:", np.round(res.params, 4))
print("SE: ", np.round(res.bse, 5))The delta method
You already know the delta method from probability theory. In statistics it is the tool for transferring standard errors from parameters to functions of them, and deserves a complete treatment.
Read as a calculation rule, the delta method says standard errors propagate via the Jacobian: , with evaluated at . The proof is short: write , where as by differentiability. The first term, multiplied by , converges to the stated normal. The second is : the first factor tends to zero in probability because , the second is bounded in probability, and Slutsky does the rest. You will reconstruct it step by step in the exercises.
Geometrically, the delta method replaces with its tangent at . An affine map transforms one normal into another, and the tangent slope multiplies standard deviation. The approximation is good when is nearly straight on the scale over which moves, i.e. over an interval of a few standard errors. One dimensionless number summarizes this: relative curvature , the relative change in slope over one standard error.
Variance-stabilizing transformations
Often asymptotic variance depends on the parameter itself: . This complicates intervals and plots, because every estimate has different precision. The delta method suggests a remedy: choose with constant, that is,
| Model | Variance of | ||
|---|---|---|---|
| Poisson, | |||
| Binomial, | |||
| Exponential, | |||
| Bivariate normal correlation | (in practice, ) |
The last is Fisher’s z transformation. Besides stabilizing variance, these transformations often reduce skewness, improving intervals built on the transformed scale and then transformed back.
import numpy as np
rng = np.random.default_rng(3)
n, R = 50, 200_000
print(" p n·Var(p̂) p(1-p) 4n·Var(arcsin √p̂)")
for p in [0.05, 0.2, 0.5, 0.8]:
ph = rng.binomial(n, p, size=R) / n
print(f"{p:5.2f} {n * ph.var():8.4f} {p * (1 - p):6.4f} {4 * n * np.arcsin(np.sqrt(ph)).var():8.4f}")The variance of changes by a factor of 5 between and ; that of remains near except at , where is small and the approximation has not yet taken hold.
M-estimators and sandwich variance
The proof of MLE normality barely used that was a log-likelihood derivative. It used three facts: solves an equation of the form “empirical mean of something equals zero”, that something has zero expectation at the limiting value, and it can be linearized. This structure has a name.
The name M-estimators and Z-estimators, with estimating equations, covers almost every estimator you will use:
- MLE: , = score.
- Least squares: , .
- Quantile : (not differentiable, but the theory extends).
- Method of moments and generalized method of moments: .
- Empirical risk minimization in machine learning: . The ERM of m13 is exactly this, and neural-network training losses are M-estimators without an underlying probabilistic model.
The matrix is the sandwich variance: is the bread and the meat. The proof is exactly the MLE proof: , hence . The multivariate CLT gives , the law of large numbers and consistency give , and Slutsky gives the product. The only change is that no equality now relates to .
For the MLE under the correct model, and : the sandwich reduces to . The simplification is exactly the information equality. Otherwise estimate the full sandwich, replacing expectations with means:
For least squares, and , and the sandwich is White’s 1980 estimator, HC0, the basis of econometric heteroskedasticity-robust standard errors.
A trick from Stefanski and Boos (2002) makes the delta method a special case: to obtain the standard error of , stack the equation onto those for and apply the sandwich to the full system. The generic implementation below does this for the coefficient of variation , which requires estimating mean and variance together.
import numpy as np
from scipy import optimize
def m_estimar(psi, datos, theta0):
"""Resuelve (1/n) sum_i psi(x_i, theta) = 0 y devuelve (theta_hat, covarianza sándwich / n)."""
n = len(datos)
Psi = lambda th: psi(datos, th).mean(axis=0)
sol = optimize.root(Psi, theta0, method="hybr", tol=1e-12)
th = sol.x
d = len(th)
A = np.empty((d, d))
for j in range(d): # jacobiano de Psi por diferencias centradas
h = 1e-6 * max(1.0, abs(th[j]))
e = np.zeros(d); e[j] = h
A[:, j] = (Psi(th + e) - Psi(th - e)) / (2 * h)
P = psi(datos, th) # n x d
B = P.T @ P / n
Ainv = np.linalg.inv(A)
return th, Ainv @ B @ Ainv.T / n
def psi_cv(x, th):
mu, s2, cv = th
tercera = np.full(len(x), np.sqrt(abs(s2)) - cv * mu) # no depende de x: solo define cv = sigma/mu
return np.column_stack([x - mu, (x - mu) ** 2 - s2, tercera])
rng = np.random.default_rng(7)
x = rng.gamma(4.0, 2.0, size=400) # coeficiente de variación verdadero 1/2
th, V = m_estimar(psi_cv, x, theta0=[x.mean(), x.var(), 0.5])
print("(media, varianza, CV):", np.round(th, 4), " SE:", np.round(np.sqrt(np.diag(V)), 5))
# comparación con el método delta "a mano": CV = sqrt(s2)/mu, con la covarianza de (media, varianza)
m, s2 = th[0], th[1]
mu3, mu4 = np.mean((x - m) ** 3), np.mean((x - m) ** 4)
Sigma = np.array([[s2, mu3], [mu3, mu4 - s2**2]]) / len(x)
g = np.array([-np.sqrt(s2) / m**2, 0.5 / (np.sqrt(s2) * m)])
print("SE del CV por método delta explícito:", round(float(np.sqrt(g @ Sigma @ g)), 5))The two figures agree because they are the same calculation: the sandwich of the stacked system contains, in its third-equation block, the gradient of and covariance of , which itself depends on third and fourth sample moments. Stacking avoids hand differentiation.
The MLE when the model is false
Every model is an approximation. What does the MLE estimate if data come from a distribution outside ? The MLE is an M-estimator with , so it converges to the maximizer of . Repeating the Jensen calculation,
This is the MLE under misspecification, a result due to Huber (1967) and White (1982). It has two messages. The reassuring one: the MLE still estimates something well defined, the best approximation within the model. The uncomfortable one: since in general, the variance printed by software, , is incorrect, and may be too large or too small.
import numpy as np
rng = np.random.default_rng(5)
n, R, s = 200, 4000, 1.0 # lognormal(0, s^2): CV^2 = e^{s^2} - 1
mu = np.exp(s**2 / 2)
lam_star = 1 / mu
est, se_mod, se_sw, cubre_mod, cubre_sw = [], [], [], 0, 0
for _ in range(R):
x = rng.lognormal(0.0, s, size=n)
lam = 1 / x.mean()
sm = lam / np.sqrt(n) # (n I(lam))^{-1/2}
sw = np.sqrt(np.mean((1 / lam - x) ** 2)) * lam**2 / np.sqrt(n) # sqrt(A^-1 B A^-1 / n)
est.append(lam); se_mod.append(sm); se_sw.append(sw)
cubre_mod += abs(lam - lam_star) <= 1.96 * sm
cubre_sw += abs(lam - lam_star) <= 1.96 * sw
print(f"pseudo-verdad 1/E[X] = {lam_star:.4f}; media de las estimaciones = {np.mean(est):.4f}")
print(f"desviación real de lambda_hat: {np.std(est):.5f}")
print(f"SE medio del modelo: {np.mean(se_mod):.5f} cobertura {cubre_mod / R:.3f}")
print(f"SE medio sándwich: {np.mean(se_sw):.5f} cobertura {cubre_sw / R:.3f}")
print(f"cociente de varianzas teórico CV^2 = {np.exp(s**2) - 1:.3f}")For a lognormal with , : model standard error is too small by a factor , and its “95 %” interval covers pseudo-truth much less often than promised. The sandwich, by contrast, gets it right.
Overdispersion in Poisson regression
The most common practical case is Poisson regression, , fitted to counts with greater variance than mean. There is additional good news: if the mean is correctly specified, pseudo-truth is the true even when the distribution differs. The Poisson score equation, , involves only the mean, and its expectation vanishes at the true (Gourieroux, Monfort and Trognon, 1984, proved this for every linear exponential family). What fails is variance: if (negative binomial), is greater than , and model standard error underestimates true uncertainty.
Asymptotic theory predicts that with , true variance of is 3.1 times the model’s assumption and its interval covers around 74 %; with , the factor is 5.1 and coverage drops to 61 %. The sandwich remains near 95 %. With it falls slightly below nominal: is calculated using squared residuals from observations that helped fit , and tends to underestimate. The HC2 and HC3 corrections in m27 and bootstrap address exactly that bias. For counts there is also an intermediate route, quasi-likelihood with an overdispersion parameter, covered with generalized linear models.
Robustness: Huber’s estimator
The most damaging misspecification for the sample mean is contamination: a small fraction of observations coming from elsewhere (recording errors, broken sensors, bot users). The mean is the normal MLE and so sensitive to those points that one sufficiently distant observation can drag it anywhere. The median is immune, but under normality loses 36 % efficiency. Peter Huber posed the problem precisely in 1964 and solved it with an M-estimator. To measure it we need a concept generalizing the breakdown point of lesson 1’s robust statistics.
For a Z-estimator, differentiating at gives : influence is proportional to . Asymptotic variance is , the sandwich: asymptotic variance and robustness are two readings of the same function. For the mean, and , unbounded. For the median, , bounded but discontinuous. Huber proposed a middle ground.
The Huber estimator is quadratic at the center, like the mean, and linear in the tails, like the median. It is calculated by iteratively reweighted least squares (IRLS): with weights on scaled residuals , the equation is , i.e. is a weighted mean; alternate weights and mean until convergence. Scale is estimated separately, robustly, using MAD divided by ; with bounded monotone and this scale, the estimator’s breakdown point is 50 %, like the median’s.
Under with known scale, and , so
Efficiency and sensitivity both increase with . At efficiency is exactly 95 %, so it is the default in almost every library.
The interactive shows the full tradeoff. Huber’s asymptotic bias under contamination is bounded by something of order regardless of how far away is; the mean’s is and unbounded. Huber (1964) also proved that if the true distribution can be any with arbitrary symmetric , the estimator minimizing maximum asymptotic variance is Huber’s with solving
For this corresponds to , and to . This is the first time in the lesson an estimator is chosen by its worst-case behavior in a neighborhood of the model, rather than under the exact model.
import numpy as np
import statsmodels.api as sm
from scipy.stats import norm
def huber(x, k=1.345, tol=1e-10, escala_rlm=False):
"""Posición de Huber por mínimos cuadrados reponderados.
Escala: MAD de los datos, fija; con escala_rlm=True, la regla de statsmodels RLM:
mediana de |x - mu| / 0.6745, recalculada en cada iteración con el mu actual."""
c = norm.ppf(0.75)
med = np.median(x)
s = np.median(np.abs(x - med)) / c
mu = med
for _ in range(500):
if escala_rlm:
s = np.median(np.abs(x - mu)) / c
r = (x - mu) / s
w = np.minimum(1.0, k / np.maximum(np.abs(r), 1e-300))
nuevo = np.sum(w * x) / np.sum(w)
if abs(nuevo - mu) < tol * (1 + abs(mu)):
return nuevo
mu = nuevo
return mu
rng = np.random.default_rng(11)
x = np.concatenate([rng.normal(0, 1, 90), rng.normal(8, 1, 10)]) # 10 % contaminado en 8
rlm = sm.RLM(x, np.ones_like(x), M=sm.robust.norms.HuberT(t=1.345)).fit(tol=1e-12)
print(f"media {x.mean():.4f} mediana {np.median(x):.4f} Huber (MAD fija) {huber(x):.6f}")
print(f"Huber (escala de RLM) {huber(x, escala_rlm=True):.8f} statsmodels RLM {rlm.params[0]:.8f}")
# estudio de simulación: sesgo y ECM con y sin contaminación (verdad = 0)
R, n = 1500, 100
print("\ncolumnas: media, mediana, Huber k = 1.345, Huber k = 1")
for eps in [0.0, 0.1]:
est = np.empty((R, 4))
for r in range(R):
malos = rng.random(n) < eps
y = np.where(malos, rng.normal(8, 1, n), rng.normal(0, 1, n))
est[r] = y.mean(), np.median(y), huber(y), huber(y, k=1.0)
sesgo, ecm = est.mean(axis=0), (est**2).mean(axis=0)
print(f"eps = {eps:.1f}: sesgo = {np.round(sesgo, 3)} ECM = {np.round(ecm, 4)}")
if eps == 0:
print(f" eficiencia relativa a la media = {np.round(ecm[0] / ecm, 3)}")Three observations. Libraries make choices. RLM in statsmodels does not fix scale: each iteration uses the median of at current (residual MAD about 0, not about their median). This is a slightly different estimator in the third digit; with the same rule, the from-scratch version agrees with the library to tolerance. Without contamination, Huber with retains efficiency near the theoretical 95 %, with somewhat less, and the median loses more than a third. With 10 % of data at 8, the mean shifts 0.8 and its MSE increases seventyfold. The median, with bias , beats Huber with : contamination is nearly twice the 5.8 % for which that is minimax, and bias dominates MSE. With , minimax for 14 %, Huber recovers much of the ground. This is the interactive’s tradeoff in data.
When asymptotics fail
The theorem assumptions are not technicalities. Four situations are worth recognizing immediately.
Small samples or little information. As the first interactive showed, normality is a limit, and distance from it depends on score skewness and total information. Transformations (log of a rate, logit of a probability) and likelihood-ratio intervals, which do not depend on parameterization, usually work much better than naive Wald intervals.
Boundary parameters. If and , the interior-point assumption fails. With , the constrained MLE is and : a mixture of point mass 1/2 at 0 and half a normal distribution. The likelihood-ratio statistic converges to (Chernoff, 1954; Self and Liang, 1987). This occurs when testing whether a variance component is zero, a mixture needs another component, or a random effect exists.
Nonregular models. If support depends on the parameter, as in , likelihood is not differentiable at the maximum, score does not have mean zero, and the MLE, , converges at rate : . Neither normal nor .
The number of parameters grows with . This is the most treacherous because the model is perfectly regular. Neyman and Scott (1948) illustrated it with pairs: for , with a mean for each pair and a common variance. The MLE of each is the pair mean, and that of variance is
because . With observations and parameters, dimension grows with data and fixed-dimensional theorems do not apply. This is the incidental parameter problem, which recurs in panel models with fixed effects and, differently, in high-dimensional logistic regression, where with non-negligible the MLE systematically overestimates coefficients (Sur and Candès, 2019).
import numpy as np
rng = np.random.default_rng(2)
sigma2 = 1.0
for m in [10, 100, 10_000]:
mu = rng.normal(0, 5, size=m) # una media distinta por par
X = mu[:, None] + rng.normal(0, np.sqrt(sigma2), size=(m, 2))
emv = np.mean((X - X.mean(axis=1, keepdims=True)) ** 2)
corr = np.sum((X[:, 0] - X[:, 1]) ** 2) / (2 * m) # verosimilitud de las diferencias
print(f"m = {m:6d} pares: EMV {emv:.4f} corregido {corr:.4f} (verdad {sigma2})")The fix is to eliminate incidental parameters before estimation: differences do not depend on the , and their likelihood gives consistent . This is marginal likelihood; conditional and modified profile versions use the same idea.
Common mistakes
Exercises
Step 1 of 4. Which expansion do you start with?
Step 1 of 4. What property of follows from differentiability of at ?
More than one answer may be correct.
varianzas_poisson(X, y, beta) to return (V_modelo, V_sandwich): estimated model-based covariance of , with , and sandwich covariance, . Both already include (they are covariances of , not of ). The function ajusta_poisson is provided. Do not use Python loops over observations.import numpy as np
def ajusta_poisson(X, y, iters=50):
"""EMV de la regresión de Poisson con enlace log, por Newton (scoring de Fisher)."""
beta = np.zeros(X.shape[1])
beta[0] = np.log(y.mean())
for _ in range(iters):
mu = np.exp(X @ beta)
paso = np.linalg.solve(X.T @ (mu[:, None] * X), X.T @ (y - mu))
beta = beta + paso
if np.max(np.abs(paso)) < 1e-10:
break
return beta
def varianzas_poisson(X, y, beta):
"""Devuelve (V_modelo, V_sandwich), covarianzas estimadas de beta_hat."""
mu = np.exp(X @ beta)
A = X.T @ (mu[:, None] * X)
V_modelo = np.linalg.inv(A)
# tu código: la carne B = sum_i (y_i - mu_i)^2 x_i x_i^T y el sándwich
V_sandwich = V_modelo
return V_modelo, V_sandwichSummary
- Consistency. The MLE maximizes an empirical mean whose limit, , is maximized at by Jensen and identifiability. With uniform convergence and a well-separated maximum (Wald), .
- Normality. Taylor expansion of score, CLT in the numerator, LLN in the denominator, and Slutsky: . The approximation takes longer with skewness, little total information, or parameters near a boundary.
- Efficiency. The MLE attains , minimum variance among regular estimators; Hodges’ superefficiency is bought at enormous maximum risk.
- In practice. Observed information (numerical or automatic Hessian) or expected information; check coverage with a simulation study.
- Delta method. , or : replace with its tangent. It fails if relative curvature is not small or . Variance-stabilizing transformations choose .
- M-estimators. MLE, least squares, quantiles, GMM, and ERM share the same structure with sandwich variance; stacking equations gives the delta method for free.
- Misspecification. The MLE converges to the pseudo-truth minimizing KL; model variance is incorrect and sandwich variance is consistent.
- Robustness. An M-estimator’s influence function is proportional to . Huber bounds at : with , 95 % efficiency under normality and bounded bias under contamination.
- Limits. Boundaries, parameter-dependent supports, and incidental parameters (Neyman–Scott) break classical theory.