Statistical decision theory and shrinkage: Stein's paradox
Compare estimators through decision-theoretic risk and derive James–Stein shrinkage and empirical Bayes.
After this lesson you can
- Define loss, risk, Bayes rules, admissibility and minimaxity.
- Derive Stein’s unbiased risk estimator and James–Stein dominance.
- Apply shrinkage and empirical Bayes to groups of unequal size.
Before you start
- 05Mean squared error bias-variance decompositionMaximum likelihood estimator (MLE)Prior, likelihood and posteriorConjugate priorsMaximum a posteriori estimatorMarginal likelihood (evidence)
- 04Multivariate Gaussian distributionAffine transformations of Gaussians
- 03Integration by substitution and by parts
Motivation: five hundred failure rates with little data
You have 500 production microservices and want to estimate each failure rate using one week’s data. Some receive thousands of requests, others only dozens. For service , with requests and failures, the natural estimate is raw rate , the binomial maximum likelihood estimator, also unbiased. Yet ranking services by raw rate to decide which to inspect fills the top with small services: with 20 requests, three failures give 15% even when true rate is 3%. Extremes of a list of noisy estimates are mostly noise.
An engineer intuitively corrects this: 15% from 20 requests is “less believable” than 15% from 2000, so pull it toward the fleet’s typical rate. But correction raises questions previous lessons cannot answer:
- What does “better” mean? Raw rate is unbiased and efficient for each service separately. Correcting it introduces bias. By what criterion can a biased estimator win?
- Is using other data legitimate? If services are independent, failures of service 7 say nothing about service 312. Why would they improve its estimate?
- How much correction? Neither raw rate nor fleet mean: something between, different for each service according to size.
This lesson constructs the framework answering all three: Wald’s statistical decision theory, making “better” a mathematical claim about risk functions. It contains classical statistics’ most surprising result, proved by Charles Stein in 1956 and made explicit as an estimator by James and Stein in 1961: when estimating three or more normal means at once, the seemingly unbeatable sample mean is dominated. Another estimator has smaller total squared error for every possible set of means, even when they are unrelated. Viewed Bayesianly, this estimator is exactly the correction the engineer’s intuition requested.
Loss, risk and the impossibility of a uniformly best estimator
First separate three things often mixed in practice: what is decided, the cost of error, and how that cost is averaged.
In estimation, and the rule is an estimator. Common losses are squared (or in several dimensions), whose risk is mean squared error from the bias–variance decomposition; absolute , less sensitive to large errors; 0–1 , distinguishing success from failure; and weighted versions like , measuring error relative to parameter scale. A hypothesis test is also a decision rule: , 0–1 loss counts errors, and risk is probability of type I error on and type II on .
The crucial point is what kind of object risk is: a function of , not a number. Comparing estimators means comparing curves.
An example throughout the lesson
Let and consider linear rules
With this is MLE ; with , Laplace estimator . By bias plus variance, with and ,
MLE risk is : maximal at and zero at endpoints. Rules with pay bias near endpoints in exchange for lower variance at center. The absurd rule , ignoring data, has risk : exactly zero at .
The figure shows the central issue. With , MLE wins near endpoints, Laplace in an intermediate band, minimax in two bands on both sides of , and the constant rule ignoring data wins throughout , where . None lies below all others throughout .
Proof
Constant rule has . If were uniformly better, , i.e. for . Similarly with , for . But and are disjoint, so and would be concentrated on disjoint sets: mutually singular. Contradiction.
∎Assumptions are minimal: whenever one sample does not reveal with certainty, “which estimator is best?” has no answer. There are three exits, each producing a theory:
- Restrict the rule class. Among unbiased estimators a uniform optimum can exist, the UMVUE from sufficiency. The price is discarding all biased estimators in advance, and this lesson shows some are much better.
- Summarize the curve by a number. Average with a weight (Bayes risk) or take its worst value (minimax risk). Either turns partial ordering of curves into total ordering.
- Retain partial ordering. Although no best exists, some rules are worse: another beats them for all . Discarding these is admissibility.
Bayes risk and Bayes rules
Given a weight on , either a prior as in Bayesian updating or simply a way to emphasize values of , summarize risk by its weighted average.
Minimizing an integral over all functions looks like calculus of variations. It is not: for each observed , minimize a quantity depending only on posterior.
Proof
Since , Tonelli’s theorem permits exchanging integration order without further conditions. Using , for any rule ,
For each , the right-hand integrand is at least . Integrating gives .
∎This theorem bridges the two schools. Bayes risk is a frequentist criterion (averages over unobserved data), and its minimizer is computed using a Bayesian object (posterior given observed data). No need to think about : a Bayes rule is what a Bayesian would do with posterior and a given loss. Loss decides the optimal posterior summary.
Proof
(1) You reconstruct this in the first proof exercise by completing the square around posterior mean.
(2) Let be a posterior median and (case is symmetric). If , . If , triangle inequality gives . Combining,
and taking posterior expectation, , since because is a median. Thus every median minimizes. Conversely, if is not a median, e.g. , then for sufficiently close , because the right derivative of at is .
(3) : minimizing it maximizes mass of . Let be the mode, density strictly increasing to its left and decreasing to its right. If the interval lies entirely left of (), shifting it right adds higher-density mass than removed, likewise in reverse to the right of . Thus every optimal interval contains , its center satisfies , and approaches as .
(4) is a parabola in minimized at the stated ratio.
∎In the binomial example with prior , conjugacy yields posterior . Its mean is , so orange curves in the figure are Bayes rules, one per prior. Its mode is , which under uniform prior is MLE: the MAP estimator is the limit of Bayes rules under 0–1 loss, not the Bayes rule for any reasonable loss in a continuous problem. This explains parameterization dependence: under posterior density gains a Jacobian and mode of is not of mode of . Median is equivariant under monotone , while mean changes only because squared loss on scale is a different loss. Its median has no closed form; for (three successes in ten with uniform prior) it is , between mode and mean .
Admissibility
The third exit from the dead end does not pick a winner; it discards losers.
An inadmissible rule is indefensible under that loss: another never does worse and sometimes does better, whatever the parameter. Admissibility is a low bar: constant rule is admissible in the binomial example, because any rule matching it at must equal almost surely. Admissibility is a necessary condition for sense, not a certificate of quality.
How can a rule be proved admissible? The main tool is that Bayes rules nearly always are.
Proof
Suppose dominates . Integrating against gives , so is Bayes too.
(1) By uniqueness, almost surely under every , hence risks agree for every and cannot be strictly better anywhere. Contradiction.
(2) Some has . By continuity, there are and an open neighborhood of where the gap exceeds . Then , contradicting Bayes optimality of .
∎In the binomial example, every in has positive probability for any , and posterior mean is unique for each : rules with are unique Bayes rules and thus admissible. MLE is also admissible, by a useful trick. Under weighted loss and uniform prior, point 4 of the posterior-mean theorem gives , exactly with posterior for (also at and , checked separately). Thus is the unique Bayes rule for that loss and admissible under it. Since weighted risk is with the same positive factor for every rule, removing it does not change dominance: is also admissible under squared loss.
One normal mean: admissible in dimension 1
Turn to the model used in the rest of the lesson, with . Estimator is not Bayes for any proper prior (under squared loss an unbiased estimator can be Bayes only with zero Bayes risk), but it is a limit of Bayes rules, which suffices.
Proof
Blyth’s argument (1951). Suppose dominates : for every and at some . In the normal family risks are continuous in , so some satisfy when . Take prior . By the normal-normal example its Bayes rule has Bayes risk , and Bayes optimality gives
Rearranging, . But probability on the left is at least , decaying as , while right side decays as . Multiply by and let : left tends to , right to 0. Contradiction.
∎Repeat in dimension with and prior . The gap between risk and Bayes-rule risk is now , order , while a fixed ball’s prior probability is order . At probability wins and yields contradiction. At they tie and the argument is inconclusive (Stein proved remains admissible in 1956 with finer priors). At the gap wins decisively and the argument says nothing. This is not a proof weakness: at , is inadmissible.
Minimax: protection against the worst case
The other way to summarize the risk curve is its worst value.
The minimax criterion describes a game against an adversary choosing after seeing your rule. Finding the infimum of a supremum over all functions seems harder than finding a Bayes rule, but a shortcut exists: a Bayes rule without weak points is minimax.
Proof
For any rule , supremum exceeds any weighted average:
The second inequality uses Bayes optimality of , the third the hypothesis. For any other prior , , so is least favorable. If were another minimax rule, the whole chain would be equalities, , making Bayes and hence equal to by uniqueness.
∎In the binomial example, find making the numerator of constant:
Setting the coefficient to zero gives , and the coefficient gives , i.e. . The Bayes rule under prior is
constant, hence minimax (unique because the Bayes rule is unique), and prior is least favorable: it concentrates mass around , hardest to estimate. At , maximum risk drops from (MLE) to . But minimax beats MLE only when , i.e. ; outside this band it loses, badly near endpoints. As grows, maximum-risk ratio tends to 1 and minimax’s winning band narrows toward . If proportions are failure or conversion rates of a few percent, minimax optimizes a region that does not matter to you. Minimax guarantees against worst case, which may not be yours.
The same vocabulary extends to sequential decisions changing subsequent observed data. In reinforcement-learning bandits, loss is regret versus the best action, and minimax regret bounds play the role of this section’s minimax risk.
For normal means no proper Bayes rule has constant risk, but a limiting version works.
Proof
For any and every , . Taking limits gives .
∎With , risk of is and priors have optimal Bayes risk . Thus is minimax in every dimension. Any rule dominating is too. Minimax and admissible are independent properties; the next section constructs a rule dominating another minimax rule.
Stein’s lemma and the unbiased risk estimator
From here, with known : means estimated at once, each with one noisy independent observation (or a mean of several, equivalent with another ). This is a multivariate Gaussian with diagonal covariance. Loss is total squared loss , and risk of is . We seek estimators and must compute risk without knowing . The tool is Gaussian integration by parts, familiar as Stein’s lemma.
Proof
Let be the density of . The key identity is , from differentiating: and . Likewise, . Since , subtract :
In the first term write and exchange integration order, justified by Fubini because :
The second term similarly gives . Adding yields .
∎This is integration by parts of against , with , written without assuming behavior of at infinity: suffices. Applied coordinatewise (conditioning on the independent remaining coordinates), it gives the multivariate version: if each is absolutely continuous in for almost all other coordinates and , then .
Proof
Expand and take expectations. The first term is and Stein’s lemma turns the second into .
∎The remarkable result: risk of any smooth normal-mean estimator can be estimated without knowing the mean. Stein published it in 1981; it underlies hyperparameter selection without cross-validation, such as wavelet soft-threshold choice (Donoho–Johnstone SureShrink) or in ridge regression, whose divergence term is effective degrees of freedom. A caveat quantified in the first code cell: SURE is unbiased on average, but in one realization can be far from realized loss.
James–Stein: sample mean is inadmissible
Seek a correction pulling toward zero more strongly when closer to zero: .
Proof
With and , calculate both SURE pieces. Each coordinate derivative is
Thus and , and
It remains to justify lemma assumptions. is smooth except at zero, where and derivatives . In polar coordinates, , finite exactly when . Thus for , (Gaussian density is bounded) and all lemma expectations are finite; absolute continuity in each coordinate fails only on a null set. Since , the subtracted term is strictly positive.
∎The proof also explains dimension. At , and coefficient is not positive: at the formula gives , “shrinkage” that expands and has infinite risk. The 2 in appears in the divergence of , and is the same 2 making Brownian motion recurrent in the plane and transient in space: Brown (1971) showed admissibility of generalized Bayes normal-mean estimators is equivalent to recurrence of an associated diffusion.
Exact risk uses the distribution of , noncentral with parameter , a mixture of central with . Since ,
Three readings:
- At risk is for any . With , estimator’s average total error is versus : five times smaller.
- Far from zero the gain fades. By Jensen’s inequality, , so . Gain is large when is comparable to or below , and tends to 0 (never vanishing) as .
- The origin is not special. Applying the theorem to , estimator dominates for any preselected point . Gain depends on : a good point helps, a bad one does not hurt.
What the paradox does not say
James–Stein improves total error, not each component’s. For a particular coordinate its risk can greatly exceed : with , and , first-coordinate risk is about versus for , while total risk is about versus . The atypical component is pulled toward an unsuitable center, while the nine typical components gain more than it loses. If one component matters (the service being debugged, player to hire), the theorem promises nothing.
It also does not say means are related. The theorem holds for arbitrary : combine tea price, tree height and Mars temperature in one vector (with equalized variances), and James–Stein reduces total error. Explanation is geometric, not causal: has mean , so is systematically too long, and at there is enough information in to estimate how much to shorten it. Whether total improvement matters is a loss-function choice, not a theorem; common mistakes returns to this.
Positive part and shrinkage toward the grand mean
When , James–Stein’s factor is negative and the estimator reverses ‘s sign: absurd. The positive-part version truncates it at zero,
and dominates (Baranchik, 1964). Write with and . Losses differ only when , where
The first term is positive, and expectation of the second conditional on is nonnegative: on each sphere, density is proportional to and favors points with . So truncation never worsens risk and sometimes improves it. (Positive-part itself is inadmissible because an admissible rule here must be analytic, but known improvements are tiny.)
In practice the natural shrinkage target is the grand mean , not fixed in advance. Estimator
dominates if . Proof is change of basis: decompose into the line of and its orthogonal complement of dimension . Leave the component on unchanged () and apply James–Stein in dimension to orthogonal component , giving constant . Estimating the center costs one degree of freedom.
Empirical Bayes: James–Stein as prior estimation
Return to normal-normal, now with units:
If and were known, Bayes rule would be with , Bayes risk . They are not. But we have observations of the marginal distribution: since sums independent normals (an affine transformation of a Gaussian vector), marginally . With known , , and since ,
James–Stein is the Bayes rule replacing by an unbiased estimate of calculated from data. This is Efron–Morris (1973), the founding example of empirical Bayes: with many parallel units, prior hyperparameters are estimated from marginal data distribution (by moments as here, or maximizing marginal likelihood), then plugged into the Bayes rule. Robbins proposed it in 1956; James–Stein gave frequentist justification.
The price of unknown is exact. Under the hierarchical model James–Stein Bayes risk is , i.e.
Extra cost is at most in total, independent of : with many units empirical Bayes is nearly as good as Bayes knowing the prior. It also retains a guarantee pure Bayes lacks: it dominates even if the normal prior is false, because James–Stein holds for each fixed .
Two generalizations matter in real problems:
- Unequal variances. If , e.g. group has observations and , Bayes shrinks each unit by its own : small groups shrink more. Estimate and by maximizing marginal likelihood . No dominance theorem as clean as James–Stein applies here, but it works well in practice, as the fourth code cell shows.
- Other models. For counts or proportions, conjugate beta-binomial gives posteriors , with estimated by beta-binomial marginal maximum likelihood. The same shrinkage, with factor depending on group size.
Efron and Morris’s baseball players
Efron and Morris popularized the paradox using batting averages of 18 players in the 1970 major-league baseball season after their first 45 at-bats. The goal is predicting average for the remainder. Let be the first-45 average. Under a normal approximation, and , where is the mean of the 18. Shrinking to grand mean (constant with ),
Roberto Clemente, 18 hits in 45 at-bats (), moves to ; his remaining-season average was . Total squared error against the remainder drops from (MLE) to (James–Stein), a factor . Sixteen of 18 players improve.
Best hindsight is , error : James–Stein, without seeing the rest of the season, chooses and lies within of optimum. Even full shrinkage, (predict the 18-player mean for all), with error , beats MLE: here 45-at-bat noise () exceeds true between-player dispersion. The two who worsen are Swoboda and E. Rodriguez: they started below average (0.244 and 0.222) and remained low in the rest of the season (0.230 and 0.226), so shrinkage moved them too close to 0.265. Efron and Morris used an arcsine variance-stabilizing transformation in their 1975 paper; this direct version is from their 1977 popular article with the same data.
Shrinkage in practice
Group rates. Return to 500 services. The fourth code cell simulates a fleet with true rates (mean 3%) and 20 to 3000 requests per service, comparing raw rate with unequal-variance normal-normal empirical Bayes. Mean squared error versus truth drops by over half, and the list of twenty “most problematic” services is no longer dominated by services with about a hundred requests. The same holds for campaign conversion, supplier defect rates or store performance: with many proportions and highly unequal sizes, raw rate is the worst way to rank them.
Ratings and rankings. The “Bayesian average” used by rating sites, with votes averaging , grand mean and pseudovotes, is exactly a conjugate posterior mean: shrink toward with weight , more with fewer votes. Empirical Bayes chooses from data rather than by eye.
Regularization. Ridge is posterior mean (and MAP) in a linear model with Gaussian prior ; with orthonormal design it shrinks each least-squares coefficient by , this lesson’s . Choosing by marginal likelihood is empirical Bayes; choosing by SURE uses Stein’s lemma (see shrinkage in the singular-value basis). Applied to covariance matrices the same idea gives Ledoit–Wolf, and fully hierarchical models, putting priors on and instead of estimating them, are probabilistic-model partial pooling.
Implementation from scratch
The first cell calculates exact squared risk of proportion rules by summing over possible values rather than using closed form, and numerically finds the beta prior minimizing maximum risk.
import numpy as np
from scipy import stats, optimize
def riesgo_exacto(delta, n, ps):
"""R(p, delta) = sum_x (delta(x) - p)^2 P_p(X = x), para cada p de la rejilla."""
x = np.arange(n + 1)
pmf = stats.binom.pmf(x[:, None], n, ps[None, :]) # forma (n+1, len(ps))
return ((delta(x)[:, None] - ps[None, :]) ** 2 * pmf).sum(axis=0)
def integral(f, xs): # regla del trapecio
return float(((f[1:] + f[:-1]) / 2 * np.diff(xs)).sum())
n = 16
ps = np.linspace(0, 1, 401)
reglas = {
"EMV X/n": lambda x: x / n,
"Laplace (X+1)/(n+2)": lambda x: (x + 1) / (n + 2),
"minimax": lambda x: (x + np.sqrt(n) / 2) / (n + np.sqrt(n)),
"constante 1/2": lambda x: np.full(x.shape, 0.5),
}
print(f"{'regla':22s} {'máx R':>8s} {'mín R':>8s} {'Bayes unif.':>12s}")
for nombre, d in reglas.items():
R = riesgo_exacto(d, n, ps)
print(f"{nombre:22s} {R.max():8.5f} {R.min():8.5f} {integral(R, ps):12.5f}")
# prior Beta(a, b) que minimiza el riesgo máximo de su media posterior
def riesgo_max(log_ab):
a, b = np.exp(log_ab)
return riesgo_exacto(lambda x: (x + a) / (n + a + b), n, ps).max()
res = optimize.minimize(riesgo_max, x0=np.log([1.0, 1.0]), method="Nelder-Mead",
options={"xatol": 1e-8, "fatol": 1e-12})
a, b = np.exp(res.x)
print(f"\nprior menos favorable: Beta({a:.4f}, {b:.4f}); sqrt(n)/2 = {np.sqrt(n) / 2}")
print(f"riesgo máximo: {res.fun:.6f}; 1/(4(1 + sqrt n)^2) = {1 / (4 * (1 + np.sqrt(n)) ** 2):.6f}")
R_mm, R_emv = riesgo_exacto(reglas["minimax"], n, ps), riesgo_exacto(reglas["EMV X/n"], n, ps)
gana = ps[R_mm < R_emv]
print(f"el minimax gana al EMV solo para p en [{gana.min():.4f}, {gana.max():.4f}]")The optimizer finds without being told risk must be constant, and maximum risk matches formula . The table reproduces figure numbers: minimax has smallest maximum risk, Laplace smallest Bayes risk under uniform prior (, as expected since it is that prior’s Bayes rule), and constant wins at with zero risk.
Now Stein’s lemma and SURE by Monte Carlo.
import numpy as np
rng = np.random.default_rng(0)
mu, sigma = 0.7, 1.5
Z = rng.normal(mu, sigma, 1_000_000)
pruebas = [("tanh", np.tanh, lambda z: 1 - np.tanh(z) ** 2),
("z^3", lambda z: z ** 3, lambda z: 3 * z ** 2),
("|z|", np.abs, np.sign)] # |z| no es derivable en 0, pero sí absolutamente continua
for nombre, g, dg in pruebas:
izq = np.mean((Z - mu) * g(Z))
der = sigma ** 2 * np.mean(dg(Z))
print(f"g = {nombre:5s} E[(Z - mu) g(Z)] = {izq:8.4f} sigma^2 E[g'(Z)] = {der:8.4f}")
# SURE de James-Stein: p sigma^2 - (p - 2)^2 sigma^4 / ||X||^2, con sigma = 1
p = 10
mu_v = np.linspace(-1, 2, p)
X = mu_v + rng.standard_normal((20000, p))
n2 = (X ** 2).sum(axis=1)
js = (1 - (p - 2) / n2)[:, None] * X
perdida = ((js - mu_v) ** 2).sum(axis=1)
sure = p - (p - 2) ** 2 / n2
print(f"\npérdida media de JS = {perdida.mean():.3f} SURE medio = {sure.mean():.3f} riesgo de X = {p}")
print(f"correlación entre pérdida y SURE réplica a réplica: {np.corrcoef(perdida, sure)[0, 1]:.2f}")Both columns agree within Monte Carlo error, including , nondifferentiable but absolutely continuous. SURE is correct on average (6.54 versus mean loss 6.50, within Monte Carlo error), but per-replicate correlation with realized loss is negative (). When noise shortens by chance, is small and SURE predicts low loss, yet James–Stein then shrinks strongly toward an origin far from , increasing real loss. It compares rules on average, not one realization’s error.
The third cell implements James–Stein with arbitrary shrinkage target and checks dominance in several dimensions.
import numpy as np
def james_stein(x, sigma2=1.0, nu=0.0, plus=False):
"""James-Stein hacia nu aplicado a cada fila de x (forma (réplicas, p) o (p,))."""
x = np.atleast_2d(np.asarray(x, dtype=float))
p = x.shape[1]
d = x - nu
factor = 1 - (p - 2) * sigma2 / (d ** 2).sum(axis=1, keepdims=True)
if plus:
factor = np.maximum(factor, 0.0)
return nu + factor * d
rng = np.random.default_rng(1)
reps = 20000
print(" p R(X) R(JS) R(JS+) P(JS gana en una réplica)")
for p in [2, 3, 5, 10, 20]:
mu = rng.normal(1.0, 1.0, p) # unas medias cualesquiera, fijas en la simulación
X = mu + rng.standard_normal((reps, p))
perdida = lambda est: ((est - mu) ** 2).sum(axis=1)
lx, lj, lp = perdida(X), perdida(james_stein(X)), perdida(james_stein(X, plus=True))
print(f"{p:2d} {lx.mean():6.3f} {lj.mean():6.3f} {lp.mean():6.3f} {np.mean(lj < lx):.3f}")
# el riesgo exacto en mu = 0 es 2 para todo p >= 3
for p in [3, 10, 50]:
X = rng.standard_normal((reps, p))
print(f"p = {p:2d}, mu = 0: riesgo simulado de JS = {((james_stein(X)) ** 2).sum(axis=1).mean():.3f}")At factor is exactly 1 and there is no gain. From , James–Stein wins in risk, and probability of winning one realization grows with but never reaches 1: dominance concerns averages. At risk is 2 in every dimension (at simulation is noisier because has infinite variance for ).
The fourth cell addresses the motivation: unequal-variance normal-normal empirical Bayes, estimating and by marginal maximum likelihood and validating against next-period data.
import numpy as np
from scipy import optimize
rng = np.random.default_rng(2026)
k = 500
p_real = rng.beta(2, 60, k) # tasas reales, media ~3 %
n_pet = np.round(np.exp(rng.uniform(np.log(20), np.log(3000), k))).astype(int)
fallos = rng.binomial(n_pet, p_real)
fallos_sig = rng.binomial(10 * n_pet, p_real) # periodo siguiente, más largo
tasa, tasa_sig = fallos / n_pet, fallos_sig / (10 * n_pet)
def bayes_empirico_normal(x, s2):
"""Normal-normal con varianzas desiguales: EMV marginal de (nu, tau2) y medias posteriores."""
def nll(log_tau2): # -log verosimilitud marginal, perfilando nu
v = s2 + np.exp(log_tau2)
nu = np.sum(x / v) / np.sum(1 / v)
return 0.5 * np.sum(np.log(v) + (x - nu) ** 2 / v)
tau2 = np.exp(optimize.minimize_scalar(nll, bounds=(-20, 2), method="bounded").x)
v = s2 + tau2
nu = np.sum(x / v) / np.sum(1 / v)
B = s2 / v # contracción de cada unidad
return nu + (1 - B) * (x - nu), nu, tau2, B
p_glob = fallos.sum() / n_pet.sum()
s2 = p_glob * (1 - p_glob) / n_pet # varianza binomial con la tasa global
post, nu, tau2, B = bayes_empirico_normal(tasa, s2)
print(f"nu = {nu:.4f} tau = {np.sqrt(tau2):.4f} contracción B: de {B.min():.3f} (grandes) a {B.max():.3f} (pequeños)")
for nombre, est in [("tasa bruta", tasa), ("media global", np.full(k, p_glob)), ("bayes empírico", post)]:
print(f"{nombre:15s} ECM frente a la verdad = {np.mean((est - p_real) ** 2):.2e}"
f" frente al periodo siguiente = {np.mean((est - tasa_sig) ** 2):.2e}")
top = lambda v: set(np.argsort(-v)[:20])
peores = top(p_real)
print(f"de los 20 con mayor tasa estimada, están entre los 20 peores reales: bruta {len(top(tasa) & peores)}, "
f"bayes empírico {len(top(post) & peores)}")
print(f"peticiones medianas del top 20: bruta {np.median(n_pet[list(top(tasa))]):.0f}, "
f"bayes empírico {np.median(n_pet[list(top(post))]):.0f}")MSE against truth falls from to , and next-period validation, all one would have in production, tells the same story. Shrinkage ranges from 2% for large services to 77% for small ones. The twenty-worst list improves from 9 to 12 hits and, above all, changes composition: median requests in the top 20 rise from 96 to 382. Small services enter only with overwhelming evidence.
Finally, the baseball players, using Efron and Morris’s article data.
import numpy as np
nombres = ["Clemente", "F. Robinson", "F. Howard", "Johnstone", "Berry", "Spencer", "Kessinger",
"L. Alvarado", "Santo", "Swoboda", "Unser", "Williams", "Scott", "Petrocelli",
"E. Rodriguez", "Campaneris", "Munson", "Alvis"]
aciertos = np.array([18, 17, 16, 15, 14, 14, 13, 12, 11, 11, 10, 10, 10, 10, 10, 9, 8, 7])
resto = np.array([.346, .298, .276, .222, .273, .270, .263, .210, .269, .230, .264, .256,
.303, .264, .226, .285, .316, .200]) # promedio en el resto de 1970
y = aciertos / 45
k, ybar = len(y), y.mean()
sigma2 = ybar * (1 - ybar) / 45
S = np.sum((y - ybar) ** 2)
c = 1 - (k - 3) * sigma2 / S
js = ybar + c * (y - ybar)
print(f"media global = {ybar:.4f} sigma^2 = {sigma2:.5f} S = {S:.4f} c = {c:.3f}")
print(f"error total: EMV = {np.sum((y - resto) ** 2):.4f} James-Stein = {np.sum((js - resto) ** 2):.4f}"
f" media global = {np.sum((ybar - resto) ** 2):.4f}")
d, e = y - ybar, resto - ybar
print(f"c óptimo a posteriori = {np.sum(d * e) / np.sum(d * d):.3f}")
mejor = np.abs(js - resto) < np.abs(y - resto)
print(f"mejoran {mejor.sum()} de {k}; empeoran: {[n for n, m in zip(nombres, mejor) if not m]}")
print(f"Clemente: {y[0]:.3f} -> {js[0]:.3f} (resto de la temporada: {resto[0]:.3f})")The library version
Neither SciPy nor scikit-learn has james_stein; shrinkage appears within other methods. For proportions, use the full beta-binomial model, whose marginal likelihood is in scipy.stats.betabinom. For covariance matrices, sklearn.covariance.LedoitWolf shrinks sample covariance toward a multiple of identity with data-estimated strength.
import numpy as np
from scipy import stats, optimize
from sklearn.covariance import LedoitWolf, empirical_covariance
# mismos 500 servicios que antes (misma semilla)
rng = np.random.default_rng(2026)
k = 500
p_real = rng.beta(2, 60, k)
n_pet = np.round(np.exp(rng.uniform(np.log(20), np.log(3000), k))).astype(int)
fallos = rng.binomial(n_pet, p_real)
def nll(theta): # -log verosimilitud marginal beta-binomial
a, b = np.exp(theta)
return -stats.betabinom.logpmf(fallos, n_pet, a, b).sum()
r = optimize.minimize(nll, x0=np.log([1.0, 30.0]), method="Nelder-Mead")
a, b = np.exp(r.x)
post = (fallos + a) / (n_pet + a + b) # media posterior Beta(a + x, b + n - x)
print(f"a = {a:.2f}, b = {b:.1f} (verdad: 2 y 60)")
print(f"ECM: tasa bruta {np.mean((fallos / n_pet - p_real) ** 2):.2e} beta-binomial {np.mean((post - p_real) ** 2):.2e}")
peso = (a + b) / (n_pet + a + b)
print(f"peso del prior: {peso.min():.3f} con {n_pet.max()} peticiones, {peso.max():.3f} con {n_pet.min()}")
# Ledoit-Wolf: 30 muestras de dimensión 20
d, m = 20, 30
L = rng.normal(size=(d, d)) / np.sqrt(d)
Sigma = L @ L.T + 0.5 * np.eye(d)
Xm = rng.multivariate_normal(np.zeros(d), Sigma, size=m)
for nombre, est in [("muestral", empirical_covariance(Xm)), ("Ledoit-Wolf", LedoitWolf().fit(Xm).covariance_)]:
print(f"{nombre:12s} error de Frobenius = {np.linalg.norm(est - Sigma):.3f} "
f"número de condición = {np.linalg.cond(est):.0f}")
print(f"intensidad de contracción estimada: {LedoitWolf().fit(Xm).shrinkage_:.3f}")Beta-binomial recovers the generating hyperparameters and gives nearly the same MSE as the normal approximation without requiring it. Form shows each service shrinks with weight : large groups little, small ones much. Ledoit–Wolf, with estimated shrinkage 0.47, reduces covariance Frobenius error from 6.9 to 3.8 and especially condition number from 447 to 7: with 30 samples in dimension 20, sample covariance is nearly singular, and anything inverting it (minimum-variance portfolio, Mahalanobis distance) amplifies noise.
Common mistakes
Exercises
Step 1 of 4. How decompose ?
Step 1 of 4. What property of enables integration by parts?
scipy.stats.beta.)More than one answer may be correct.
More than one answer may be correct.
js_media_global(x, sigma2=1.0), receiving a length- vector x of independent and returning , where is the mean of x and . Return a float array of the same shape. Tests check specific values, truncation, translation equivariance and that with simulated risk is clearly below that of .import numpy as np
def js_media_global(x, sigma2=1.0):
"""James-Stein positive-part hacia la media global de x."""
x = np.asarray(x, dtype=float)
# tu código: media global, S, factor (p - 3) sigma2 / S truncado en [0, 1]
return x.copy()Summary
- A decision problem specifies loss ; risk is a function of , and except in trivial cases no rule minimizes risk at every simultaneously.
- Bayes risk averages risk under a prior. Its minimizer uses the observed-data posterior: posterior mean for squared loss, median for absolute loss, and mode in the 0–1 limit.
- A rule is admissible if no other dominates it. Unique Bayes rules (or with full-support priors and continuous risks) are admissible; unbiasedness does not prevent inadmissibility.
- A constant-risk Bayes rule is minimax and its prior least favorable: binomial , risk , beats MLE only near . is minimax for a normal mean in every dimension.
- Stein’s lemma yields unbiased risk estimator SURE. James–Stein has risk for ; positive part improves it and grand-mean shrinkage requires .
- James–Stein is the normal-normal Bayes rule with factor estimated unbiasedly from data. With unequal variances each group has its own , shrinking more when smaller. Ridge, Ledoit–Wolf and hierarchical models share this idea.