Fisher information and the Cramér-Rao bound
Measure how much information an observation contains about a parameter. Prove score properties (zero mean and variance equal to information), both Fisher-information expressions and their matrix form, and the Cramér–Rao lower bound on variance of unbiased estimators. Interpret information as log-likelihood curvature and a metric leading to the natural gradient.
After this lesson you can
- Prove that score has zero mean and variance equal to Fisher information under regularity conditions.
- Calculate expected and observed Fisher information in scalar and multiparameter models, including the normal matrix.
- Prove the Cramér–Rao bound and determine whether an estimator is efficient.
- Transform information under reparameterization and add it for iid samples.
- Identify when regularity fails (parameter-dependent support) and the bound does not apply.
Before you start
Motivation: how much data is needed?
You will measure a component’s failure rate and want to know its absolute precision. With independent tests, frequency has variance , so a interval with half-width needs approximately tests. For this gives when and only when . In absolute terms, estimating a parameter near the boundary is about 25 times cheaper.
But if relative precision matters (within of the value), the calculation reverses: requires about 385 tests at and at . The answer to “how much data?” depends on which parameter is measured and how much one observation teaches about it. The second quantity has a name and formula: Fisher information. This lesson defines and computes it, proves it sets a universal lower bound on variance of unbiased estimators (the Cramér–Rao bound), and explains when the bound is attained and when it cannot be applied.
The result matters outside classical statistics. Fisher information is local curvature of KL divergence between neighboring models, the natural metric on parameter space, the matrix preconditioning the m06 natural gradient, the weight Elastic Weight Consolidation uses to avoid forgetting tasks, and posterior Gaussian precision in the Laplace approximation. All follow from one identity: variance of the derivative of log-likelihood.
Score and its two properties
Work with a statistical model with open (multiple parameters come below). For one observation , log-likelihood is and its derivative is the score
Score evaluated at random variable is a random variable. It measures the direction and force with which the observation pushes the parameter. Conditions are needed for good behavior.
Condition 1 is the most forgotten and most consequential: if support moves with , a boundary term appears in Leibniz’s rule and the next two properties cease to hold (as uniform shows at the end).
Proof
Since is a density, for every . Differentiate under the integral (condition 3):
which is the first equality. For the second, differentiate again. By the product rule, , using . Integrating,
Since , .
∎Interpretation: if data come from the model with the evaluated, score is unbiased: on average, an observation pushes the parameter neither up nor down. Random score fluctuations have magnitude equal to mean log-likelihood curvature. The next figure makes this visible by plotting scores of many simulated samples.
Two readings. At curves cross the horizontal axis distributed symmetrically and mean (orange) passes through zero: . Away from , mean score is nonzero, and the mean curve’s slope at is : that tilt lets likelihood “feel” a wrong parameter. A steep score quickly separates parameters; a shallow one confuses them.
Fisher information
Two useful interpretations. The variance form says measures score agitation: a highly variable score discriminates parameter values well. The curvature form says is log-likelihood curvature and its mean: a likelihood sharply peaked around truth locates it precisely. The next section’s first figure shows this.
Before continuing, examples used constantly. In each, is information from one observation.
| Model | Parameter | |
|---|---|---|
| Exponential, rate | ||
| , known | ||
| , known | ||
| Laplace, scale , location | ||
| Logistic, scale , location | ||
| Cauchy, scale , location |
Observed information
Fisher information is an expectation: a model property at unknown true . With data you have something different: curvature of your log-likelihood.
Both measure the same thing but are not equal: promises an average over samples you could obtain; is what this sample gave. Later you will see why observed information is often useful for standard errors. They agree, , in exponential families and all their parameterizations: depends on data only through the sufficient statistic, and the likelihood equation fixes it at its expectation under . This occurs for Poisson (where ) or normal in at the MLE.
Curvature as precision
For Bernoulli data, the next figure plots for two parameter values at the same . The osculating parabola has the same curvature at the maximum, , and defines : precisely the interval obtained by dropping units from a parabola’s maximum.
At , expected information is and , a factor . Interval width is proportional to : for and for , a factor . But width relative to is in the first and in the second: on the parameter’s own scale, is poorly measured. Information depends on parameterization, as seen next.
Additivity and reparameterization
Proof
Sample score is , a sum of independent zero-mean variables. Variance of an independent sum is the sum of variances: .
∎Information grows linearly with data: each independent observation contributes. This is why the Cramér–Rao bound decreases as .
Proof
By the chain rule, . Factor is constant with respect to , so its square leaves the variance: .
∎Information is not a number belonging to the model, but a measure of the parameter: it changes by the square of a scale-change factor. For Bernoulli with (logit), and , so
On logit scale, information vanishes as : this is what the figure’s relative width expressed. With , for every : a scale where precision is value-independent. This is the Bernoulli variance-stabilizing transformation, and square root of information determines Jeffreys prior in Bayesian inference.
Multiple parameters: the information matrix
Now is open. Score is the gradient . Regularity conditions apply componentwise, and both score properties are proved the same way: and .
Immediate properties: symmetric and positive semidefinite, because (positive definite matrix). It is positive definite if and only if no nonzero linear combination of score components is almost surely constant: if almost surely, moving in direction does not change density to first order, so data do not distinguish that direction to first order. This typically signals local nonidentifiability, though it does not imply it: in information at is zero but the model is identifiable (revisit identifiability in lesson 2). Additivity: . The Jacobian rule becomes matrix-valued.
Proof is the scalar one using multivariate chain rule: and .
Normal in
For , and, with ,
Then , (because ), and , because standard normal odd moments vanish. The matrix is diagonal:
and are called orthogonal parameters. Their statistical meaning is clear: inverse is estimator asymptotic covariance and diagonal, so and are asymptotically uncorrelated (for normal they are actually independent for every ). Orthogonality is a parameterization property, not a model property.
The Jacobian rule quickly gives other parameterizations. With , and . With , and : a constant, because on log scale estimating a scale costs the same whatever its value. But switching to with (e.g. a normal quantile), Jacobian mixes coordinates and
Estimated quantile and scale are correlated even though mean and scale are not. The next interactive displays this on the confidence ellipse.
Blue ellipse (quadratic, information-based) and gray line (exact image) agree to first order and separate when is small and transformation highly curved, such as near . This is the delta method: Jacobian rule linearizes reparameterization.
Cramér–Rao bound
The central result: an unbiased estimator may have many variances, but not any variance; model information sets a floor.
Proof
Let be sample score, with and . Differentiating under the integral,
the last equality because . Now Cauchy-Schwarz in ( spaces) for covariance: . Therefore
which is the bound.
∎The proof is short, but each step works. Equality ties estimator sensitivity to the parameter to its correlation with score; Cauchy-Schwarz bounds that correlation by ; and score variance is information. Bound recovers the opening intuition: unbiased estimator standard error cannot fall below .
Known bias. If has bias , then and the bound is . With MSE, . For example, in with known , shrunk estimator has , , and variance : it attains the biased bound. Biased estimators such as regularized ones are not subject to ; they can go below it at the cost of bias.
Multiple parameters. If estimates with and Jacobian matrix , then in Loewner order,
meaning the difference is positive semidefinite.
Proof
The preceding argument gives (), and covariance of vector is positive semidefinite:
Since , the block’s Schur complement is also positive semidefinite: .
∎One special case is constant use: estimating a single parameter without knowing others, , and (Cauchy-Schwarz in the inner product). Not knowing other parameters costs information unless orthogonal: for normal , estimating costs the same whether is known; for it does not.
Efficient estimators
This is the estimator lesson’s relative efficiency, taking the bound’s unattainable optimum as reference. When do efficient estimators exist? The bound’s proof says equality in Cauchy-Schwarz occurs when is proportional to score.
Proof
Equality in Cauchy-Schwarz requires almost surely; multiplying by and taking expectations gives , yielding the expression for . For fixed , integrate with respect to : , where and . Conversely, in an exponential family , satisfying equality in Cauchy-Schwarz.
∎Known examples follow: is efficient for in normal, for in Poisson (variance ), for in Bernoulli (variance ), and for exponential mean . Cases with no efficient estimator follow too: the bound exists but none reaches it. For normal, is unbiased for with variance , while the bound is : efficiency , e.g. at . Yet is the best possible unbiased estimator (proved in optimal estimators): the bound was unattainable. For exponential rate , unbiased estimator of has variance versus bound .
The race
Although an efficient unbiased estimator may not exist, the MLE is asymptotically efficient: MLE asymptotic normality (lesson 8) says , with limiting variance exactly the bound. Check three scale- location families: normal (), Laplace (), and logistic ().
Exact asymptotic efficiency limits are below (with , and trimmed mean computed by numerical integration; see previous lesson).
| Family | mean | median | 20% trimmed | MLE |
|---|---|---|---|---|
| Normal | (mean) | |||
| Laplace | (median) | |||
| Logistic |
(Logistic mean: and per-observation bound , so efficiency is .) Two observations about such results. Laplace median is MLE but at finite lies below the limit (simulated efficiency is at ) and converges slowly. Estimator ranking depends on family: no universal “best” except MLE, the only winner in all three.
When the bound fails: uniform
Let . Naively apply the formula: on support, score (constant), and . The “bound” would be . Compare two unbiased estimators of from the previous lesson: , variance , and corrected maximum , variance . Both fall below the “bound”: first by factor , second by .
None contradicts the theorem because assumptions fail. With support , Leibniz’s rule has a boundary term:
so , not zero. The three expressions equal under regularity are here , , and : three different numbers. Information’s definition ceases to make sense, and so does the bound.
The deeper statistical reason: when support depends on parameter, an observation near the boundary cuts off abruptly (the maximum is an exact lower bound for ), information never captured by the derivative. This is the estimator lesson phenomenon: corrected maximum variance falls as versus for . “Nonregular” models are no expository whim: parameter-dependent supports occur in auctions, regime-change processes, and threshold models.
Information as a metric
A third geometric interpretation explains why this quantity reappears in optimization and ML.
Proof
By definition, . Taylor-expand in (multivariate Taylor) through second order: . Taking expectation, linear term is and quadratic is . The KL minus sign leaves .
∎The information matrix defines a metric: “infinitesimal distance” between neighboring model distributions is (Fisher–Rao metric), invariant under reparameterization by the Jacobian rule. With one observation, two parameters at Fisher distance much below are barely distinguishable; with observations, uncertainty radius is order in this metric, as the bound says. Check numerically below.
This foreshadows two algorithms. The m06 natural gradient replaces steepest descent in with steepest descent in this metric: , making the step independent of parameterization (m07). Fisher scoring replaces Newton–Raphson’s observed Hessian by expected information, with sample score, the engine of generalized linear models.
Implementation from scratch
Start with observed information. Approximate second derivative of log-likelihood with central differences: , and each Hessian cross element with the four-point formula. Step is the important choice: too large and truncation error dominates; too small and subtraction of nearly equal numbers divided by destroys digits. Default balances errors; measure effect on Poisson with , exact .
import numpy as np
from scipy.special import gammaln
def hessiano_fd(f, theta, h=None):
"""Hessiano de f en theta por diferencias centrales de segundo orden."""
theta = np.asarray(theta, dtype=float)
p = theta.size
if h is None: # eps^(1/4) escalado: equilibra truncamiento y redondeo
h = np.finfo(float).eps ** 0.25 * np.maximum(np.abs(theta), 1.0)
h = np.broadcast_to(h, theta.shape).astype(float)
H = np.zeros((p, p))
f0 = f(theta)
for i in range(p):
ei = np.zeros(p); ei[i] = h[i]
H[i, i] = (f(theta + ei) - 2 * f0 + f(theta - ei)) / h[i] ** 2
for j in range(i + 1, p):
ej = np.zeros(p); ej[j] = h[j]
H[i, j] = H[j, i] = (f(theta + ei + ej) - f(theta + ei - ej) - f(theta - ei + ej) + f(theta - ei - ej)) / (4 * h[i] * h[j])
return H
def info_observada(loglik, theta_hat, h=None):
return -hessiano_fd(loglik, theta_hat, h)
rng = np.random.default_rng(1)
x = rng.poisson(4.0, size=1000)
ll_pois = lambda th: np.sum(x * np.log(th[0]) - th[0] - gammaln(x + 1))
lam = x.mean() # el EMV de la Poisson
exacta = len(x) / lam
print(f"EMV = {lam:.4f}; J exacta n/lambda = {exacta:.6f}")
print(f"{'paso h':>8} {'J':>14} {'error relativo':>15}")
for h in (1e-1, 1e-2, 1e-3, 1e-4, 1e-5, 1e-6, 1e-7, 1e-8):
J = info_observada(ll_pois, [lam], h=np.array([h]))[0, 0]
print(f"{h:8.0e} {J:14.6f} {abs(J - exacta) / exacta:15.2e}")
# la normal en (mu, sigma): en el EMV la matriz es diagonal y vale (n/s^2, 2n/s^2)
y = rng.normal(1.0, 2.0, size=500)
def ll_norm(th):
mu, s = th
return np.sum(-np.log(s) - 0.5 * np.log(2 * np.pi) - (y - mu) ** 2 / (2 * s**2))
mh, sh = y.mean(), y.std()
print("\nnormal: J numérica\n", np.round(info_observada(ll_norm, [mh, sh]), 4))
print("normal: (n/s^2, 2n/s^2) =", round(len(y) / sh**2, 4), round(2 * len(y) / sh**2, 4))Relative error traces a U: minimum near (error ), growing as toward the table’s left and shooting up at right. At subtraction of numbers order gives zero by rounding: “information” is zero. At it is too low; a slightly worse step can give negative, meaningless as curvature of a maximum. This is the fourth common mistake below.
Now expected information as score variance, estimated by Monte Carlo with scores from central differences of one observation’s log-density. This is the definition’s variance form. Test on gamma with shape and scale , exact matrix with trigamma .
import numpy as np
from scipy.special import gammaln, polygamma
def scores_fd(logf, theta, xs, h=1e-5):
"""Matriz (len(xs), p) con el score de cada observación, por diferencias centrales."""
theta = np.asarray(theta, dtype=float)
S = np.zeros((len(xs), theta.size))
for i in range(theta.size):
e = np.zeros(theta.size); e[i] = h
S[:, i] = (logf(theta + e, xs) - logf(theta - e, xs)) / (2 * h)
return S
def info_mc(logf, theta, sampler, R=20_000, seed=0):
xs = sampler(np.random.default_rng(seed), R)
S = scores_fd(logf, theta, xs)
return S.mean(axis=0), np.cov(S.T) # media del score (debe ser 0) y su covarianza
# Poisson(4): I = 1/4
lf_pois = lambda th, xs: xs * np.log(th[0]) - th[0] - gammaln(xs + 1)
m, I = info_mc(lf_pois, [4.0], lambda g, R: g.poisson(4.0, R))
print(f"Poisson: media del score = {m[0]:+.4f}; I = {I.item():.4f} (exacta 0.25)")
# Normal(1, 2^2) en (mu, sigma): I = diag(1/4, 1/2)
lf_norm = lambda th, xs: -np.log(th[1]) - 0.5 * np.log(2 * np.pi) - (xs - th[0]) ** 2 / (2 * th[1] ** 2)
m, I = info_mc(lf_norm, [1.0, 2.0], lambda g, R: g.normal(1.0, 2.0, R))
print("normal: media del score =", np.round(m, 4), "\n", np.round(I, 4), "(exacta diag(0.25, 0.5))")
# Gamma(k=3, escala 2): matriz NO diagonal
k0, t0 = 3.0, 2.0
lf_gam = lambda th, xs: -gammaln(th[0]) - th[0] * np.log(th[1]) + (th[0] - 1) * np.log(xs) - xs / th[1]
m, I = info_mc(lf_gam, [k0, t0], lambda g, R: g.gamma(k0, t0, R))
exacta = np.array([[polygamma(1, k0), 1 / t0], [1 / t0, k0 / t0**2]])
print("gamma: media del score =", np.round(m, 4), "\n", np.round(I, 4), "\nexacta\n", np.round(exacta, 4))At Monte Carlo error of each element is order : simulated matrices match exact to that precision and mean score is zero within noise (a few hundredths expected). Note gamma: the matrix is not diagonal. Shape and scale correlate because for fixed mean , greater shape is offset by lower scale. (An exercise asks you to diagonalize it.)
Symbolic form avoids simulation. With sympy differentiate the log-density Hessian and calculate its expectation. For Poisson, is linear in , so substitute by its mean; for normal use central moments for even and for odd . Verify the Jacobian rule for in two ways: transform the matrix and calculate it directly.
import sympy as sp
x, lam, mu, sg, v, t = sp.symbols("x lambda mu sigma v t", positive=True)
# Poisson: la segunda derivada es lineal en x, la esperanza sustituye x por su media
logf = x * sp.log(lam) - lam - sp.loggamma(x + 1)
print("Poisson: I(lambda) =", sp.simplify((-sp.diff(logf, lam, 2)).subs(x, lam)))
def esperanza_normal(expr, mu_, s_):
"""E[expr(X)] con X ~ N(mu_, s_^2): se expande en t = x - mu_ y se usan los momentos de la normal."""
P = sp.Poly(sp.expand(expr.subs(x, mu_ + t)), t)
return sp.simplify(sum(c * (0 if m[0] % 2 else s_ ** m[0] * sp.factorial2(m[0] - 1)) for m, c in P.terms()))
logn = -sp.log(sg) - (x - mu) ** 2 / (2 * sg**2) - sp.log(2 * sp.pi) / 2
I_ms = (-sp.hessian(logn, (mu, sg))).applyfunc(lambda e: esperanza_normal(e, mu, sg))
print("normal en (mu, sigma): I =", I_ms.tolist())
# regla del jacobiano: theta = (mu, sigma) = h(mu, v) con sigma = sqrt(v)
Hm = sp.Matrix([[1, 0], [0, 1 / (2 * sp.sqrt(v))]])
I_regla = (Hm.T * I_ms.subs(sg, sp.sqrt(v)) * Hm).applyfunc(sp.simplify)
logv = logn.subs(sg, sp.sqrt(v))
I_directa = (-sp.hessian(logv, (mu, v))).applyfunc(lambda e: esperanza_normal(e, mu, sp.sqrt(v)))
print("en (mu, v) por la regla: ", I_regla.tolist())
print("en (mu, v) directamente: ", I_directa.tolist())
print("iguales:", sp.simplify(I_regla - I_directa) == sp.zeros(2, 2))The two matrices, , agree, verifying the two-parameter Jacobian rule.
The next experiment shows why observed information is more than a noisy estimate of expected information. Take Cauchy location (scale , , so ) with . Search for the MLE on a grid and refine by Newton, calculate per sample, and group samples into three thirds by .
import numpy as np
rng = np.random.default_rng(11)
n, R = 20, 1500
x = rng.standard_cauchy((R, n))
med = np.median(x, axis=1)
grid = np.linspace(-3, 3, 121)
cand = med[:, None] + grid[None, :] # (R, G) candidatos
ll = -np.log1p((x[:, None, :] - cand[:, :, None]) ** 2).sum(axis=2) # log-verosimilitud en la rejilla
m = cand[np.arange(R), ll.argmax(axis=1)]
for _ in range(6): # refinamiento de Newton
u = x - m[:, None]
s = (2 * u / (1 + u**2)).sum(axis=1) # score de la muestra
H = (-2 * (1 - u**2) / (1 + u**2) ** 2).sum(axis=1) # segunda derivada de l
m = m - s / H
u = x - m[:, None]
J = (2 * (1 - u**2) / (1 + u**2) ** 2).sum(axis=1) # información observada en el EMV
print(f"n I = {n / 2:.1f} (esperada); J observada: media {J.mean():.2f}, mín {J.min():.2f}, máx {J.max():.2f}")
print(f"varianza del EMV = {np.mean(m**2):.4f}; cota 1/(nI) = {2 / n:.4f}")
q = np.quantile(J, [1 / 3, 2 / 3])
for nombre, msk in [("J baja ", J <= q[0]), ("J media", (J > q[0]) & (J <= q[1])), ("J alta ", J > q[1])]:
print(f"{nombre}: J media {J[msk].mean():5.2f} | error cuadrático medio del EMV {np.mean(m[msk] ** 2):.4f} | 1/J medio {np.mean(1 / J[msk]):.4f}")Expected information says all samples of size have the same precision . Observed information fluctuates from to and separates samples: when is low, MLE mean squared error is around , and when high, , with each third near . For an MLE lacking a sufficient statistic absorbing all information, curvature of this log-likelihood measures precision of this estimate better than the average over unseen samples. This is Efron and Hinkley’s (1978) argument and why practical standard errors use observed information.
Finally, geometry: KL between two neighboring Bernoullis versus .
import numpy as np
def kl_bern(p, q):
return p * np.log(p / q) + (1 - p) * np.log((1 - p) / (1 - q))
p = 0.3
I = 1 / (p * (1 - p))
print(f"{'delta':>8} {'KL(p || p+delta)':>18} {'I delta^2 / 2':>15} {'cociente':>10}")
for d in (0.1, 0.03, 0.01, 0.003):
kl, apr = kl_bern(p, p + d), 0.5 * I * d**2
print(f"{d:8.3f} {kl:18.3e} {apr:15.3e} {kl / apr:10.4f}")The ratio tends to as : Fisher information is KL curvature.
Empirical efficiency of estimators
Using the estimator lesson’s ADEMP framework, turn the race figure into a simulation study. Aims: which location estimator reaches the bound and how much do others lose? D: three mechanisms, normal, Laplace, logistic, scale and . E: center . M: mean, median, trimmed mean, and MLE (logistic solved by vectorized Newton as in the interactive). P: efficiency boundvariance with Monte Carlo error; for variance estimated as mean of , relative error is .
import numpy as np
from scipy import stats
def mle_logistica(x, it=12):
"""EMV de la localización logística (escala 1): Newton sobre el score sum(tanh((x - m)/2)) = 0."""
m = np.median(x, axis=1)
for _ in range(it):
t = np.tanh((x - m[:, None]) / 2)
m = m + t.sum(axis=1) / (0.5 * (1 - t**2)).sum(axis=1)
return m
FAMILIAS = { # nombre: (generador con centro 0, información de Fisher por observación)
"normal": (lambda g, s: g.standard_normal(s), 1.0),
"laplace": (lambda g, s: g.laplace(0, 1, s), 1.0),
"logistica": (lambda g, s: g.logistic(0, 1, s), 1 / 3),
}
n, R = 50, 4000
for i, (nombre, (gen, I)) in enumerate(FAMILIAS.items()):
x = gen(np.random.default_rng([2024, n, i]), (R, n)) # las mismas muestras para todos los métodos
est = {"media": x.mean(1), "mediana": np.median(x, 1), "recort.20%": stats.trim_mean(x, 0.2, axis=1)}
est["EMV"] = x.mean(1) if nombre == "normal" else np.median(x, 1) if nombre == "laplace" else mle_logistica(x)
cota = 1 / (n * I)
print(f"{nombre}: cota 1/(nI) = {cota:.5f}")
for k, e in est.items():
v = np.mean(e**2) # centro conocido 0: ECM = varianza
ee = np.sqrt((np.mean(e**4) / v**2 - 1) / R) # error Monte Carlo relativo
print(f" {k:>10}: varianza {v:.5f} eficiencia {cota / v:.3f} ± {cota / v * ee:.3f}")Read the table with Monte Carlo errors visible. Under normality mean and MLE are the same, efficiency up to noise. A value slightly above does not violate the bound: it is Monte Carlo error (at most a couple of errors), because the bound is exact and simulation an estimate. Under Laplace, mean efficiency is , trimmed , and median (MLE) : at it has not reached asymptotic limit . Under logistic, mean gives , trimmed , median ; MLE, the only one using all score information, gives , compatible with (at asymptotic convergence still shows). Thus MLE is the default recommendation when the family is known.
With libraries
In practice compute Hessians symbolically (compile with lambdify) when the model is manageable, or with automatic differentiation (jax.hessian, torch.autograd.functional.hessian) otherwise. With sympy derive observed information for gamma, compare it to expected information and simulated standard deviation of shape and scale MLEs, obtained by vectorized Newton on likelihood equation . Standard errors are .
import numpy as np, sympy as sp
from scipy import stats
from scipy.special import digamma, polygamma
def emv_gamma(x):
"""EMV (forma, escala) por Newton vectorizado; x tiene forma (R, n)."""
x = np.atleast_2d(x)
s = np.log(x.mean(1)) - np.log(x).mean(1)
k = (3 - s + np.sqrt((s - 3) ** 2 + 24 * s)) / (12 * s) # arranque de Minka
for _ in range(8):
k = k - (np.log(k) - digamma(k) - s) / (1 / k - polygamma(1, k))
return k, x.mean(1) / k
k0, t0, n = 3.0, 2.0, 200
x = np.random.default_rng(3).gamma(k0, t0, size=n)
kh, th = (float(v[0]) for v in emv_gamma(x))
print(f"EMV propio: ({kh:.4f}, {th:.4f}) scipy: ({stats.gamma.fit(x, floc=0)[0]:.4f}, {stats.gamma.fit(x, floc=0)[2]:.4f})")
k, t, xs = sp.symbols("k theta x", positive=True)
logf = -sp.loggamma(k) - k * sp.log(t) + (k - 1) * sp.log(xs) - xs / t
Hs = sp.hessian(logf, (k, t))
fun = [[sp.lambdify((k, t, xs), Hs[i, j], modules=[{"polygamma": polygamma}, "numpy"]) for j in range(2)] for i in range(2)]
Jobs = -np.array([[np.sum(np.broadcast_to(fun[i][j](kh, th, x), x.shape)) for j in range(2)] for i in range(2)])
Jesp = n * np.array([[polygamma(1, kh), 1 / th], [1 / th, kh / th**2]])
se = lambda J: np.sqrt(np.diag(np.linalg.inv(J)))
K, T = emv_gamma(np.random.default_rng(4).gamma(k0, t0, size=(2000, n)))
Jv = n * np.array([[polygamma(1, k0), 1 / t0], [1 / t0, k0 / t0**2]])
print("EE (forma, escala) con J observada simbólica:", np.round(se(Jobs), 4))
print("EE con la esperada n I(theta_hat) :", np.round(se(Jesp), 4))
print("EE teórica con n I(theta verdadero) :", np.round(se(Jv), 4))
print("EE simulada (2000 muestras) :", np.round([K.std(ddof=1), T.std(ddof=1)], 4))
print(f"correlación teórica {np.linalg.inv(Jv)[0, 1] / np.sqrt(np.prod(np.diag(np.linalg.inv(Jv)))):+.3f}; simulada {np.corrcoef(K, T)[0, 1]:+.3f}")Three comments. First, our MLE agrees with scipy.stats.gamma.fit to several digits. Second, observed and expected information both evaluated at agree exactly here (gamma Hessian in is linear in and at MLE ), unlike Cauchy; difference from theoretical SE is only that between and . Third, these SEs reproduce simulated MLE spread, and correlation between and is strongly negative (theoretical ): matrix nondiagonality seen from data.
Common mistakes
Exercises
Step 1 of 4. Which starting identity gives both equalities?
Step 1 of 4. What quantity should be related to ?
info_gamma(), returning tuple (k, th, mu, I, Iorto): sympy symbols k (shape), th (scale), and mu (mean ), the Fisher information matrix I of one observation in parameters , and matrix Iorto in parameters . Method hints: is affine in , so its expectation follows by substituting by ; for Iorto apply the Jacobian rule with . Tests check I is not diagonal, Iorto is diagonal, and numerical values.import sympy as sp
def info_gamma():
k, th, mu, x = sp.symbols('k theta mu x', positive=True)
# log f = -loggamma(k) - k log(th) + (k - 1) log(x) - x / th
# tu código: hessiano, sustituir x por k*th, regla del jacobiano para (k, mu)
I = sp.eye(2)
Iorto = sp.eye(2)
return k, th, mu, I, IortoMore than one answer may be correct.
More than one answer may be correct.
Summary
- Regularity: fixed support, differentiability, and exchange of derivative and integral. Under these, score has zero mean and variance (proved by differentiating twice).
- Observed information versus expected : the former is random and measures this sample’s precision (Cauchy, : ranges from to with ); the latter describes the model.
- Additivity: . Jacobian rule: scalar, matrix. Bernoulli: for , for logit, for .
- Information matrix: score-vector covariance, positive semidefinite and positive definite if no nonidentifiable directions. Normal gives (orthogonal parameters); gamma is not diagonal, but is in .
- Cramér–Rao: by Cauchy-Schwarz and ; with known bias, ; in matrix form, by Schur complement.
- Efficiency: equality requires , an exponential family. is optimal unbiased but efficiency . MLE is asymptotically efficient; at finite , Laplace MLE (median) and logistic MLE do not yet attain it (efficiency ).
- Nonregular-model failure: for , and ; unbiased corrected maximum has variance , below .
- Geometry: . This yields natural gradient (m06), Fisher scoring (GLM), EWC weighting (m20), and Laplace approximation (m14).