Sufficiency, exponential families and optimal unbiased estimation
Understand sufficient statistics and exponential families, derive moments and maximum-likelihood estimates from the log-partition function, and use Rao–Blackwell and Lehmann–Scheffé to improve unbiased estimators.
After this lesson you can
Use factorization and likelihood ratios to identify sufficient and minimal sufficient statistics.
Write exponential families in canonical form and derive moments and Fisher information from the log-partition function.
Explain when fixed-dimensional data compression is possible and why parameter-dependent support matters.
Apply Rao–Blackwell and Lehmann–Scheffé and recognize limitations of unbiased estimation.
Motivation: compress data without losing anything about θ
Flip a coin a million times and store the entire sequence: one million bits. If you only want to estimate heads probability p, must all be kept? Intuition says no: the number of heads suffices. Their order seems irrelevant. This lesson turns intuition into a theorem, finds each model’s smallest possible summary, and discovers that the answer depends on the model: if flips are not independent, head count no longer suffices.
The question has practical consequences:
Streaming and federated computation. If a fixed-dimensional summary (a sum or sum of squares) contains all parameter information, process data exceeding memory or aggregate many servers by summing vectors, losing nothing compared with having all data together.
Why some models are easy and others are not. In normal, Poisson, or logistic regression, maximum likelihood is a concave problem depending on few sums. For a Gaussian mixture or Cauchy model no summary is possible: each optimizer iteration scans all data and likelihood has local maxima. This frontier has a name: the exponential family.
Optimal estimators. If a summary contains all information, an estimator depending on more carries removable noise. Rao–Blackwell removes it and Lehmann–Scheffé certifies when none remains: the result is the minimum-variance unbiased estimator.
Start with a statistical model{Pθ:θ∈Θ} for full sample X=(X1,…,Xn), with mass or density pθ(x). A statistic is any data function T(X) not depending on θ.
The definition says something concrete: once T is known, the remaining data are noise whose law is known without θ. For the coin with Xi∼iidBern(p) and T=∑iXi, any sequence x with t heads satisfies
Pp(X=x∣T=t)=(tn)pt(1−p)n−tpt(1−p)n−t=(tn)1.
Given the head count, all orders are equally likely, whatever p. Order contains no information about p.
Sufficiency belongs to a statistic-model pair, not the statistic alone. In the figure, independent flips make two sequences with equal head counts have equal likelihood; a model allowing dependence between consecutive flips does not.
InteractiveLossless compression for p
A
B
Relative likelihood L(p)/maxpL(p) of each sequence
Log-likelihood difference ℓA(p)−ℓB(p): flat if and only if curves above agree
sequence A
sequence B
ℓA−ℓB
Sequence pair
Heads A | B8 | 8
Alternations A | B1 | 14
p^ A | B0.400 | 0.400
Variation of ℓA−ℓB0
Model sufficient statisticheads
Same number of heads (8) and constant ℓA−ℓB: the sequences contain exactly the same information about p.
Two 20-flip sequences (filled = heads); click a circle to change it. Above, each relative likelihood; below, log-likelihood difference. With κ=0 (independence), A and B have 8 heads and curves coincide exactly: difference is line 0. Raise κ, introducing Markov dependence P(Xi+1=1∣Xi=x)=(1−κ)p+κx: curves separate despite unchanged head count, because the grouped sequence has far fewer alternations. Try 'B = shuffled A' and 'Different' too.
In the figure’s Markov model, likelihood is px1(1−p)1−x1∏iq(xi)xi+1(1−q(xi))1−xi+1 with q(x)=(1−κ)p+κx. It depends on data via the first flip and transition counts (n00,n01,n10,n11): that is now the sufficient summary. Grouped sequence A has one alternation and B fourteen; with κ>0 this changes inference about p.
Factorization theorem
Checking the definition requires a conditional distribution, generally awkward. The practical criterion examines likelihood’s form.
This is the factorization theorem. In the discrete case each direction takes one line, worked through in the final guided exercise: if T is sufficient, pθ(x)=Pθ(T=T(x))P(X=x∣T=T(x)) already factorizes; if factorized, conditioning cancels gθ(t). The density case needs measure theory (Halmos and Savage, 1949) without new ideas.
An immediate consequence: likelihood L(θ;x)=pθ(x), as a function of θ, is proportional to gθ(T(x)). Two samples with the same T have proportional likelihoods and the MLE is always a function of any sufficient statistic. The figure’s flat difference shows this.
Minimal sufficiency
The entire sample X is always sufficient (trivially), as is any bijection of a sufficient statistic. The interesting object is the smallest summary.
Proof
Prove the discrete case. Sufficiency. For each value t of T, choose representative yt with T(yt)=t. By assumption pθ(x)=c(x,yT(x))pθ(yT(x)) for every θ. Define gθ(t)=pθ(yt) and h(x)=c(x,yT(x)): this factorizes, so T is sufficient. Minimality. Let U be another sufficient statistic and suppose U(x)=U(y). By factorization of U, pθ(x)/pθ(y)=hU(x)/hU(y), independent of θ, so by assumption T(x)=T(y). Thus U(x)=U(y)⇒T(x)=T(y), exactly stating that T is a function of U.
∎
The criterion turns search into algebra: write the ratio and inspect what must agree for θ to cancel.
Bernoulli.pθ(x)/pθ(y)=(p/(1−p))tx−ty is free of p if and only if tx=ty. ∑Xi is minimal.
Uniform on (θ,θ+1). Likelihood is 1[x(n)−1≤θ≤x(1)], an interval indicator. The ratio is free of θ if and only if the two intervals coincide: minimal is (X(1),X(n)), two numbers for a one-dimensional parameter.
Cauchy location. With density 1/(π(1+(x−θ)2)), ratio is ∏i(1+(yi−θ)2)/∏i(1+(xi−θ)2), a ratio of degree-2n polynomials in θ. It is constant if and only if the polynomials have the same complex roots xi±i, meaning sets {xi} and {yi} agree. Minimal is the order statistics(X(1),…,X(n)): only arrival order can be discarded.
InteractiveWhen compression fails: normal versus Cauchy
Relative log likelihood ℓ(μ)−maxμℓ of location μ
Data (drag)
normal model: −2n(μ−xˉ)2
Cauchy model: −∑ilog(1+(xi−μ)2)
local maximum
n | xˉ (normal MLE)5 | 0.18
Cauchy MLE3.97
Local maxima of Cauchy ℓ3
Minimal sufficient dimension: normal | Cauchy1 | 5
Cauchy log likelihood has 3 local maxima: a local optimizer can get stuck at the wrong one.
Drag data in the lower strip (or press buttons). Above: relative log-likelihood of location μ in normal (blue) and Cauchy (red) models. Normal is always the same parabola −2n(μ−xˉ)2: 'Separate extremes' moves two observations without changing xˉ and the blue curve stays fixed. Cauchy's changes with any movement and initially has three local maxima. Bring extremes together until one remains.
Exponential family
Nearly all models with fixed-dimensional sufficient statistics in preceding examples share a form. Uniform is an exception for a reason seen below.
Often a model has another parameter θ and is written pθ(x)=h(x)exp(η(θ)⊤T(x)−B(θ)). Convert to canonical form by changing variable to η=η(θ), advisable before differentiating.
Family
T(x)
η
A(η)
h(x)
N
Bern(p)
x
log1−pp
log(1+eη)
1
R
Bin(m,p), fixed m
x
log1−pp
mlog(1+eη)
(xm)
R
Pois(λ)
x
logλ
eη
1/x!
R
N(μ,1)
x
μ
η2/2
e−x2/2/2π
R
N(μ,σ2)
(x,x2)
(σ2μ,−2σ21)
−4η2η12−21log(−2η2)
1/2π
R×(−∞,0)
Exponential, rate β
x
−β
−log(−η)
1
(−∞,0)
Gamma(α,β)
(logx,x)
(α−1,−β)
logΓ(η1+1)−(η1+1)log(−η2)
1
(−1,∞)×(−∞,0)
Beta(a,b)
(logx,log(1−x))
(a−1,b−1)
logB(η1+1,η2+1)
1
(−1,∞)2
Categorical, K classes
ex (one-hot)
z (logits)
log∑jezj
1
RK
The last row is softmax: P(x=j)=ezj/∑lezl=exp(z⊤ej−A(z)). This representation is not minimal because 1⊤ex=1 always (adding a constant to all logits changes nothing); setting zK=0 gives a minimal one with K−1 parameters.
Uniform on (0,θ) is not an exponential family: support depends on θ, and no choice of h, T, and A produces indicator 1[x≤θ] with a finite exponent. Neither are Student’s t with unknown degrees of freedom, Cauchy, or mixtures.
and factorization makes ∑iT(Xi) sufficient. Its dimension is kregardless of n: a million gamma observations compress losslessly into two numbers. Under a minimal representation the ratio criterion shows it is also minimal: the ratio is exp(η⊤(∑T(xi)−∑T(yi))) times an η-free factor, and is independent of η on an open set only if the difference is zero.
Proof
Let η1,η2∈N and α∈(0,1). Write the intermediate-point integrand as a product of powers and apply Hölder’s inequality with exponents 1/α and 1/(1−α):
Taking logarithms, A(αη1+(1−α)η2)≤αA(η1)+(1−α)A(η2)<∞: the intermediate point belongs to N and A is convex. Equality in Hölder requires the two functions to be proportional, so e(η1−η2)⊤T(x) is constant on support, prohibited by minimality if η1=η2.
∎
A second, more revealing proof follows: the Hessian of A is a covariance matrix.
Moments by differentiating the log-partition
Proof
eA(η)=∫heη⊤T is a Laplace transform. Near an interior point differentiation under the integral is allowed because ∣Tj∣meη⊤T is dominated by a combination of e(η±δej)⊤T, integrable for small δ (dominated convergence). Differentiate A=log∫heη⊤T:
∂ηj∂A=∫heη⊤T∫Tjheη⊤T=∫Tjheη⊤T−A(η)=Eη[Tj].
Differentiating the middle expression again, ∂ηi∂(Tjheη⊤T−A(η))=Tj(Ti−∂iA)heη⊤T−A, so
For the cumulant generator, Eη[es⊤T]=∫he(η+s)⊤T−A(η)=eA(η+s)−A(η).
∎
The Hessian matrix symmetry guaranteed by Schwarz’s theorem is covariance symmetry here. Since covariance is positive semidefinite, ∇2A⪰0: a second convexity proof. It is positive definite exactly when no combination a⊤T is constant, which is minimality.
Everything depends on calculating A. If T is rich (e.g. outputs of a neural network), the defining integral for A becomes intractable: the energy-based models of module 19. Identity ∇A=Eη[T] still holds, but expectation has no closed form and must be estimated by sampling from the model itself, making training expensive.
InteractiveThe log-partition knows everything
Log-partition A(η), tangent and osculating parabola
A(η)
tangent: slope =E[T]
parabola: curvature =Var[T]
Distribution of X at this η (Bernoulli)
mass p(x∣η)
mean
mean ± standard deviation
Family
A(η)=log(1+eη),p=σ(η)=0.690
Slope A′(η) (finite differences)0.6900
Mean Eη[T] (summing distribution)0.6900
Curvature A′′(η) (finite differences)0.2139
Variance Varη[T] (summing distribution)0.2139
Fisher information I(η)=A′′(η)0.2139
Left: A(η) with its tangent at η (orange) and osculating parabola (dashed). Right: distribution of X at that η with its mean and one standard deviation on each side, calculated by summing or integrating without differentiation. Readouts compare both: tangent slope matches mean and curvature matches variance in all four families. For exponential, watch A diverge at natural-space boundary η=0. Then enable 'Fit data': line of slope Tˉ touches A at one point, the MLE.
Fisher information and mean parameterization
Score in the natural parameter is especially simple: ∇ηlogpη(x)=T(x)−∇A(η). Its covariance is Fisher information:
I(η)=Covη[T(X)]=∇2A(η).
A finer point: observed information, −∇η2logpη(x)=∇2A(η), does not depend on data: observed and expected coincide in natural parameters. Newton’s method and Fisher scoring are thus the same in these models (and generalized linear models with canonical link).
Since ∇A is the gradient of a strictly convex function (minimal case), η↦μ=∇A(η) is injective: mean vector μ=E[T] is another valid parameterization, the mean parameterization. Its Jacobian is ∂μ/∂η=∇2A, and the information change-of-variable rule gives
Now estimator Tˉ=n1∑iT(Xi): it is unbiased for μ with covariance Cov[T]/n=(nI(μ))−1. It attains Cramér–Rao: an efficient estimator. The converse holds in dimension one: equality requires score affine in estimator, ∂θlogpθ=a(θ)(δ(x)−g(θ)), and integrating in θ gives an exponential family with sufficient δ. Finite-sample efficient estimators essentially exist only in exponential families, and only for affine functions of the mean parameter. This explains the previous lesson’s few exact efficiency examples.
MLE is moment matching
For an iid sample, log-likelihood in natural parameter is
ℓ(η)=η⊤i=1∑nT(xi)−nA(η)+i∑logh(xi),
linear minus convex: concave. Its gradient is ∑iT(xi)−n∇A(η), and Hessian −n∇2A(η).
Uniqueness comes from strict concavity: a critical point of a strictly concave function is its unique global maximum. Existence has real content: with 20 flips and 0 heads, Tˉ=0 is at the boundary of [0,1], and ℓ(η)=−20log(1+eη) strictly increases as η decreases: it approaches supremum 0 as η→−∞ without attaining it at finite η. The MLE of p is 0, but the natural-parameter MLE does not exist. This is the statistical version of perfect separation in logistic regression.
The previous figure shows the geometry. Dividing by n, ℓ(η)/n=ηTˉ−A(η)+cte: signed vertical distance between line ηTˉ and curve A. It is maximal where A‘s tangent is parallel to the line, A′(η^)=Tˉ. Maximum supη{ηTˉ−A(η)} is the convex conjugateA∗(Tˉ), equal to negative fitted-distribution entropy relative to base h (ordinary entropy when h=1, as in Bernoulli or gamma): the exponential family solves the maximum entropy principle under E[T] constraints, and this calculation is its other face.
Pitman–Koopman–Darmois: only the exponential family compresses
Do other models have fixed-dimensional sufficient statistics? With fixed support, essentially no.
Darmois (1935), Koopman (1936), and Pitman (1936) independently proved it; a precise statement and proof are in Lehmann and Casella, section 1.6. Consequences:
For Cauchy, Student’s t, or logistic location, and mixtures with unknown components such as the Gaussian mixture, minimal sufficient statistics are order statistics. No fixed-size summary preserves all information.
Computationally, each optimizer or EM algorithm iteration must scan all data, and exact aggregation of different servers’ computations with a few sums is impossible. Concavity is lost too: the Cauchy figure had three local maxima with five observations.
Uniform escapes because its support depends on θ. Thus it compresses into X(n) without being exponential, and this section’s results (moments by differentiation, concavity, efficiency) do not apply.
Rao–Blackwell: conditioning on a sufficient statistic never worsens
If T contains all information about θ, an estimator depending on data beyond T carries useless noise. Remove it by averaging within each level set of T.
This is the Rao–Blackwell theorem, independently published by C. R. Rao (1945) and D. Blackwell (1947).
Proof
(1) Conditional expectation uses the law of X given T, independent of θ by sufficiency. Without sufficiency, Eθ[δ∣T] would depend on unknown θ and could not estimate. (2) Tower property: Eθ[E[δ∣T]]=Eθ[δ]. (3) For general convex loss, conditional Jensen gives L(θ,E[δ∣T])≤E[L(θ,δ)∣T]; taking expectations, Eθ[L(θ,δ∗)]≤Eθ[L(θ,δ)]. For squared error, total variance also yields the equality condition; the guided exercise proves it.
∎
Variance is reduced: by MSE decomposition and unchanged bias, gain is exactly Eθ[Var(δ∣T)], the variance δ had inside T‘s level sets.
Poisson P(X=0) example
With Xi∼iidPois(λ), estimate g(λ)=P(X=0)=e−λ, the probability of an interval without events. A ridiculously simple unbiased estimator looks only at the first observation: δ0=1[X1=0]. It is 0 or 1, unbiased, and has variance e−λ(1−e−λ), which does not decrease with n.
Condition on S=∑iXi. Given S=s, vector (X1,…,Xn) is multinomial with s trials and probabilities 1/n (each of the s events randomly falls into one of n observations), so X1∣S=s∼Bin(s,1/n) and
δ1=E[δ0∣S]=P(X1=0∣S)=(1−n1)S.
Generating function E[tS]=enλ(t−1) calculates everything. With t=(n−1)/n, E[δ1]=e−λ: unbiased as required. With t=((n−1)/n)2, E[δ12]=e−2λ+λ/n, so
Var(δ1)=e−2λ(eλ/n−1),cota de Crameˊr-Rao=n/λg′(λ)2=nλe−2λ.
For λ=2 and n=10: Var(δ0)=0.1170, Var(δ1)=0.004055 (29 times less), and the bound is 0.003663. Ratio (eλ/n−1)/(λ/n)=1.107 is always above 1 and tends to 1: δ1 never attains the bound for finite n, consistent with e−λ not being affine in mean parameter λ. Yet soon we see no unbiased estimator does better.
InteractiveRao–Blackwell live
1200 of 4000 replicates: estimator value versus S=∑Xi
Its distribution
replicates
E[δ0∣S=s]=((n−1)/n)s
diamonds: empirical mean of each column
estimator mean
±1 standard deviation
t = 0.00
Estimator shownδ₀ = 1{X₁ = 0}
Mean of replicates | g(λ)=e−λ0.1348 | 0.1353
Variance of replicates0.1166
Var(δ0)=e−λ(1−e−λ)0.1170
Var(δ1)=e−2λ(eλ/n−1)0.00406
Cramér–Rao bound λe−2λ/n0.00366
Reduction Var(δ0)/Var(δ1) | efficiency of δ1×28.9 | 90.3 %
Each point is a Poisson sample replicate (1200 of 4000 used by readouts): horizontal axis is its sum S; vertical is estimator value. Initially δ0=1[X1=0] is only 0 or 1. Play: each point slides to its column mean, curve ((n−1)/n)s; diamonds are empirical column means and lie on it. Right: estimator-value histogram on the same axis. Mean remains e−λ throughout animation (up to simulation noise, since both endpoints are unbiased) and variance falls around 29-fold to near Cramér–Rao. Change n and λ.
Completeness and Lehmann–Scheffé
Rao–Blackwell improves estimators, but when is the best reached? If two different unbiased estimators were functions of T, Rao–Blackwellization could not choose between them. Completeness prevents this.
Poisson. If Eλ[φ(S)]=e−nλ∑s≥0φ(s)(nλ)s/s!=0 for all λ>0, the power series ∑sφ(s)nsλs/s! is identically zero, and so are all its coefficients: φ≡0.
Exponential family. If the representation is minimal and N contains an open set, ∑iT(Xi) is complete. The proof uses uniqueness of the Laplace transform (Lehmann and Casella, theorem 1.6.22).
Uniform on (0,θ). If ∫0θφ(m)nmn−1θ−ndm=0 for every θ, differentiating with respect to θ yields φ(θ)θn−1=0 for almost all θ. X(n) is complete.
A minimal sufficient statistic that is not complete. For the uniform distribution on (θ,θ+1), the range X(n)−X(1) has a distribution independent of θ (it is an ancillary statistic), with mean (n−1)/(n+1). The function φ=X(n)−X(1)−(n−1)/(n+1) of (X(1),X(n)) has mean zero for every θ without being identically zero.
“Uniformly” is the demanding part: one estimator must beat all others at every value of θ simultaneously. The parameter θ cannot select a different estimator. Surprisingly, with a complete sufficient statistic, this happens.
Proof
Let δ be any unbiased finite-variance estimator of g(θ) and set δ∗=E[δ∣T]. By Rao–Blackwell, δ∗ is unbiased, is a function of T, and Varθ(δ∗)≤Varθ(δ). Now δ∗−φ(T) is a function of T with Eθ[δ∗−φ(T)]=g(θ)−g(θ)=0 for every θ; by completeness, δ∗=φ(T) almost surely. Hence Varθ(φ(T))=Varθ(δ∗)≤Varθ(δ) for every θ. If δ were also a UMVUE, it would have the same variance as φ(T)=δ∗, and the equality condition of Rao–Blackwell would give δ=δ∗=φ(T) almost surely.
∎
The proof gives two recipes for finding the UMVUE: solve Eθ[φ(T)]=g(θ) directly for φ, or Rao–Blackwellize any simple unbiased estimator using a complete sufficient statistic. Thus:
Xˉ is the UMVUE of λ for Poisson and of μ for the normal; S2=n−11∑(Xi−Xˉ)2 is the UMVUE of σ2.
((n−1)/n)S is the UMVUE of e−λ: no unbiased estimator has lower variance, although it does not attain the Cramér–Rao bound. The bound is not the best attainable value, only a lower bound.
nn+1X(n) is the UMVUE of θ for the uniform distribution.
The limits of pursuing unbiasedness
The UMVUE is optimal within a class that may be a poor choice.
It can be absurd. With one observation X∼Pois(λ), estimate g(λ)=e−2λ (the probability of no events in two intervals). An unbiased estimator δ satisfies ∑xδ(x)e−λλx/x!=e−2λ, that is, ∑xδ(x)λx/x!=e−λ=∑x(−1)xλx/x!. Matching coefficients, δ(X)=(−1)X is the only unbiased estimator, and therefore the UMVUE. It estimates a probability using +1 or −1. Its MSE is 1−e−4λ, equal to 0.982 at λ=1; the biased MLE e−2X has MSE 0.279.
A biased estimator can beat it in MSE. In the estimators lesson you saw that, for the normal, dividing ∑(Xi−Xˉ)2 by n+1 gives lower MSE than the UMVUE S2. The same happens for the uniform: n+1n+2X(n) has MSE θ2/(n+1)2, lower than the UMVUE’s θ2/(n(n+2)) because n(n+2)=(n+1)2−1. Decision theory in lesson 23 takes this idea as far as the James–Stein estimator.
It may not exist. With X∼Bin(n,p), Ep[φ(X)] is a polynomial in p of degree at most n, so 1/p (or logp) has no unbiased estimator. Unbiasedness is not invariant either: if θ^ is unbiased for θ, g(θ^) is almost never unbiased for g(θ), unlike the MLE, which is invariant.
Implementation from scratch
The first cell builds a generic exponential-family class from its symbolic log-partition function. SymPy differentiates A and turns the derivatives into numerical functions; the MLE solves the moment equation ∇A(η)=Tˉ using scipy.optimize.root, passing the Hessian of A as its Jacobian (exact Newton, as we saw). Finite differences provide an independent check.
[ ]ExponentialFamily class from scratchBrowser
import numpy as np
import sympy as sp
from scipy import optimize, special
class ExponentialFamily:
"""p(x | eta) = h(x) exp(eta · T(x) - A(eta)), con A dada como expresión de sympy."""
def __init__(self, nombre, eta, A, T, log_h):
self.nombre, self.eta = nombre, list(eta)
self.k = len(self.eta)
grad = [sp.diff(A, e) for e in self.eta]
hess = [[sp.diff(g, e) for e in self.eta] for g in grad]
mods = ["scipy", "numpy"]
self._A = sp.lambdify(self.eta, A, mods)
self._grad = sp.lambdify(self.eta, grad, mods)
self._hess = sp.lambdify(self.eta, hess, mods)
self.T, self.log_h = T, log_h # T: x (n,) -> (n, k)
def A(self, eta):
return float(self._A(*eta))
def mean(self, eta): # grad A = E[T]
return np.array(self._grad(*eta), dtype=float)
def cov(self, eta): # hess A = Cov[T]
return np.array(self._hess(*eta), dtype=float).reshape(self.k, self.k)
def mean_fd(self, eta, h=1e-5): # comprobación: diferencias centradas
eta = np.asarray(eta, float)
E = np.eye(self.k) * h
return np.array([(self.A(eta + E[j]) - self.A(eta - E[j])) / (2 * h) for j in range(self.k)])
def loglik(self, eta, x):
return float(np.sum(self.log_h(x)) + self.T(x).sum(axis=0) @ np.asarray(eta) - len(x) * self.A(eta))
def fit(self, x, eta0):
"""EMV: resuelve grad A(eta) = media de T(x_i), con el hessiano como jacobiano."""
tbar = self.T(x).mean(axis=0)
sol = optimize.root(lambda e: self.mean(e) - tbar, eta0, jac=self.cov)
return sol.x, sol.success
e, e1, e2 = sp.symbols("eta eta1 eta2")
familias = {
"Bernoulli": ExponentialFamily("Bernoulli", [e], sp.log(1 + sp.exp(e)),
lambda x: x[:, None], lambda x: np.zeros_like(x)),
"Poisson": ExponentialFamily("Poisson", [e], sp.exp(e),
lambda x: x[:, None], lambda x: -special.gammaln(x + 1)),
"Gamma": ExponentialFamily("Gamma", [e1, e2], sp.loggamma(e1 + 1) - (e1 + 1) * sp.log(-e2),
lambda x: np.column_stack([np.log(x), x]), lambda x: np.zeros_like(x)),
"Beta": ExponentialFamily("Beta", [e1, e2],
sp.loggamma(e1 + 1) + sp.loggamma(e2 + 1) - sp.loggamma(e1 + e2 + 2),
lambda x: np.column_stack([np.log(x), np.log1p(-x)]), lambda x: np.zeros_like(x)),
}
rng = np.random.default_rng(0)
n = 20_000
casos = { # (muestra, parámetro natural verdadero, punto de partida del ajuste)
"Bernoulli": (rng.binomial(1, 0.3, n).astype(float), [np.log(0.3 / 0.7)], [0.0]),
"Poisson": (rng.poisson(4.0, n).astype(float), [np.log(4.0)], [0.0]),
"Gamma": (rng.gamma(3.0, 1 / 2.0, n), [2.0, -2.0], [0.0, -1.0]),
"Beta": (rng.beta(2.0, 5.0, n), [1.0, 4.0], [0.0, 0.0]),
}
for nombre, (x, eta_true, eta0) in casos.items():
F = familias[nombre]
Tx = F.T(x)
print(f"{nombre}: eta verdadero = {np.round(eta_true, 4)}")
print(" grad A (sympy) :", np.round(F.mean(eta_true), 4))
print(" grad A (dif. finitas):", np.round(F.mean_fd(eta_true), 4))
print(" media muestral de T :", np.round(Tx.mean(axis=0), 4))
print(" hess A :", np.round(F.cov(eta_true), 4).ravel())
print(" cov. muestral de T :", np.round(np.atleast_2d(np.cov(Tx.T)), 4).ravel())
eta_hat, ok = F.fit(x, eta0)
print(f" EMV eta = {np.round(eta_hat, 4)} (convergió: {ok})")
All four families behave alike: the symbolic gradient, numerical gradient, and sample mean of T agree up to Monte Carlo error, as do the Hessian and sample covariance. The MLE recovers the true natural parameter up to sampling error (with n=20000, on the order of a hundredth for Bernoulli and a few hundredths for beta). Notice that the class knows nothing about each family except A, T, and h: all the theory in this lesson fits in those three functions.
The second cell measures the gains from Rao–Blackwell in the lesson’s two examples and compares them with the formulas: variances, Cramér–Rao bound, biased MLE e−Xˉ and, for the uniform, the biased estimator that beats the UMVUE in MSE. It also estimates E[δ0∣S=s] by averaging δ0 within each value of S, literally the definition.
[ ]Rao–Blackwellization by simulationBrowser
import numpy as np
rng = np.random.default_rng(1)
# Poisson: estimar exp(-lambda) = P(X = 0)
lam, n, R = 2.0, 10, 200_000
X = rng.poisson(lam, size=(R, n))
S = X.sum(axis=1)
d0 = (X[:, 0] == 0).astype(float) # estimador burdo
d1 = ((n - 1) / n) ** S # Rao-Blackwellizado = UMVUE
emv = np.exp(-X.mean(axis=1)) # EMV, sesgado
g = np.exp(-lam)
crlb = lam * np.exp(-2 * lam) / n
print(f"g = exp(-lambda) = {g:.5f}, cota de Cramér-Rao = {crlb:.6f}")
for nombre, d, teo in [("delta0", d0, g * (1 - g)),
("delta1", d1, np.exp(-2 * lam) * (np.exp(lam / n) - 1)),
("EMV", emv, None)]:
ecm = np.mean((d - g) ** 2)
extra = f" (teórica {teo:.6f})" if teo is not None else ""
print(f" {nombre:7s} media {d.mean():.5f} varianza {d.var():.6f}{extra} ECM {ecm:.6f}")
# E[delta0 | S = s] estimada promediando dentro de cada columna, frente a la fórmula
print("\n s media empírica de delta0 ((n-1)/n)^s réplicas")
for s in range(14, 27, 3):
sel = S == s
print(f" {s:3d} {d0[sel].mean():.4f} {((n - 1) / n) ** s:.4f} {sel.sum():6d}")
# Uniforme(0, theta): 2 X1 frente a su versión Rao-Blackwellizada
theta, n = 1.0, 5
U = rng.uniform(0, theta, size=(R, n))
M = U.max(axis=1)
for nombre, d, teo in [("2 X1", 2 * U[:, 0], theta**2 / 3),
("(n+1)/n max", (n + 1) / n * M, theta**2 / (n * (n + 2))),
("(n+2)/(n+1) max", (n + 2) / (n + 1) * M, theta**2 / (n + 1) ** 2)]:
print(f"\n {nombre:16s} media {d.mean():.4f} ECM {np.mean((d - theta) ** 2):.5f} (teórico {teo:.5f})", end="")
print()
Simulated variances agree with the formulas within Monte Carlo error (less than 0.5 %): the variance of δ1 is about 29 times smaller than that of δ0 and is 11 % above the bound. Column means reproduce ((n−1)/n)s, as the diamonds in the animation showed. The MLE e−Xˉ is biased upward (mean 0.149 versus 0.135; the exact value is enλ(e−1/n−1)), yet its MSE, 0.0046, is only 13 % greater than that of the UMVUE. For the uniform distribution, the biased estimator n+1n+2X(n) beats the UMVUE in MSE, as predicted.
Finally, the counterexample: without an exponential family there is neither a summary nor concavity. With the five observations in the Cauchy figure, a local optimizer reaches different maxima depending on its starting point.
[ ]Cauchy: no fixed-dimensional sufficient statistic or concavityBrowser
import numpy as np
from scipy import optimize
x = np.array([-4.4, -3.7, 0.3, 4.0, 4.7])
nll = lambda m: np.sum(np.log1p((x - np.atleast_1d(m)[0]) ** 2)) # -log-verosimilitud (salvo constante)
mu = np.linspace(-8, 8, 3201)
ll = -np.array([nll(m) for m in mu])
picos = [mu[i] for i in range(1, len(mu) - 1) if ll[i] > ll[i - 1] and ll[i] >= ll[i + 1]]
print("máximos locales de la log-verosimilitud:", np.round(picos, 3))
for inicio in [-6.0, 0.0, 2.0, 6.0]:
r = optimize.minimize(nll, x0=[inicio], method="BFGS")
print(f"BFGS desde {inicio:+.1f} -> mu = {r.x[0]:+.3f}, log-verosimilitud = {-r.fun:.3f}")
# el modelo normal solo ve la media: cambiar los datos sin cambiar x̄ no cambia nada
y = x.copy(); y[0] -= 1.0; y[-1] += 1.0
print("\nmedias:", x.mean(), y.mean(), " EMV normal igual; EMV de Cauchy:",
round(optimize.minimize_scalar(nll, bounds=(-8, 8), method="bounded").x, 3), "frente a",
round(optimize.minimize_scalar(lambda m: np.sum(np.log1p((y - m) ** 2)), bounds=(-8, 8), method="bounded").x, 3))
There are three local maxima, at −3.69, 0.34 and 3.98, and the last is global. None of the four BFGS starts finds it: three end at 0.34 and one at −3.69. When the extremes are moved apart without changing xˉ, the normal MLE stays unchanged while the Cauchy MLE moves from 3.976 to 3.939. In an exponential family none of this can occur: the log-likelihood is concave and only sees Tˉ.
The library version
scipy.stats fits any distribution by maximum likelihood using fit, optimizing numerically without knowing the family is exponential. For gamma and beta it should reach the same place as our moment equation (fixing location, and scale for beta, which are not parameters of the exponential family).
[ ]scipy.stats.fit versus the moment equationBrowser
import numpy as np
from scipy import stats
xg, eta_g, eta0_g = casos["Gamma"]
eta_hat, _ = familias["Gamma"].fit(xg, eta0_g)
a_sc, loc, escala = stats.gamma.fit(xg, floc=0)
print("Gamma nuestra: alfa = %.4f beta = %.4f" % (eta_hat[0] + 1, -eta_hat[1]))
print(" scipy : alfa = %.4f beta = %.4f" % (a_sc, 1 / escala))
xb, eta_b, eta0_b = casos["Beta"]
eta_hat_b, _ = familias["Beta"].fit(xb, eta0_b)
a_b, b_b, _, _ = stats.beta.fit(xb, floc=0, fscale=1)
print("Beta nuestra: a = %.4f b = %.4f" % (eta_hat_b[0] + 1, eta_hat_b[1] + 1))
print(" scipy : a = %.4f b = %.4f" % (a_b, b_b))
# la condición de primer orden: los momentos del suficiente cuadran
print("\nE[T] ajustada:", np.round(familias["Gamma"].mean(eta_hat), 6),
" media de T:", np.round(familias["Gamma"].T(xg).mean(axis=0), 6))
The two approaches agree to the first four digits, and the last line shows the condition characterizing the MLE: the fitted mean of T=(logX,X) exactly matches the observed one. In PyTorch, torch.distributions.ExponentialFamily is the base class of Bernoulli, Poisson, Gamma, Beta, Normal and others; each subclass declares _natural_params and _log_normalizer (our A), and the base class calculates, for example, entropy by automatic differentiation of A:
import torchd = torch.distributions.Gamma(torch.tensor(3.0), torch.tensor(2.0))eta = [p.detach().requires_grad_() for p in d._natural_params] # (alfa - 1, -beta)A = d._log_normalizer(*eta)grad = torch.autograd.grad(A, eta) # (E[log X], E[X])
Common mistakes
Exercises
QuizWhich models can be compressed?
For iid samples of arbitrary size n, which of these models have a sufficient statistic of fixed dimension (not growing with n)?
More than one answer may be correct.
QuizOne parameter, two numbers
With X1,…,Xn∼iidUnif(θ,θ+1), what is a minimal sufficient statistic for θ?
NumericVariance from curvature
For Bernoulli in canonical form, A(η)=log(1+eη). Calculate A′′(η) at η=log3.
QuizThe derivative that is not the mean
A colleague writes Poisson as p(x∣λ)=x!1exp(xlogλ−λ), differentiates B(λ)=λ with respect to λ, and gets 1. They conclude that something is wrong with E[T]=∇A. What happened?
NumericThe UMVUE of the probability of zero
With X1,…,X10∼iidPois(λ) you observe ∑iXi=15. What is the UMVUE of e−λ=P(X=0)?
NumericHow far from the bound?
For Xi∼iidPois(λ), with λ=2 and n=10, calculate the ratio between the variance of the UMVUE ((n−1)/n)S of e−λ and the Cramér–Rao bound for estimating e−λ.
NumericThe uniform UMVUE
With X1,…,X4∼iidUnif(0,θ) you observe x(4)=maxixi=8. What is the UMVUE of θ?
QuizAn embarrassing UMVUE
With a single observation X∼Pois(λ), the only unbiased estimator of e−2λ is (−1)X. Which conclusion is correct?
ProofThe factorization theorem, discrete case
Prove: Let X be discrete with probability mass pθ(x) and let T=T(X) be a statistic. T is sufficient for θ if and only if there exist gθ≥0 and h≥0 with pθ(x)=gθ(T(x))h(x) for every x and θ.
0
Prove both implications.
Step 1 of 4. (⇒) Suppose T is sufficient. How do you obtain the factorization?
ProofRao–Blackwell using total variance
Prove: Let δ be an estimator of g(θ) with Eθ[δ2]<∞, T sufficient, and δ∗=E[δ∣T]. Then Eθ[(δ∗−g(θ))2]≤Eθ[(δ−g(θ))2] for every θ, with equality if and only if δ=δ∗ almost surely.
0
Fix θ.
Step 1 of 5. Why is δ∗ a legitimate estimator?
CodeGamma as an exponential family
For X∼Gamma(α,β) (shape α, rate β) with sufficient statistic T(x)=(logx,x) and h(x)=1, implement gamma_natural(alpha, beta), returning natural parameter η as an array of shape (2,); gamma_A(eta), the closed-form log-partition A(η)=log∫0∞eη1logx+η2xdx; and gamma_hess_A(eta), its closed-form 2×2 Hessian (use scipy.special.polygamma). Tests compare A with numerical integration, the Hessian with finite differences of your A, and with the sample covariance of (logX,X) in a large simulation.
import numpy as np
from scipy.special import gammaln, polygamma
def gamma_natural(alpha, beta):
"""Parámetro natural eta de Gamma(alpha, beta), beta = tasa, con T(x) = (log x, x)."""
# tu código
return np.zeros(2)
def gamma_A(eta):
"""Log-partición A(eta) en forma cerrada."""
# tu código
return 0.0
def gamma_hess_A(eta):
"""Hessiano de A en eta, en forma cerrada."""
# tu código
return np.zeros((2, 2))
Shift+Enter to run
Summary
Key idea
A sufficient statistic compresses data without losing anything about θ; with fixed support, exponential families are the only models allowing fixed-dimensional compression, and their log-partition A(η) yields moments, Fisher information and the MLE by differentiation.
T is sufficient if the law of X given T does not depend on θ; the factorization theorem, pθ(x)=gθ(T(x))h(x), checks this in practice. The likelihood-ratio criterion gives the minimal sufficient statistic, whose dimension need not equal the parameter’s.
In an exponential family h(x)exp(η⊤T(x)−A(η)): ∑iT(Xi) is sufficient with fixed dimension, A is convex, ∇A=E[T], ∇2A=Cov[T]=I(η), and the MLE solves ∇A(η^)=Tˉ, uniquely by convexity. Tˉ is efficient for the mean parameter.
By Pitman–Koopman–Darmois, outside these families (Cauchy, mixtures), the minimal sufficient statistic is the order statistics: no compression and generally no concavity.
Rao–Blackwell: E[δ∣T] preserves bias and does not increase MSE; the gain is E[Var(δ∣T)]. If T is also complete, Lehmann–Scheffé says the unique unbiased function of T is the UMVUE.
The UMVUE is not always desirable: it may be absurd, lose to biased estimators in MSE, or not exist. Unbiasedness is a constraint, not an objective.