Module contents
Lesson 8 of 27Advanced 115 min

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

Motivation: where standard errors come from

Fit a logistic regression with any statistical package and it will return a standard error, a zz statistic, and a 95 % interval with each coefficient. None comes from an exact formula: the distribution of the logistic maximum-likelihood estimator with n=500n = 500 has no closed form. What software prints is an asymptotic approximation: it assumes θ^\hat\theta 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.

[ ]Standard errors printed by softwareBrowser
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:

  1. Why does θ^\hat\theta approach the true value? Consistency, from Jensen’s inequality and the law of large numbers.
  2. Why the normal distribution and why I(θ)−1I(\theta)^{-1}? A Taylor expansion of the score function, the central limit theorem, and Slutsky’s lemma.
  3. What if I care about a function of θ\theta (a ratio, an odds ratio, a mean)? The delta method.
  4. What if the model is false? The estimator still converges, but to something else, and its variance is no longer I−1I^{-1}: 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 X1,…,Xn∼iidpθ0X_1, \dots, X_n \iid p_{\theta_0}, a model {pθ:θ∈Θ}\{p_\theta : \theta \in \Theta\} with Θ⊆Rd\Theta \subseteq \R^d, and mean log-likelihood

Mn(θ)=1n∑i=1nlog⁡pθ(Xi),M(θ)=Eθ0[log⁡pθ(X)].M_n(\theta) = \frac{1}{n}\sum_{i=1}^n \log p_\theta(X_i), \qquad M(\theta) = \E_{\theta_0}\big[\log p_\theta(X)\big].

The MLE maximizes MnM_n. By the law of large numbers, Mn(θ)→M(θ)M_n(\theta) \to M(\theta) for each fixed θ\theta. If the maximum of MnM_n approaches the maximum of MM, we only need to know where the latter is. Jensen’s inequality tells us.

Proof

Since log⁡\log is strictly concave, Jensen gives

M(θ)−M(θ0)=Eθ0[log⁡pθ(X)pθ0(X)]≤log⁡Eθ0[pθ(X)pθ0(X)]=log⁡∫{pθ0>0}pθ≤log⁡1=0.M(\theta) - M(\theta_0) = \E_{\theta_0}\Big[\log \frac{p_\theta(X)}{p_{\theta_0}(X)}\Big] \le \log \E_{\theta_0}\Big[\frac{p_\theta(X)}{p_{\theta_0}(X)}\Big] = \log \int_{\{p_{\theta_0} > 0\}} p_\theta \le \log 1 = 0.

Equality in Jensen requires the ratio pθ/pθ0p_\theta/p_{\theta_0} to be constant almost surely under pθ0p_{\theta_0}, and equality in the last inequality requires pθp_\theta to assign no mass outside the support of pθ0p_{\theta_0}. Together they force the constant to be 1, i.e. pθ=pθ0p_\theta = p_{\theta_0} almost surely, and identifiability gives θ=θ0\theta = \theta_0. 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 Mn(θ)→M(θ)M_n(\theta) \to M(\theta) 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 MM 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.

  1. Uniform law. Under (i), (iii), and (iv), sup⁡θ∈Θ∣Mn(θ)−M(θ)∣→0\sup_{\theta \in \Theta} \abs{M_n(\theta) - M(\theta)} \to 0 in probability. Compactness lets us cover Θ\Theta by finitely many balls where log⁡pθ\log p_\theta oscillates little, and the envelope allows the law of large numbers to be applied to those oscillations (a Glivenko–Cantelli-type theorem).
  2. Separation. MM is continuous (dominated convergence using the envelope), Θ\Theta is compact, and θ0\theta_0 is the unique maximum, so for every ε>0\eps > 0 there is an η>0\eta > 0 with sup⁡∥θ−θ0∥≥εM(θ)≤M(θ0)−η\sup_{\norm{\theta - \theta_0} \ge \eps} M(\theta) \le M(\theta_0) - \eta.
  3. Putting them together. Since Mn(θ^n)≥Mn(θ0)M_n(\hat\theta_n) \ge M_n(\theta_0), adding and subtracting gives M(θ^n)≥M(θ0)−2sup⁡θ∣Mn−M∣M(\hat\theta_n) \ge M(\theta_0) - 2\sup_\theta\abs{M_n - M}. If ∥θ^n−θ0∥≥ε\norm{\hat\theta_n - \theta_0} \ge \eps, then 2sup⁡∣Mn−M∣≥η2\sup\abs{M_n - M} \ge \eta, whose probability tends to zero.

Asymptotic normality

Consistency says where θ^n\hat\theta_n ends up; now we want its distribution around that point. The idea is that near θ0\theta_0, the score equation Sn(θ)=∑iℓ′(θ;Xi)=0S_n(\theta) = \sum_i \ell'(\theta; X_i) = 0, with ℓ(θ;x)=log⁡pθ(x)\ell(\theta; x) = \log p_\theta(x), 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 θ^n≈N(θ0,1/(nI(θ0)))\hat\theta_n \approx \Normal(\theta_0, 1/(n I(\theta_0))): the MLE attains the Cramér–Rao bound in the limit.

Proof

Expand SnS_n around θ0\theta_0 with a second-order Lagrange remainder and evaluate at θ^n\hat\theta_n, which lies in UU with probability tending to one:

0=Sn(θ^n)=Sn(θ0)+(θ^n−θ0) Sn′(θ0)+12(θ^n−θ0)2 Sn′′(θ~n),0 = S_n(\hat\theta_n) = S_n(\theta_0) + (\hat\theta_n - \theta_0)\,S_n'(\theta_0) + \tfrac12(\hat\theta_n - \theta_0)^2\,S_n''(\tilde\theta_n),

where θ~n\tilde\theta_n lies between θ0\theta_0 and θ^n\hat\theta_n. Rearranging and multiplying by n\sqrt n,

n (θ^n−θ0)=n−1/2 Sn(θ0)−n−1Sn′(θ0)−12(θ^n−θ0) n−1Sn′′(θ~n).\sqrt n\,(\hat\theta_n - \theta_0) = \frac{n^{-1/2}\,S_n(\theta_0)}{-n^{-1}S_n'(\theta_0) - \tfrac12(\hat\theta_n - \theta_0)\,n^{-1}S_n''(\tilde\theta_n)}.

Numerator. Sn(θ0)S_n(\theta_0) is a sum of nn iid variables with mean 0 and variance I(θ0)I(\theta_0), so by the central limit theorem n−1/2Sn(θ0)→dN(0,I(θ0))n^{-1/2}S_n(\theta_0) \xrightarrow{d} \Normal(0, I(\theta_0)). First denominator term. By the law of large numbers, −n−1Sn′(θ0)=−n−1∑iℓ′′(θ0;Xi)→I(θ0)-n^{-1}S_n'(\theta_0) = -n^{-1}\sum_i\ell''(\theta_0; X_i) \to I(\theta_0) in probability. Remainder. ∣n−1Sn′′(θ~n)∣≤n−1∑iK(Xi)→EK(X)<∞\abs{n^{-1}S_n''(\tilde\theta_n)} \le n^{-1}\sum_i K(X_i) \to \E K(X) < \infty, so it is bounded in probability, and θ^n−θ0→0\hat\theta_n - \theta_0 \to 0 in probability by consistency: their product tends to 0. By Slutsky’s lemma, the ratio converges in distribution to N(0,I(θ0))/I(θ0)=N(0,I(θ0)−1)\Normal(0, I(\theta_0))/I(\theta_0) = \Normal(0, I(\theta_0)^{-1}).

∎

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 θ^n\hat\theta_n already to be close, which consistency supplies. In dd dimensions the argument is identical with vectors and matrices: with invertible Fisher information matrix I(θ0)\mat{I}(\theta_0), the multivariate CLT gives

n (θ^n−θ0)→dN(0, I(θ0)−1).\sqrt n\,(\hat\theta_n - \theta_0) \xrightarrow{d} \Normal\big(\vb{0},\, \mat{I}(\theta_0)^{-1}\big).

(The mean value theorem does not hold for vector functions with a single intermediate point; apply it row by row, with a different θ~\tilde\theta 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 n=20n = 20. The next interactive tests it with three models. For exponential rate λ\lambda, λ^=1/Xˉ\hat\lambda = 1/\bar X and I(λ)=1/λ2I(\lambda) = 1/\lambda^2; the shape of the distribution of n(λ^−λ)/λ\sqrt n(\hat\lambda - \lambda)/\lambda does not depend on λ\lambda, so we fix it at 1. For Poisson, λ^=Xˉ\hat\lambda = \bar X and I(λ)=1/λI(\lambda) = 1/\lambda. For gamma with unknown shape α\alpha and scale, α^\hat\alpha solves log⁡α−ψ(α)=log⁡Xˉ−log⁡X‾\log\alpha - \psi(\alpha) = \log\bar X - \overline{\log X}, with ψ\psi the digamma function, and its asymptotic variance, accounting for scale estimation, is α/(αψ′(α)−1)\alpha/(\alpha\psi'(\alpha) - 1).

InteractiveThe normal distribution emerges
Histogram of n(λ^−λ)\sqrt{n}(\hat\lambda - \lambda) with n=10n = 10 and limiting normal N(0,I(λ)−1)\mathcal{N}(0, I(\lambda)^{-1}), σ=1.000\sigma = 1.000
replicate mean
  • MLE replicates
  • limiting normal
  • replicate mean
Outside the plot (over 4.5σ): 1.1 % of replicates.
Model
10
3000 replicates
Replicates3000
Mean n(λ^−λ)\sqrt{n}(\hat\lambda - \lambda)0.360 (limit 0)
Standard deviation: actual | asymptotic1.241 | 1.000
Skewness (normal is 0)1.35
95 % Wald coverage95.4 % ± 0.8
Coverage is acceptable, but the histogram remains skewed: the two interval endpoints fail at different rates.
Each replicate simulates a sample of size nn, calculates the MLE, and adds n(θ^−θ)\sqrt n(\hat\theta - \theta) to the histogram; above is the limiting normal N(0,I(θ)−1)\Normal(0, I(\theta)^{-1}). Press play to accumulate 3000 replicates. Coverage is that of the Wald interval θ^±1.96 SE\hat\theta \pm 1.96\,\mathrm{SE}, with SE=(nI(θ^))−1/2\mathrm{SE} = (n I(\hat\theta))^{-1/2}, with its Monte Carlo error alongside. With exponential and n=10n = 10 you will see skew and a displaced replicate mean; increase nn. Then select Poisson and lower λ\lambda towards 0: the MLE sticks to the boundary, equals 0 in many replicates, and the Wald interval collapses.

Three lessons from the interactive. Skewness is the last thing to disappear. The normal has skewness 0; for exponential λ^=1/Xˉ\hat\lambda = 1/\bar X has inverse-gamma skewness 4n−2/(n−3)4\sqrt{n - 2}/(n - 3) (1.6 at n=10n = 10, 0.6 at n=50n = 50), and the two Wald interval ends fail at different rates even if total coverage seems reasonable. Total information matters, not nn. For Poisson, what matters is nλn\lambda, the expected event count: with λ=0.05\lambda = 0.05 and n=50n = 50 there are 2.5 expected events, P(λ^=0)=e−2.5≈0.08\Pr(\hat\lambda = 0) = e^{-2.5} \approx 0.08, 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 α\alpha has positive bias of order 1/n1/n (with α=2\alpha = 2, about 16 % at n=20n = 20 and 3 % at n=100n = 100) and a longer right tail.

Asymptotic efficiency and the superefficiency trap

The MLE’s asymptotic variance, I(θ)−1I(\theta)^{-1}, 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 I(θ)−1I(\theta)^{-1} in the limit? Joseph Hodges constructed a troubling counterexample in 1951. With Xi∼iidN(θ,1)X_i \iid \Normal(\theta, 1), define

Tn={Xˉnsi ∣Xˉn∣≥n−1/4,0si ∣Xˉn∣<n−1/4.T_n = \begin{cases} \bar X_n & \text{si } \abs{\bar X_n} \ge n^{-1/4}, \\ 0 & \text{si } \abs{\bar X_n} < n^{-1/4}. \end{cases}

If θ≠0\theta \neq 0, ∣Xˉn∣≥n−1/4\abs{\bar X_n} \ge n^{-1/4} with probability tending to one and TnT_n behaves like Xˉn\bar X_n: asymptotic variance 1. If θ=0\theta = 0, P(∣Xˉn∣<n−1/4)=P(∣Z∣<n1/4)→1\Pr(\abs{\bar X_n} < n^{-1/4}) = \Pr(\abs{Z} < n^{1/4}) \to 1 and n Tn→0\sqrt n\,T_n \to 0: asymptotic variance 0, better than the bound. It is superefficient at θ=0\theta = 0. The price appears in the risk near 0, rather than at the exact point.

[ ]Hodges' estimator and its riskBrowser
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 θ\theta. Hodges’ is nearly 0 at θ=0\theta = 0, but has a peak near θ≈n−1/4\theta \approx n^{-1/4} whose height grows without bound, on the order of n\sqrt n: 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 θ0+h/n\theta_0 + h/\sqrt n), none has asymptotic variance lower than I(θ0)−1I(\theta_0)^{-1}. MLE efficiency is therefore local and uniform optimality, not pointwise optimality.

Standard errors in practice

The theorem gives Var⁡(θ^n)≈(n I(θ0))−1\Var(\hat\theta_n) \approx (n\,\mat{I}(\theta_0))^{-1}, which depends on unknown θ0\theta_0. Three common substitutes are all consistent under the model:

Covariance estimatorFormulaWhen
Expected information at θ^\hat\theta(n I(θ^))−1(n\,\mat{I}(\hat\theta))^{-1}I\mat{I} in closed form
Observed informationJ(θ^)−1\mat{J}(\hat\theta)^{-1},  J(θ)=−∇2log⁡L(θ)\ \mat{J}(\theta) = -\hess \log L(\theta)used by almost all programs
Score outer product(∑i∇ℓi(θ^)∇ℓi(θ^)⊤)−1\big(\sum_i \grad\ell_i(\hat\theta)\grad\ell_i(\hat\theta)\T\big)^{-1}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 J(θ^)\mat{J}(\hat\theta) needs the Hessian. There are three routes. By hand, for a small model. Centered finite differences: ∂2f/∂θj∂θk≈[f(θ+hej+hek)−f(θ+hej−hek)−f(θ−hej+hek)+f(θ−hej−hek)]/(4h2)\partial^2 f/\partial\theta_j\partial\theta_k \approx [f(\theta + h\vb{e}_j + h\vb{e}_k) - f(\theta + h\vb{e}_j - h\vb{e}_k) - f(\theta - h\vb{e}_j + h\vb{e}_k) + f(\theta - h\vb{e}_j - h\vb{e}_k)]/(4h^2), with truncation error O(h2)\bigO(h^2) and rounding error O(εmaˊq/h2)\bigO(\eps_{\text{máq}}/h^2); the balance is at h≈εmaˊq1/4≈10−4h \approx \eps_{\text{máq}}^{1/4} \approx 10^{-4} 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 ϕ=h(θ)\phi = h(\theta), the covariance in ϕ\phi is that of θ\theta transformed by the Jacobian. This rule is the delta method, formalized in the next section. First, a complete gamma lab.

[ ]Gamma MLE, numerical Hessian, and Wald intervalsBrowser
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 (α,escala)(\alpha, \text{escala}) depend on data only through xˉ\bar x, and at the MLE xˉ=α^ escala^\bar x = \hat\alpha\,\widehat{\text{escala}}, so observed and expected information coincide exactly at θ^\hat\theta; the small difference is finite-difference error. Also, the MLE of the mean is exactly xˉ\bar x: the scale score equation is ∑ixi=nαs\sum_i x_i = n\alpha s. Its delta-method standard error, s^2 Var⁡(α^)+2s^α^Cov⁡+α^2Var⁡(s^)\sqrt{\hat s^2\,\Var(\hat\alpha) + 2\hat s\hat\alpha\Cov + \hat\alpha^2\Var(\hat s)}, is exactly s^α^/n\hat s\sqrt{\hat\alpha}/\sqrt n, the fitted gamma standard deviation divided by n\sqrt n (with the inverse Fisher matrix above, g⊤I−1g\vb{g}\T\mat{I}^{-1}\vb{g} simplifies to αs2\alpha s^2). It differs from sx/ns_x/\sqrt n, 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 α=2.5\alpha = 2.5 and scale 1.61.6 for several nn; estimands are α\alpha, scale, and mean; methods are Wald with expected information and the delta method; the performance measure is coverage with its Monte Carlo error.

[ ]Wald interval coverage (ADEMP)Browser
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 n=15n = 15 each interval fails in its own way: scale coverage is about 82 %, mean about 91 %, and shape overshoots (97 %), because α^\hat\alpha has positive bias and its estimated standard error increases with α^\hat\alpha. With n=50n = 50 scale is still at 90 %, and only at n=200n = 200 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.

[ ]The same gamma with statsmodelsBrowser
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: SE(g(θ^))≈G Var⁡^(θ^) G⊤\mathrm{SE}(g(\hat\theta)) \approx \sqrt{\mat{G}\,\widehat{\Var}(\hat\theta)\,\mat{G}\T}, with G\mat{G} evaluated at θ^\hat\theta. The proof is short: write g(Tn)−g(θ)=G(Tn−θ)+R(Tn−θ) ∥Tn−θ∥g(T_n) - g(\theta) = \mat{G}(T_n - \theta) + R(T_n - \theta)\,\norm{T_n - \theta}, where R(h)→0R(\vb{h}) \to \vb{0} as h→0\vb{h} \to \vb{0} by differentiability. The first term, multiplied by n\sqrt n, converges to the stated normal. The second is R(Tn−θ)⋅n∥Tn−θ∥R(T_n - \theta)\cdot\sqrt n\norm{T_n - \theta}: the first factor tends to zero in probability because Tn→θT_n \to \theta, 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 gg with its tangent at θ\theta. An affine map transforms one normal into another, and the tangent slope multiplies standard deviation. The approximation is good when gg is nearly straight on the scale over which θ^\hat\theta moves, i.e. over an interval of a few standard errors. One dimensionless number summarizes this: relative curvature SE⋅∣g′′/g′∣\mathrm{SE}\cdot\abs{g''/g'}, the relative change in slope over one standard error.

InteractiveThe delta method is a tangent
y=log⁡xy = \log x, its tangent at μ\mu, and distributions of θ^\hat\theta (bottom) and g(θ^)g(\hat\theta) (left)
tangent
  • distribution of θ^\hat\theta
  • true distribution of g(θ^)g(\hat\theta)
  • delta-method normal
  • quantiles ±1 and ±2 se along the curve
Function gg
2.000
0.300
g(μ)g(\mu) | g′(μ)g'(\mu)0.693 | 0.500
Delta standard error ∣g′(μ)∣ se|g'(\mu)|\,\mathrm{se}0.150
True central 68 % half-width0.151
Relative curvature se ∣g′′/g′∣\mathrm{se}\,|g''/g'|0.150
Total variation distance4.4 %
On the se scale the curve is nearly straight: the tangent transforms the normal into another nearly exact normal.
Below is the distribution of θ^∼N(μ,se2)\hat\theta \sim \Normal(\mu, \mathrm{se}^2), whose center can be dragged. On the left, orange shows the exact distribution of g(θ^)g(\hat\theta), obtained by change of variable; the dashed curve is the delta-method normal, the image of the distribution below under the tangent. Orange points are the curve's images of μ\mu, μ±se\mu \pm \mathrm{se} and μ±2 se\mu \pm 2\,\mathrm{se}; open blue points are their images under the tangent. With log⁡x\log x, increase se or move μ\mu toward 0: the left points separate from those of the tangent and the true distribution becomes skewed. With x2x^2, move μ\mu to 0: the tangent is horizontal and the delta method predicts a degenerate distribution.

Variance-stabilizing transformations

Often asymptotic variance depends on the parameter itself: n(Tn−θ)→N(0,σ2(θ))\sqrt n(T_n - \theta) \to \Normal(0, \sigma^2(\theta)). This complicates intervals and plots, because every estimate has different precision. The delta method suggests a remedy: choose gg with g′(θ) σ(θ)g'(\theta)\,\sigma(\theta) constant, that is,

g(θ)=∫ ⁣dθσ(θ).g(\theta) = \int \frac{\dd\theta}{\sigma(\theta)}.
Modelσ2(θ)\sigma^2(\theta)ggVariance of g(Tn)g(T_n)
Poisson, Tn=XˉT_n = \bar Xλ\lambdaλ\sqrt\lambda1/(4n)1/(4n)
Binomial, Tn=p^T_n = \hat pp(1−p)p(1 - p)arcsin⁡p\arcsin\sqrt p1/(4n)1/(4n)
Exponential, Tn=λ^T_n = \hat\lambdaλ2\lambda^2log⁡λ\log\lambda1/n1/n
Bivariate normal correlation(1−ρ2)2(1 - \rho^2)^2artanh⁡ρ\operatorname{artanh}\rho1/n1/n (in practice, 1/(n−3)1/(n - 3))

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.

[ ]Stabilizing the variance of a proportionBrowser
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 p^\hat p changes by a factor of 5 between p=0.05p = 0.05 and p=0.5p = 0.5; that of arcsin⁡p^\arcsin\sqrt{\hat p} remains near 1/(4n)1/(4n) except at p=0.05p = 0.05, where np=2.5np = 2.5 is small and the approximation has not yet taken hold.

M-estimators and sandwich variance

The proof of MLE normality barely used that SnS_n was a log-likelihood derivative. It used three facts: θ^\hat\theta 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: mθ=log⁡pθm_\theta = \log p_\theta, ψθ\psi_\theta = score.
  • Least squares: mβ(x,y)=−(y−x⊤β)2m_\beta(x, y) = -(y - x\T\beta)^2, ψβ=x(y−x⊤β)\psi_\beta = x(y - x\T\beta).
  • Quantile τ\tau: ψθ(x)=1[x≤θ]−τ\psi_\theta(x) = \ind[x \le \theta] - \tau (not differentiable, but the theory extends).
  • Method of moments and generalized method of moments: ψθ(x)=g(x)−Eθg(X)\psi_\theta(x) = g(x) - \E_\theta g(X).
  • Empirical risk minimization in machine learning: mθ=−ℓ(fθ(x),y)m_\theta = -\ell(f_\theta(x), y). The ERM of m13 is exactly this, and neural-network training losses are M-estimators without an underlying probabilistic model.

The matrix A−1BA−T\mat{A}^{-1}\mat{B}\mat{A}^{-\mathsf T} is the sandwich variance: A−1\mat{A}^{-1} is the bread and B\mat{B} the meat. The proof is exactly the MLE proof: 0=Ψn(θ^n)=Ψn(θ∗)+Ψ˙n(θ~)(θ^n−θ∗)\vb{0} = \Psi_n(\hat\theta_n) = \Psi_n(\theta^*) + \dot\Psi_n(\tilde\theta)(\hat\theta_n - \theta^*), hence n(θ^n−θ∗)=−Ψ˙n(θ~)−1n Ψn(θ∗)\sqrt n(\hat\theta_n - \theta^*) = -\dot\Psi_n(\tilde\theta)^{-1}\sqrt n\,\Psi_n(\theta^*). The multivariate CLT gives n Ψn(θ∗)→N(0,B)\sqrt n\,\Psi_n(\theta^*) \to \Normal(\vb{0}, \mat{B}), the law of large numbers and consistency give Ψ˙n(θ~)→A\dot\Psi_n(\tilde\theta) \to \mat{A}, and Slutsky gives the product. The only change is that no equality now relates A\mat{A} to B\mat{B}.

For the MLE under the correct model, A=E[∇2log⁡pθ0]=−I(θ0)\mat{A} = \E[\hess\log p_{\theta_0}] = -\mat{I}(\theta_0) and B=E[∇log⁡p ∇log⁡p⊤]=I(θ0)\mat{B} = \E[\grad\log p\,\grad\log p\T] = \mat{I}(\theta_0): the sandwich reduces to I−1II−1=I−1\mat{I}^{-1}\mat{I}\mat{I}^{-1} = \mat{I}^{-1}. The simplification is exactly the information equality. Otherwise estimate the full sandwich, replacing expectations with means:

A^=1n∑i∂ψθ(Xi)∂θ⊤∣θ^,B^=1n∑iψθ^(Xi) ψθ^(Xi)⊤,Var⁡^(θ^)=1n A^−1B^A^−T.\hat{\mat{A}} = \frac1n\sum_i \frac{\partial\psi_\theta(X_i)}{\partial\theta\T}\Big|_{\hat\theta}, \qquad \hat{\mat{B}} = \frac1n\sum_i \psi_{\hat\theta}(X_i)\,\psi_{\hat\theta}(X_i)\T, \qquad \widehat{\Var}(\hat\theta) = \frac1n\,\hat{\mat{A}}^{-1}\hat{\mat{B}}\hat{\mat{A}}^{-\mathsf T}.

For least squares, A^=−X⊤X/n\hat{\mat{A}} = -\mat{X}\T\mat{X}/n and B^=∑ie^i2 xixi⊤/n\hat{\mat{B}} = \sum_i \hat e_i^2\,\vb{x}_i\vb{x}_i\T/n, 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 g(θ)g(\theta), stack the equation η−g(θ)=0\eta - g(\theta) = 0 onto those for θ\theta and apply the sandwich to the full system. The generic implementation below does this for the coefficient of variation σ/μ\sigma/\mu, which requires estimating mean and variance together.

[ ]Generic M-estimation and the sandwich by stackingBrowser
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 gg and covariance of (xˉ,s2)(\bar x, s^2), 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 QQ outside {pθ}\{p_\theta\}? The MLE is an M-estimator with mθ=log⁡pθm_\theta = \log p_\theta, so it converges to the maximizer of EQlog⁡pθ(X)\E_Q\log p_\theta(X). Repeating the Jensen calculation,

θ∗=arg max⁡θEQ[log⁡pθ(X)]=arg min⁡θKL⁡(Q ∥ pθ).\theta^* = \argmax_\theta \E_Q\big[\log p_\theta(X)\big] = \argmin_\theta \KL(Q \,\|\, p_\theta).

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 −A≠B-\mat{A} \neq \mat{B} in general, the variance printed by software, (−A)−1(-\mat{A})^{-1}, is incorrect, and may be too large or too small.

EQ[1λ∗−X]=0  ⟺  λ∗=1μ\E_Q\Big[\frac{1}{\lambda^*} - X\Big] = 0 \iff \lambda^* = \frac1\mu
The estimating equation is the exponential score, ψλ(x)=1/λ−x\psi_\lambda(x) = 1/\lambda - x; its population root is the pseudo-true value.
1/5
[ ]Model versus sandwich standard errors with lognormal dataBrowser
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 σ=1\sigma = 1, CV2=e−1≈1.72\mathrm{CV}^2 = e - 1 \approx 1.72: model standard error is too small by a factor 1.72≈1.31\sqrt{1.72} \approx 1.31, 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, E[Y∣x]=exp⁡(β0+β1x)\E[Y \given x] = \exp(\beta_0 + \beta_1 x), fitted to counts with greater variance than mean. There is additional good news: if the mean is correctly specified, pseudo-truth is the true β\beta even when the distribution differs. The Poisson score equation, ∑i(yi−μi)xi=0\sum_i(y_i - \mu_i)\vb{x}_i = \vb{0}, involves only the mean, and its expectation vanishes at the true β\beta (Gourieroux, Monfort and Trognon, 1984, proved this for every linear exponential family). What fails is variance: if Var⁡(Y∣x)=μ+αμ2\Var(Y \given x) = \mu + \alpha\mu^2 (negative binomial), B=E[μ(1+αμ)xx⊤]\mat{B} = \E[\mu(1 + \alpha\mu)\vb{x}\vb{x}\T] is greater than −A=E[μ xx⊤]-\mat{A} = \E[\mu\,\vb{x}\vb{x}\T], and model standard error underestimates true uncertainty.

InteractiveSandwich versus model when the model lies
95 % interval coverage for β1\beta_1 (300 replicates per point, n=200n = 200)
nominal 95 %
  • model SE
  • sandwich SE
  • model, asymptotic theory
  • 95 % ± Monte Carlo error
30 replicates with α=1.00\alpha = 1.00: 13 model and 2 sandwich intervals fail
  • sandwich (above)
  • model (below)
  • does not cover 1
1.00
Sample size nn
Coverage with model SE74.3 %
Coverage with sandwich SE95.3 %
Actual standard deviation of β^1\hat\beta_10.1659
Mean SE: model | sandwich0.0977 | 0.1672
Mean β^1\hat\beta_1 (truth 1)1.0054
Model SE underestimates actual spread by a factor of 1.70: the “95 %” interval covers only 74 %. The point estimate remains good.
Negative-binomial counts with E[Y∣x]=exp⁡(0.5+x)\E[Y \given x] = \exp(0.5 + x), x∼Unif⁡(−1,1)x \sim \Unif(-1, 1) and variance μ+αμ2\mu + \alpha\mu^2, fitted with Poisson regression. For each α\alpha, 300 replicates are simulated and coverage of β^1±1.96 SE\hat\beta_1 \pm 1.96\,\mathrm{SE} is measured with model and sandwich standard errors; the dashed grey line is theoretical asymptotic coverage of the former. At right are 30 replicates, red for intervals that do not contain the true value. Increase α\alpha and compare; then lower nn to 50 to see that the sandwich also has a small-sample cost.

Asymptotic theory predicts that with α=1\alpha = 1, true variance of β^1\hat\beta_1 is 3.1 times the model’s assumption and its interval covers around 74 %; with α=2\alpha = 2, the factor is 5.1 and coverage drops to 61 %. The sandwich remains near 95 %. With n=50n = 50 it falls slightly below nominal: B^\hat{\mat{B}} is calculated using squared residuals from observations that helped fit β^\hat\beta, 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 EFtψT(Ft)(X)=0\E_{F_t}\psi_{T(F_t)}(X) = 0 at t=0t = 0 gives IF(x)=−A−1ψθ∗(x)\mathrm{IF}(x) = -\mat{A}^{-1}\psi_{\theta^*}(x): influence is proportional to ψ\psi. Asymptotic variance is E[IF IF⊤]=A−1BA−T\E[\mathrm{IF}\,\mathrm{IF}\T] = \mat{A}^{-1}\mat{B}\mat{A}^{-\mathsf T}, the sandwich: asymptotic variance and robustness are two readings of the same function. For the mean, ψ(x)=x−μ\psi(x) = x - \mu and IF(x)=x−μ\mathrm{IF}(x) = x - \mu, unbounded. For the median, IF(x)=sign⁡(x−m)/(2f(m))\mathrm{IF}(x) = \operatorname{sign}(x - m)/(2f(m)), 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 wi=min⁡(1,k/∣ri∣)w_i = \min(1, k/\abs{r_i}) on scaled residuals rir_i, the equation is ∑iwi(xi−μ)=0\sum_i w_i(x_i - \mu) = 0, i.e. μ\mu is a weighted mean; alternate weights and mean until convergence. Scale is estimated separately, robustly, using MAD divided by Φ−1(3/4)≈0.6745\Phi^{-1}(3/4) \approx 0.6745; with bounded monotone ψ\psi and this scale, the estimator’s breakdown point is 50 %, like the median’s.

Under N(0,1)\Normal(0, 1) with known scale, A=−Eψk′(Z)=−(2Φ(k)−1)A = -\E\psi_k'(Z) = -(2\Phi(k) - 1) and B=Eψk(Z)2=2Φ(k)−1−2kφ(k)+2k2(1−Φ(k))B = \E\psi_k(Z)^2 = 2\Phi(k) - 1 - 2k\varphi(k) + 2k^2(1 - \Phi(k)), so

efficiency(k)=1A−2B=(2Φ(k)−1)22Φ(k)−1−2kφ(k)+2k2(1−Φ(k)),γ∗(k)=k2Φ(k)−1.\text{efficiency}(k) = \frac{1}{A^{-2}B} = \frac{(2\Phi(k) - 1)^2}{2\Phi(k) - 1 - 2k\varphi(k) + 2k^2\big(1 - \Phi(k)\big)}, \qquad \gamma^*(k) = \frac{k}{2\Phi(k) - 1}.

Efficiency and sensitivity both increase with kk. At k=1.345k = 1.345 efficiency is exactly 95 %, so it is the default in almost every library.

InteractiveTuning Huber
Influence function IF(x)\mathrm{IF}(x) under N(0,1)\mathcal{N}(0, 1)
γ* = 1.64
Asymptotic efficiency versus the mean under normality
median 2/π95 % at k = 1.345
A sample of 80 with 10 % contaminated around x0=6.0x_0 = 6.0
  • mean
  • median
  • Huber (MAD scale)
  • contaminants
Asymptotic bias with ε=10 %\varepsilon = 10\,\% at x0=6.0x_0 = 6.0
k minimaxmedianmean: 0.60 (off scale)
1.345
10 %
6.0
Efficiency under the normal95.0 %
Gross-error sensitivity γ∗\gamma^*1.637
Asymptotic bias: Huber | median | mean0.182 | 0.140 | 0.600
Minimax kk for this ε\varepsilon1.140
Sample: mean | median | Huber0.700 | 0.278 | 0.305
Top left: influence functions of the mean (straight line), median (step), and Huber estimator (ramp bounded by γ∗\gamma^*; the shaded band is ∣x∣≤k\abs{x} \le k). Top right: efficiency under normality versus kk. Bottom right: asymptotic bias under contamination (1−ε)N(0,1)+ε δx0(1 - \varepsilon)\Normal(0, 1) + \varepsilon\,\delta_{x_0}, with median and mean as references, and in grey Huber's minimax kk for that ε\varepsilon. Bottom left: a contaminated sample and the three estimates. Move kk: no value wins in both right-hand panels at once. Move x0x_0 away: Huber's bias does not grow, but the mean's does.

The interactive shows the full tradeoff. Huber’s asymptotic bias under contamination is bounded by something of order εγ∗\varepsilon\gamma^* regardless of how far away x0x_0 is; the mean’s is εx0\varepsilon x_0 and unbounded. Huber (1964) also proved that if the true distribution can be any (1−ε)Φ+εH(1 - \varepsilon)\Phi + \varepsilon H with arbitrary symmetric HH, the estimator minimizing maximum asymptotic variance is Huber’s with kk solving

2φ(k)k−2Φ(−k)=ε1−ε.\frac{2\varphi(k)}{k} - 2\Phi(-k) = \frac{\varepsilon}{1 - \varepsilon}.

For k=1.345k = 1.345 this corresponds to ε≈5.8 %\varepsilon \approx 5.8\,\%, and k=1k = 1 to ε≈14.3 %\varepsilon \approx 14.3\,\%. 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.

[ ]Huber from scratch versus mean, median, and statsmodelsBrowser
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 ∣xi−μ∣\abs{x_i - \mu} at current μ\mu (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 k=1.345k = 1.345 retains efficiency near the theoretical 95 %, with k=1k = 1 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 Φ−1(0.5/0.9)≈0.14\Phi^{-1}(0.5/0.9) \approx 0.14, beats Huber with k=1.345k = 1.345: contamination is nearly twice the 5.8 % for which that kk is minimax, and bias dominates MSE. With k=1k = 1, 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 Θ=[0,∞)\Theta = [0, \infty) and θ0=0\theta_0 = 0, the interior-point assumption fails. With Xi∼iidN(θ,1)X_i \iid \Normal(\theta, 1), the constrained MLE is θ^=max⁡(0,Xˉ)\hat\theta = \max(0, \bar X) and n θ^→max⁡(0,Z)\sqrt n\,\hat\theta \to \max(0, Z): a mixture of point mass 1/2 at 0 and half a normal distribution. The likelihood-ratio statistic converges to 12χ02+12χ12\tfrac12\chi^2_0 + \tfrac12\chi^2_1 (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 Unif⁡(0,θ)\Unif(0, \theta), likelihood is not differentiable at the maximum, score does not have mean zero, and the MLE, max⁡iXi\max_i X_i, converges at rate 1/n1/n: n(θ−θ^n)/θ→Exp(1)n(\theta - \hat\theta_n)/\theta \to \mathrm{Exp}(1). Neither normal nor n\sqrt n.

The number of parameters grows with nn. This is the most treacherous because the model is perfectly regular. Neyman and Scott (1948) illustrated it with pairs: Xi1,Xi2∼iidN(μi,σ2)X_{i1}, X_{i2} \iid \Normal(\mu_i, \sigma^2) for i=1,…,mi = 1, \dots, m, with a mean for each pair and a common variance. The MLE of each μi\mu_i is the pair mean, and that of variance is

σ^2=12m∑i=1m∑j=12(Xij−Xˉi)2=14m∑i=1m(Xi1−Xi2)2→pσ22,\hat\sigma^2 = \frac{1}{2m}\sum_{i=1}^m\sum_{j=1}^2 (X_{ij} - \bar X_i)^2 = \frac{1}{4m}\sum_{i=1}^m (X_{i1} - X_{i2})^2 \xrightarrow{p} \frac{\sigma^2}{2},

because Xi1−Xi2∼N(0,2σ2)X_{i1} - X_{i2} \sim \Normal(0, 2\sigma^2). With n=2mn = 2m observations and m+1m + 1 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 p/np/n the MLE systematically overestimates coefficients (Sur and Candès, 2019).

[ ]Neyman–Scott: more data do not fix itBrowser
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 Di=Xi1−Xi2∼N(0,2σ2)D_i = X_{i1} - X_{i2} \sim \Normal(0, 2\sigma^2) do not depend on the μi\mu_i, and their likelihood gives consistent σ~2=∑iDi2/(2m)\tilde\sigma^2 = \sum_i D_i^2/(2m). This is marginal likelihood; conditional and modified profile versions use the same idea.

Common mistakes

Exercises

ProofAsymptotic normality of the MLE
Prove: Under the theorem assumptions (interior point, consistent root, dominated third derivative and information equality), n(θ^n−θ0)→N(0,I(θ0)−1)\sqrt n(\hat\theta_n - \theta_0) \to \Normal(0, I(\theta_0)^{-1}) in distribution.
0
Let Sn(θ)=∑iℓ′(θ;Xi)S_n(\theta) = \sum_i \ell'(\theta; X_i) be the score and θ^n\hat\theta_n a consistent root of Sn(θ)=0S_n(\theta) = 0.

Step 1 of 4. Which expansion do you start with?

ProofThe univariate delta method
Prove: If n(Tn−θ)→N(0,σ2)\sqrt n(T_n - \theta) \to \Normal(0, \sigma^2) in distribution and gg is differentiable at θ\theta, then n(g(Tn)−g(θ))→N(0,g′(θ)2σ2)\sqrt n(g(T_n) - g(\theta)) \to \Normal(0, g'(\theta)^2\sigma^2).
0
Define R(h)=(g(θ+h)−g(θ)−g′(θ)h)/hR(h) = \big(g(\theta + h) - g(\theta) - g'(\theta)h\big)/h for h≠0h \neq 0 and R(0)=0R(0) = 0.

Step 1 of 4. What property of RR follows from differentiability of gg at θ\theta?

NumericStandard error of log odds
In a sample of n=200n = 200 you observe p^=0.3\hat p = 0.3. Use the delta method to approximate the standard error of log⁡(p^/(1−p^))\log\big(\hat p/(1 - \hat p)\big).
NumericStabilizing a Poisson
With X1,…,X100∼iidPois⁡(λ)X_1, \dots, X_{100} \iid \Pois(\lambda), what is the approximate standard error of Xˉ\sqrt{\bar X} according to the delta method? (It does not depend on λ\lambda.)
NumericHuber with k = 1
Using the lesson's formula, calculate asymptotic efficiency of Huber's estimator with k=1k = 1 (known scale) relative to the mean under a standard normal. Give a number between 0 and 1.
NumericSandwich-to-model ratio
You fit an exponential by maximum likelihood to data actually following a gamma of shape 4 (coefficient of variation 1/21/2). For large nn, what is the ratio of sandwich standard error of λ^\hat\lambda to model-based standard error?
QuizHodges' estimator
Hodges' estimator has asymptotic variance 0 at θ=0\theta = 0 and 1 elsewhere, versus 1 everywhere for the sample mean. Which conclusion is correct?
QuizIncidental parameters
In Neyman–Scott (mm pairs, each with its own mean μi\mu_i and a common variance σ2\sigma^2), the MLE of σ2\sigma^2 converges to σ2/2\sigma^2/2 as m→∞m \to \infty. Why does consistency fail and how is it fixed?
QuizWhich standard error would you report?
You fit Poisson regression by maximum likelihood to user visit counts. The conditional mean appears well specified, but sample residual variance is about three times the fitted mean. Which statements are correct?

More than one answer may be correct.

CodeSandwich variance of a Poisson regression
Complete varianzas_poisson(X, y, beta) to return (V_modelo, V_sandwich): estimated model-based covariance of β^\hat\beta, (X⊤WX)−1(\mat{X}\T\mat{W}\mat{X})^{-1} with W=diag⁡(μ^)\mat{W} = \diag(\hat\mu), and sandwich covariance, (X⊤WX)−1(∑i(yi−μ^i)2xixi⊤)(X⊤WX)−1(\mat{X}\T\mat{W}\mat{X})^{-1}\big(\sum_i (y_i - \hat\mu_i)^2\vb{x}_i\vb{x}_i\T\big)(\mat{X}\T\mat{W}\mat{X})^{-1}. Both already include 1/n1/n (they are covariances of β^\hat\beta, not of nβ^\sqrt n\hat\beta). 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_sandwich
Shift+Enter to run

Summary

Key idea
With many observations, any estimator solving “empirical mean of ψ\psi equals zero” is approximately normal with covariance A−1BA−T/n\mat{A}^{-1}\mat{B}\mat{A}^{-\mathsf T}/n; if it is the MLE under a correct model, information equality reduces this to I−1/n\mat{I}^{-1}/n, and if the model is false, the sandwich remains the honest answer.
  • Consistency. The MLE maximizes an empirical mean whose limit, Eθ0log⁡pθ\E_{\theta_0}\log p_\theta, is maximized at θ0\theta_0 by Jensen and identifiability. With uniform convergence and a well-separated maximum (Wald), θ^n→θ0\hat\theta_n \to \theta_0.
  • Normality. Taylor expansion of score, CLT in the numerator, LLN in the denominator, and Slutsky: n(θ^n−θ0)→N(0,I(θ0)−1)\sqrt n(\hat\theta_n - \theta_0) \to \Normal(0, \mat{I}(\theta_0)^{-1}). The approximation takes longer with skewness, little total information, or parameters near a boundary.
  • Efficiency. The MLE attains I−1\mat{I}^{-1}, 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. SE(g(θ^))≈∣g′(θ^)∣ SE(θ^)\mathrm{SE}(g(\hat\theta)) \approx \abs{g'(\hat\theta)}\,\mathrm{SE}(\hat\theta), or ∇g⊤Σ∇g\sqrt{\grad g\T\mat{\Sigma}\grad g}: replace gg with its tangent. It fails if relative curvature is not small or g′=0g' = 0. Variance-stabilizing transformations choose g′∝1/σ(θ)g' \propto 1/\sigma(\theta).
  • 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 ψ\psi. Huber bounds ψ\psi at ±k\pm k: with k=1.345k = 1.345, 95 % efficiency under normality and bounded bias under contamination.
  • Limits. Boundaries, parameter-dependent supports, and incidental parameters (Neyman–Scott) break classical theory.