Module contents
Lesson 23 of 27Advanced 105 min

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

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 ii, with nin_i requests and xix_i failures, the natural estimate is raw rate xi/nix_i/n_i, 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, A=Θ\mathcal{A} = \Theta and the rule is an estimator. Common losses are squared L(θ,a)=(a−θ)2L(\theta, a) = (a - \theta)^2 (or ∥a−θ∥2\norm{\vb{a} - \vb{\theta}}^2 in several dimensions), whose risk is mean squared error from the bias–variance decomposition; absolute ∣a−θ∣\abs{a - \theta}, less sensitive to large errors; 0–1 1[∣a−θ∣>ε]\ind[\abs{a - \theta} > \eps], distinguishing success from failure; and weighted versions like w(θ)(a−θ)2w(\theta)(a - \theta)^2, measuring error relative to parameter scale. A hypothesis test is also a decision rule: A={aceptar,rechazar}\mathcal{A} = \{\text{aceptar}, \text{rechazar}\}, 0–1 loss counts errors, and risk is probability of type I error on Θ0\Theta_0 and type II on Θ1\Theta_1.

The crucial point is what kind of object risk is: a function of θ\theta, not a number. Comparing estimators means comparing curves.

An example throughout the lesson

Let X∼Bin⁡(n,p)X \sim \Bin(n, p) and consider linear rules

δa,b(X)=X+an+a+b,a,b≥0.\delta_{a, b}(X) = \frac{X + a}{n + a + b}, \qquad a, b \ge 0.

With a=b=0a = b = 0 this is MLE X/nX/n; with a=b=1a = b = 1, Laplace estimator (X+1)/(n+2)(X + 1)/(n + 2). By bias plus variance, with EpX=np\E_p X = np and Var⁡pX=np(1−p)\Var_p X = np(1 - p),

R(p,δa,b)=np(1−p)(n+a+b)2+(np+an+a+b−p)2=np(1−p)+(a−(a+b)p)2(n+a+b)2.R(p, \delta_{a, b}) = \frac{np(1 - p)}{(n + a + b)^2} + \Big(\frac{np + a}{n + a + b} - p\Big)^2 = \frac{np(1 - p) + \big(a - (a + b)p\big)^2}{(n + a + b)^2}.

MLE risk is p(1−p)/np(1 - p)/n: maximal at p=1/2p = 1/2 and zero at endpoints. Rules with a,b>0a, b > 0 pay bias near endpoints in exchange for lower variance at center. The absurd rule δ≡1/2\delta \equiv 1/2, ignoring data, has risk (p−1/2)2(p - 1/2)^2: exactly zero at p=1/2p = 1/2.

InteractiveCrossing risk functions
strip: rule with lowest risk at each p
  • MLE X/nX/n
  • Bayes, prior Beta(1.00,1.00)\mathrm{Beta}(1.00, 1.00)
  • Minimax (X+n/2)/(n+n)(X + \sqrt{n}/2)/(n + \sqrt{n})
  • Constant δ≡1/2\delta \equiv 1/2
16
Prior for the Bayes rule
1.00
1.00
0.300
Visible rules
× 10⁻³
R(0.30)R(0.30)
max
Bayes
MLE
13.1
15.6
10.4
Bayes
10.9
12.3
9.3
Minimax
10.0
10.0
10.0
Constant
40.0
250
83.3
No visible rule dominates another: each wins over some range of pp.
Exact squared risk versus true pp for four binomial-proportion estimators. Orange curve is posterior mean under an adjustable Beta(a,b)\mathrm{Beta}(a, b) prior; the lower band shows which visible rule has least risk at each pp. First observe curves crossing: none wins for every pp, even against the constant rule. Then set a=b=n/2a = b = \sqrt{n}/2: orange becomes flat and coincides with minimax. Compare maximum risk and Bayes risk under a uniform prior for each rule in the table, and increase nn to see the region where minimax beats MLE narrow.

The figure shows the central issue. With n=16n = 16, MLE wins near endpoints, Laplace in an intermediate band, minimax in two bands on both sides of 1/21/2, and the constant rule ignoring data wins throughout (0.4,0.6)(0.4, 0.6), where (p−1/2)2<0.01(p - 1/2)^2 < 0.01. None lies below all others throughout [0,1][0, 1].

Proof

Constant rule δ0≡θ0\delta_0 \equiv \theta_0 has R(θ0,δ0)=0R(\theta_0, \delta_0) = 0. If δ∗\delta^* were uniformly better, R(θ0,δ∗)=0R(\theta_0, \delta^*) = 0, i.e. Pθ0(A0)=1P_{\theta_0}(A_0) = 1 for A0={x:δ∗(x)=θ0}A_0 = \{x : \delta^*(x) = \theta_0\}. Similarly with δ1≡θ1\delta_1 \equiv \theta_1, Pθ1(A1)=1P_{\theta_1}(A_1) = 1 for A1={x:δ∗(x)=θ1}A_1 = \{x : \delta^*(x) = \theta_1\}. But A0A_0 and A1A_1 are disjoint, so Pθ0P_{\theta_0} and Pθ1P_{\theta_1} would be concentrated on disjoint sets: mutually singular. Contradiction.

∎

Assumptions are minimal: whenever one sample does not reveal θ\theta with certainty, “which estimator is best?” has no answer. There are three exits, each producing a theory:

  1. 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.
  2. 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.
  3. Retain partial ordering. Although no best exists, some rules are worse: another beats them for all θ\theta. Discarding these is admissibility.

Bayes risk and Bayes rules

Given a weight π\pi on Θ\Theta, either a prior as in Bayesian updating or simply a way to emphasize values of θ\theta, summarize risk by its weighted average.

Minimizing an integral over all functions δ:X→A\delta : \mathcal{X} \to \mathcal{A} looks like calculus of variations. It is not: for each observed xx, minimize a quantity depending only on posterior.

Proof

Since L≥0L \ge 0, Tonelli’s theorem permits exchanging integration order without further conditions. Using p(x∣θ) π( ⁣dθ)=π( ⁣dθ∣x) m(x)p(x \given \theta)\,\pi(\dd\theta) = \pi(\dd\theta \given x)\,m(x), for any rule δ\delta,

r(π,δ)=∫Θ∫XL(θ,δ(x)) p(x∣θ) ⁣dx π( ⁣dθ)=∫Xρ(δ(x)∣x) m(x) ⁣dx.r(\pi, \delta) = \int_\Theta \int_{\mathcal{X}} L(\theta, \delta(x)) \, p(x \given \theta) \dd x \, \pi(\dd\theta) = \int_{\mathcal{X}} \rho(\delta(x) \given x) \, m(x) \dd x.

For each xx, the right-hand integrand is at least ρ(δπ(x)∣x)\rho(\delta_\pi(x) \given x). Integrating gives r(π,δ)≥r(π,δπ)r(\pi, \delta) \ge r(\pi, \delta_\pi).

∎

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 R(θ,δ)R(\theta, \delta): 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 mm be a posterior median and a>ma > m (case a<ma < m is symmetric). If θ≤m\theta \le m, ∣θ−a∣−∣θ−m∣=(a−θ)−(m−θ)=a−m\abs{\theta - a} - \abs{\theta - m} = (a - \theta) - (m - \theta) = a - m. If θ>m\theta > m, triangle inequality gives ∣θ−a∣−∣θ−m∣≥−(a−m)\abs{\theta - a} - \abs{\theta - m} \ge -(a - m). Combining,

∣θ−a∣−∣θ−m∣≥(a−m)(1[θ≤m]−1[θ>m]),\abs{\theta - a} - \abs{\theta - m} \ge (a - m)\big(\ind[\theta \le m] - \ind[\theta > m]\big),

and taking posterior expectation, ρ(a∣x)−ρ(m∣x)≥(a−m)(P(θ≤m∣x)−P(θ>m∣x))≥0\rho(a \given x) - \rho(m \given x) \ge (a - m)\big(\Pr(\theta \le m \given x) - \Pr(\theta > m \given x)\big) \ge 0, since P(θ≤m∣x)≥1/2\Pr(\theta \le m \given x) \ge 1/2 because mm is a median. Thus every median minimizes. Conversely, if aa is not a median, e.g. P(θ≤a∣x)<1/2\Pr(\theta \le a \given x) < 1/2, then for sufficiently close a′>aa' > a, ρ(a′∣x)<ρ(a∣x)\rho(a' \given x) < \rho(a \given x) because the right derivative of ρ\rho at aa is P(θ≤a∣x)−P(θ>a∣x)<0\Pr(\theta \le a \given x) - \Pr(\theta > a \given x) < 0.

(3) ρ(a∣x)=1−P(∣θ−a∣≤ε∣x)\rho(a \given x) = 1 - \Pr(\abs{\theta - a} \le \eps \given x): minimizing it maximizes mass of [a−ε,a+ε][a - \eps, a + \eps]. Let MM be the mode, density strictly increasing to its left and decreasing to its right. If the interval lies entirely left of MM (a+ε<Ma + \eps < M), shifting it right adds higher-density mass than removed, likewise in reverse to the right of MM. Thus every optimal interval contains MM, its center satisfies ∣a−M∣≤ε\abs{a - M} \le \eps, and approaches MM as ε→0\eps \to 0.

(4) ρ(a∣x)=E[wθ2∣x]−2a E[wθ∣x]+a2 E[w∣x]\rho(a \given x) = \E[w\theta^2 \given x] - 2a\,\E[w\theta \given x] + a^2\,\E[w \given x] is a parabola in aa minimized at the stated ratio.

∎

In the binomial example with prior Beta(a,b)\mathrm{Beta}(a, b), conjugacy yields posterior Beta(a+x,b+n−x)\mathrm{Beta}(a + x, b + n - x). Its mean is (x+a)/(n+a+b)(x + a)/(n + a + b), so orange curves in the figure are Bayes rules, one per prior. Its mode is (x+a−1)/(n+a+b−2)(x + a - 1)/(n + a + b - 2), 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 η=g(θ)\eta = g(\theta) posterior density gains a Jacobian and mode of η\eta is not gg of mode of θ\theta. Median is equivariant under monotone gg, while mean changes only because squared loss on η\eta scale is a different loss. Its median has no closed form; for Beta(4,8)\mathrm{Beta}(4, 8) (three successes in ten with uniform prior) it is 0.32380.3238, between mode 0.30.3 and mean 0.33330.3333.

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 δ≡1/2\delta \equiv 1/2 is admissible in the binomial example, because any rule matching it at p=1/2p = 1/2 must equal 1/21/2 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 δ′\delta' dominates δπ\delta_\pi. Integrating R(θ,δ′)≤R(θ,δπ)R(\theta, \delta') \le R(\theta, \delta_\pi) against π\pi gives r(π,δ′)≤r(π,δπ)r(\pi, \delta') \le r(\pi, \delta_\pi), so δ′\delta' is Bayes too.

(1) By uniqueness, δ′=δπ\delta' = \delta_\pi almost surely under every PθP_\theta, hence risks agree for every θ\theta and δ′\delta' cannot be strictly better anywhere. Contradiction.

(2) Some θ0\theta_0 has R(θ0,δ′)<R(θ0,δπ)R(\theta_0, \delta') < R(\theta_0, \delta_\pi). By continuity, there are η>0\eta > 0 and an open neighborhood UU of θ0\theta_0 where the gap exceeds η\eta. Then r(π,δπ)−r(π,δ′)≥η π(U)>0r(\pi, \delta_\pi) - r(\pi, \delta') \ge \eta\,\pi(U) > 0, contradicting Bayes optimality of δπ\delta_\pi.

∎

In the binomial example, every XX in {0,…,n}\{0, \dots, n\} has positive probability for any p∈(0,1)p \in (0, 1), and posterior mean is unique for each xx: rules δa,b\delta_{a, b} with a,b>0a, b > 0 are unique Bayes rules and thus admissible. MLE X/nX/n is also admissible, by a useful trick. Under weighted loss (a−p)2/(p(1−p))(a - p)^2/(p(1 - p)) and uniform prior, point 4 of the posterior-mean theorem gives E[p/(p(1−p))∣x]/E[1/(p(1−p))∣x]\E[p/(p(1-p)) \given x] / \E[1/(p(1-p)) \given x], exactly x/nx/n with posterior Beta(x+1,n−x+1)\mathrm{Beta}(x + 1, n - x + 1) for 1≤x≤n−11 \le x \le n - 1 (also at x=0x = 0 and x=nx = n, checked separately). Thus X/nX/n is the unique Bayes rule for that loss and admissible under it. Since weighted risk is R(p,δ)/(p(1−p))R(p, \delta)/(p(1 - p)) with the same positive factor for every rule, removing it does not change dominance: X/nX/n is also admissible under squared loss.

One normal mean: admissible in dimension 1

Turn to the model used in the rest of the lesson, X∼N(μ,1)X \sim \Normal(\mu, 1) with μ∈R\mu \in \R. Estimator XX 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 δ\delta dominates XX: R(μ,δ)≤1R(\mu, \delta) \le 1 for every μ\mu and R(μ0,δ)<1R(\mu_0, \delta) < 1 at some μ0\mu_0. In the normal family risks are continuous in μ\mu, so some ε,η>0\eps, \eta > 0 satisfy R(μ,δ)≤1−εR(\mu, \delta) \le 1 - \eps when ∣μ−μ0∣<η\abs{\mu - \mu_0} < \eta. Take prior πτ=N(0,τ2)\pi_\tau = \Normal(0, \tau^2). By the normal-normal example its Bayes rule has Bayes risk τ2/(1+τ2)\tau^2/(1 + \tau^2), and Bayes optimality gives

τ21+τ2≤r(πτ,δ)≤1−ε πτ(∣μ−μ0∣<η).\frac{\tau^2}{1 + \tau^2} \le r(\pi_\tau, \delta) \le 1 - \eps\,\pi_\tau\big(\abs{\mu - \mu_0} < \eta\big).

Rearranging, ε πτ(∣μ−μ0∣<η)≤1/(1+τ2)\eps\,\pi_\tau(\abs{\mu - \mu_0} < \eta) \le 1/(1 + \tau^2). But probability on the left is at least 2η⋅1τφ((∣μ0∣+η)/τ)∼2η/(2π τ)2\eta \cdot \frac{1}{\tau}\varphi\big((\abs{\mu_0} + \eta)/\tau\big) \sim 2\eta/(\sqrt{2\pi}\,\tau), decaying as 1/τ1/\tau, while right side decays as 1/τ21/\tau^2. Multiply by τ\tau and let τ→∞\tau \to \infty: left tends to 2εη/2π>02\eps\eta/\sqrt{2\pi} > 0, right to 0. Contradiction.

∎

Repeat in dimension pp with X∼Np(μ,I)X \sim \Normal_p(\vb{\mu}, \mat{I}) and prior Np(0,τ2I)\Normal_p(\vb{0}, \tau^2\mat{I}). The gap between XX risk and Bayes-rule risk is now p/(1+τ2)p/(1 + \tau^2), order τ−2\tau^{-2}, while a fixed ball’s prior probability is order τ−p\tau^{-p}. At p=1p = 1 probability wins and yields contradiction. At p=2p = 2 they tie and the argument is inconclusive (Stein proved XX remains admissible in 1956 with finer priors). At p≥3p \ge 3 the gap wins decisively and the argument says nothing. This is not a proof weakness: at p≥3p \ge 3, XX 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 θ\theta 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 δ\delta, supremum exceeds any weighted average:

sup⁡θR(θ,δ)≥∫R(θ,δ) π( ⁣dθ)=r(π,δ)≥r(π,δπ)≥sup⁡θR(θ,δπ).\sup_\theta R(\theta, \delta) \ge \int R(\theta, \delta) \, \pi(\dd\theta) = r(\pi, \delta) \ge r(\pi, \delta_\pi) \ge \sup_\theta R(\theta, \delta_\pi).

The second inequality uses Bayes optimality of δπ\delta_\pi, the third the hypothesis. For any other prior π′\pi', r(π′,δπ′)≤r(π′,δπ)≤sup⁡θR(θ,δπ)=r(π,δπ)r(\pi', \delta_{\pi'}) \le r(\pi', \delta_\pi) \le \sup_\theta R(\theta, \delta_\pi) = r(\pi, \delta_\pi), so π\pi is least favorable. If δ\delta were another minimax rule, the whole chain would be equalities, r(π,δ)=r(π,δπ)r(\pi, \delta) = r(\pi, \delta_\pi), making δ\delta Bayes and hence equal to δπ\delta_\pi by uniqueness.

∎

In the binomial example, find a,ba, b making the numerator of R(p,δa,b)R(p, \delta_{a, b}) constant:

np(1−p)+(a−(a+b)p)2=a2+(n−2a(a+b))p+((a+b)2−n)p2.np(1 - p) + \big(a - (a + b)p\big)^2 = a^2 + \big(n - 2a(a + b)\big)p + \big((a + b)^2 - n\big)p^2.

Setting the p2p^2 coefficient to zero gives a+b=na + b = \sqrt{n}, and the pp coefficient gives n=2ann = 2a\sqrt{n}, i.e. a=b=n/2a = b = \sqrt{n}/2. The Bayes rule under prior Beta(n/2,n/2)\mathrm{Beta}(\sqrt{n}/2, \sqrt{n}/2) is

δ∗(X)=X+n/2n+n,R(p,δ∗)=n/4(n+n)2=14(1+n)2,\delta^*(X) = \frac{X + \sqrt{n}/2}{n + \sqrt{n}}, \qquad R(p, \delta^*) = \frac{n/4}{(n + \sqrt{n})^2} = \frac{1}{4(1 + \sqrt{n})^2},

constant, hence minimax (unique because the Bayes rule is unique), and prior Beta(n/2,n/2)\mathrm{Beta}(\sqrt{n}/2, \sqrt{n}/2) is least favorable: it concentrates mass around 1/21/2, hardest to estimate. At n=16n = 16, maximum risk drops from 1/64=0.01561/64 = 0.0156 (MLE) to 0.010.01. But minimax beats MLE only when p(1−p)/16>0.01p(1 - p)/16 > 0.01, i.e. p∈(0.2,0.8)p \in (0.2, 0.8); outside this band it loses, badly near endpoints. As nn grows, maximum-risk ratio tends to 1 and minimax’s winning band narrows toward 1/21/2. 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 δ′\delta' and every kk, sup⁡θR(θ,δ′)≥r(πk,δ′)≥r(πk,δk)\sup_\theta R(\theta, \delta') \ge r(\pi_k, \delta') \ge r(\pi_k, \delta_k). Taking limits gives sup⁡θR(θ,δ′)≥sup⁡θR(θ,δ)\sup_\theta R(\theta, \delta') \ge \sup_\theta R(\theta, \delta).

∎

With X∼Np(μ,σ2I)X \sim \Normal_p(\vb{\mu}, \sigma^2\mat{I}), risk of XX is pσ2p\sigma^2 and priors Np(0,kI)\Normal_p(\vb{0}, k\mat{I}) have optimal Bayes risk pσ2k/(σ2+k)→pσ2p\sigma^2 k/(\sigma^2 + k) \to p\sigma^2. Thus XX is minimax in every dimension. Any rule dominating XX 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, X∼Np(μ,σ2I)\vb{X} \sim \Normal_p(\vb{\mu}, \sigma^2\mat{I}) with known σ2\sigma^2: pp means estimated at once, each with one noisy independent observation (or a mean of several, equivalent with another σ2\sigma^2). This is a multivariate Gaussian with diagonal covariance. Loss is total squared loss ∥δ−μ∥2=∑i(δi−μi)2\norm{\vb{\delta} - \vb{\mu}}^2 = \sum_i (\delta_i - \mu_i)^2, and risk of X\vb{X} is pσ2p\sigma^2. We seek estimators δ(X)=X+g(X)\vb{\delta}(\vb{X}) = \vb{X} + \vb{g}(\vb{X}) and must compute risk without knowing μ\vb{\mu}. The tool is Gaussian integration by parts, familiar as Stein’s lemma.

Proof

Let φ\varphi be the density of ZZ. The key identity is ∫t∞(z−μ)φ(z) ⁣dz=σ2φ(t)\int_t^\infty (z - \mu)\varphi(z) \dd z = \sigma^2\varphi(t), from differentiating:  ⁣d ⁣dtσ2φ(t)=−(t−μ)φ(t)\frac{\dd}{\dd t}\sigma^2\varphi(t) = -(t - \mu)\varphi(t) and φ(∞)=0\varphi(\infty) = 0. Likewise, ∫−∞t(z−μ)φ(z) ⁣dz=−σ2φ(t)\int_{-\infty}^t (z - \mu)\varphi(z) \dd z = -\sigma^2\varphi(t). Since ∫(z−μ)φ(z) ⁣dz=0\int (z - \mu)\varphi(z) \dd z = 0, subtract g(μ)g(\mu):

E[(Z−μ)g(Z)]=∫μ∞(z−μ)φ(z)(g(z)−g(μ)) ⁣dz+∫−∞μ(z−μ)φ(z)(g(z)−g(μ)) ⁣dz.\E[(Z - \mu)g(Z)] = \int_\mu^\infty (z - \mu)\varphi(z)\big(g(z) - g(\mu)\big) \dd z + \int_{-\infty}^\mu (z - \mu)\varphi(z)\big(g(z) - g(\mu)\big) \dd z.

In the first term write g(z)−g(μ)=∫μzg′(t) ⁣dtg(z) - g(\mu) = \int_\mu^z g'(t) \dd t and exchange integration order, justified by Fubini because ∫μ∞∣g′(t)∣ σ2φ(t) ⁣dt≤σ2E∣g′(Z)∣<∞\int_\mu^\infty \abs{g'(t)}\,\sigma^2\varphi(t) \dd t \le \sigma^2\E\abs{g'(Z)} < \infty:

∫μ∞g′(t)∫t∞(z−μ)φ(z) ⁣dz ⁣dt=∫μ∞g′(t) σ2φ(t) ⁣dt.\int_\mu^\infty g'(t) \int_t^\infty (z - \mu)\varphi(z) \dd z \dd t = \int_\mu^\infty g'(t)\,\sigma^2\varphi(t) \dd t.

The second term similarly gives ∫−∞μg′(t) σ2φ(t) ⁣dt\int_{-\infty}^\mu g'(t)\,\sigma^2\varphi(t) \dd t. Adding yields σ2E[g′(Z)]\sigma^2\E[g'(Z)].

∎

This is integration by parts of gg against φ\varphi, with φ′=−(z−μ)φ/σ2\varphi' = -(z - \mu)\varphi/\sigma^2, written without assuming behavior of gg at infinity: E∣g′(Z)∣<∞\E\abs{g'(Z)} < \infty suffices. Applied coordinatewise (conditioning on the independent remaining coordinates), it gives the multivariate version: if each gig_i is absolutely continuous in xix_i for almost all other coordinates and E∣∂igi(X)∣<∞\E\abs{\partial_i g_i(\vb{X})} < \infty, then E[(Xi−μi)gi(X)]=σ2E[∂igi(X)]\E[(X_i - \mu_i)g_i(\vb{X})] = \sigma^2\E[\partial_i g_i(\vb{X})].

Proof

Expand ∥X+g−μ∥2=∥X−μ∥2+2∑i(Xi−μi)gi(X)+∥g∥2\norm{\vb{X} + \vb{g} - \vb{\mu}}^2 = \norm{\vb{X} - \vb{\mu}}^2 + 2\sum_i (X_i - \mu_i)g_i(\vb{X}) + \norm{\vb{g}}^2 and take expectations. The first term is pσ2p\sigma^2 and Stein’s lemma turns the second into 2σ2E[∇⋅g]2\sigma^2\E[\nabla\cdot\vb{g}].

∎

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 λ\lambda 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 X\vb{X} toward zero more strongly when closer to zero: g(x)=−c x/∥x∥2\vb{g}(\vb{x}) = -c\,\vb{x}/\norm{\vb{x}}^2.

Proof

With c=(p−2)σ2c = (p - 2)\sigma^2 and g(x)=−c x/∥x∥2\vb{g}(\vb{x}) = -c\,\vb{x}/\norm{\vb{x}}^2, calculate both SURE pieces. Each coordinate derivative is

∂∂xi(xi∥x∥2)=1∥x∥2−2xi2∥x∥4,luego∇⋅x∥x∥2=p∥x∥2−2∥x∥2=p−2∥x∥2.\pd{}{x_i}\Big(\frac{x_i}{\norm{\vb{x}}^2}\Big) = \frac{1}{\norm{\vb{x}}^2} - \frac{2x_i^2}{\norm{\vb{x}}^4}, \qquad \text{luego} \qquad \nabla\cdot\frac{\vb{x}}{\norm{\vb{x}}^2} = \frac{p}{\norm{\vb{x}}^2} - \frac{2}{\norm{\vb{x}}^2} = \frac{p - 2}{\norm{\vb{x}}^2}.

Thus ∇⋅g=−c(p−2)/∥x∥2\nabla\cdot\vb{g} = -c(p - 2)/\norm{\vb{x}}^2 and ∥g∥2=c2/∥x∥2\norm{\vb{g}}^2 = c^2/\norm{\vb{x}}^2, and

SURE⁡(X)=pσ2+c2−2σ2c(p−2)∥X∥2=pσ2−(p−2)2σ4∥X∥2.\operatorname{SURE}(\vb{X}) = p\sigma^2 + \frac{c^2 - 2\sigma^2 c(p - 2)}{\norm{\vb{X}}^2} = p\sigma^2 - \frac{(p - 2)^2\sigma^4}{\norm{\vb{X}}^2}.

It remains to justify lemma assumptions. g\vb{g} is smooth except at zero, where ∣g∣∼1/∥x∥\abs{\vb{g}} \sim 1/\norm{\vb{x}} and derivatives ∼1/∥x∥2\sim 1/\norm{\vb{x}}^2. In polar coordinates, ∫∥x∥<1∥x∥−2 ⁣dx∝∫01r−2rp−1 ⁣dr\int_{\norm{\vb{x}} < 1} \norm{\vb{x}}^{-2} \dd\vb{x} \propto \int_0^1 r^{-2}r^{p-1} \dd r, finite exactly when p≥3p \ge 3. Thus for p≥3p \ge 3, E[1/∥X∥2]<∞\E[1/\norm{\vb{X}}^2] < \infty (Gaussian density is bounded) and all lemma expectations are finite; absolute continuity in each coordinate fails only on a null set. Since 1/∥X∥2>01/\norm{\vb{X}}^2 > 0, the subtracted term is strictly positive.

∎

The proof also explains dimension. At p≤2p \le 2, E[1/∥X∥2]=∞\E[1/\norm{\vb{X}}^2] = \infty and coefficient p−2p - 2 is not positive: at p=1p = 1 the formula gives X+σ2/XX + \sigma^2/X, “shrinkage” that expands and has infinite risk. The 2 in p−2p - 2 appears in the divergence of x/∥x∥2\vb{x}/\norm{\vb{x}}^2, 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 ∥X∥2/σ2\norm{\vb{X}}^2/\sigma^2, noncentral χp2\chi^2_p with parameter λ=∥μ∥2/σ2\lambda = \norm{\vb{\mu}}^2/\sigma^2, a mixture of central χp+2K2\chi^2_{p + 2K} with K∼Pois⁡(λ/2)K \sim \Pois(\lambda/2). Since E[1/χm2]=1/(m−2)\E[1/\chi^2_m] = 1/(m - 2),

R(μ,δJS)=pσ2−(p−2)2σ2 E[1p−2+2K],K∼Pois⁡(∥μ∥2/(2σ2)).R(\vb{\mu}, \vb{\delta}^{\mathrm{JS}}) = p\sigma^2 - (p - 2)^2\sigma^2\,\E\Big[\frac{1}{p - 2 + 2K}\Big], \qquad K \sim \Pois\big(\norm{\vb{\mu}}^2/(2\sigma^2)\big).

Three readings:

  • At μ=0\vb{\mu} = \vb{0} risk is 2σ22\sigma^2 for any pp. With p=10p = 10, estimator’s average total error is 2σ22\sigma^2 versus 10σ210\sigma^2: five times smaller.
  • Far from zero the gain fades. By Jensen’s inequality, E[1/∥X∥2]≥1/E∥X∥2=1/(∥μ∥2+pσ2)\E[1/\norm{\vb{X}}^2] \ge 1/\E\norm{\vb{X}}^2 = 1/(\norm{\vb{\mu}}^2 + p\sigma^2), so R≤pσ2−(p−2)2σ4/(∥μ∥2+pσ2)R \le p\sigma^2 - (p - 2)^2\sigma^4/(\norm{\vb{\mu}}^2 + p\sigma^2). Gain is large when ∥μ∥2\norm{\vb{\mu}}^2 is comparable to or below pσ2p\sigma^2, and tends to 0 (never vanishing) as ∥μ∥→∞\norm{\vb{\mu}} \to \infty.
  • The origin is not special. Applying the theorem to X−ν\vb{X} - \vb{\nu}, estimator ν+(1−(p−2)σ2/∥X−ν∥2)(X−ν)\vb{\nu} + \big(1 - (p - 2)\sigma^2/\norm{\vb{X} - \vb{\nu}}^2\big)(\vb{X} - \vb{\nu}) dominates X\vb{X} for any preselected point ν\vb{\nu}. Gain depends on ∥μ−ν∥\norm{\vb{\mu} - \vb{\nu}}: a good point helps, a bad one does not hurt.
InteractiveStein's paradox live
Each row is a component ii, ordered by μi\mu_i
  • true mean μi\mu_i
  • observation XiX_i
  • James–Stein approaches μi\mu_i
  • moves away
Total risk versus distance ∥μ−ν∥\|\mu - \nu\| (with σ=1\sigma = 1)
  • risk of XX: pp
  • exact James–Stein risk
  • losses in this realization (open) and risk estimated with 1000 (filled)
10
1.00
0.80
0.00
New realization
Common shrinkage factor0.753
Loss of XX, ∥X−μ∥2\|X - \mu\|^27.82
James–Stein loss3.82
Components that worsen2 of 10
JS risk (1000 reps)7.29 < 10
James–Stein wins in83.5 %
James–Stein wins overall although 2 of 10 components worsen (red arrows).
Each row is one component: ring is true mean μi\mu_i, blue point observation Xi∼N(μi,1)X_i \sim \Normal(\mu_i, 1), arrow leads to James–Stein estimate, aqua if closer to μi\mu_i and red if farther. True means are μi=m+τzi\mu_i = m + \tau z_i. Below: exact James–Stein risk versus XX risk pp as a function of ∥μ−ν∥\norm{\vb{\mu} - \vb{\nu}}; hollow points are this realization's losses and filled point James–Stein risk estimated over 1000 repetitions with the same μi\mu_i. Press 'New noise' several times: red arrows almost always appear and James–Stein sometimes loses in total, but the filled point remains below line pp. Drag ν\nu far from means and see gain shrink without disappearing; reduce pp to 2 and 1.

What the paradox does not say

James–Stein improves total error, not each component’s. For a particular coordinate its risk can greatly exceed σ2\sigma^2: with p=10p = 10, σ=1\sigma = 1 and μ=(4,0,…,0)\vb{\mu} = (4, 0, \dots, 0), first-coordinate risk is about 2.92.9 versus 11 for XX, while total risk is about 7.27.2 versus 1010. 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 μ\vb{\mu}: 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: ∥X∥2\norm{\vb{X}}^2 has mean ∥μ∥2+pσ2\norm{\vb{\mu}}^2 + p\sigma^2, so X\vb{X} is systematically too long, and at p≥3p \ge 3 there is enough information in ∥X∥2\norm{\vb{X}}^2 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 ∥X∥2<(p−2)σ2\norm{\vb{X}}^2 < (p - 2)\sigma^2, James–Stein’s factor is negative and the estimator reverses X\vb{X}‘s sign: absurd. The positive-part version truncates it at zero,

δJS+(X)=(1−(p−2)σ2∥X∥2)+X,\vb{\delta}^{\mathrm{JS}+}(\vb{X}) = \Big(1 - \frac{(p - 2)\sigma^2}{\norm{\vb{X}}^2}\Big)_+\vb{X},

and dominates δJS\vb{\delta}^{\mathrm{JS}} (Baranchik, 1964). Write δJS=hX\vb{\delta}^{\mathrm{JS}} = h\vb{X} with h=h(∥X∥)h = h(\norm{\vb{X}}) and δJS+=h+X\vb{\delta}^{\mathrm{JS}+} = h_+\vb{X}. Losses differ only when h<0h < 0, where

∥hX−μ∥2−∥μ∥2=h2∥X∥2+2∣h∣ μ⊤X.\norm{h\vb{X} - \vb{\mu}}^2 - \norm{\vb{\mu}}^2 = h^2\norm{\vb{X}}^2 + 2\abs{h}\,\vb{\mu}\T\vb{X}.

The first term is positive, and expectation of the second conditional on ∥X∥\norm{\vb{X}} is nonnegative: on each sphere, X\vb{X} density is proportional to eμ⊤x/σ2e^{\vb{\mu}\T\vb{x}/\sigma^2} and favors points with μ⊤x>0\vb{\mu}\T\vb{x} > 0. 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 Xˉ=1p∑iXi\bar{X} = \frac1p\sum_i X_i, not fixed in advance. Estimator

δi=Xˉ+(1−(p−3)σ2∑j(Xj−Xˉ)2)(Xi−Xˉ)\delta_i = \bar{X} + \Big(1 - \frac{(p - 3)\sigma^2}{\sum_j (X_j - \bar{X})^2}\Big)(X_i - \bar{X})

dominates X\vb{X} if p≥4p \ge 4. Proof is change of basis: decompose Rp\R^p into the line of 1\vb{1} and its orthogonal complement of dimension p−1p - 1. Leave the component on 1\vb{1} unchanged (Xˉ1\bar{X}\vb{1}) and apply James–Stein in dimension p−1p - 1 to orthogonal component X−Xˉ1\vb{X} - \bar{X}\vb{1}, giving constant (p−1)−2=p−3(p - 1) - 2 = p - 3. Estimating the center costs one degree of freedom.

Empirical Bayes: James–Stein as prior estimation

Return to normal-normal, now with pp units:

μi∼iidN(ν,τ2),Xi∣μi∼N(μi,σ2) independientes.\mu_i \iid \Normal(\nu, \tau^2), \qquad X_i \given \mu_i \sim \Normal(\mu_i, \sigma^2) \text{ independientes}.

If ν\nu and τ2\tau^2 were known, Bayes rule would be μ^i=ν+(1−B)(Xi−ν)\hat\mu_i = \nu + (1 - B)(X_i - \nu) with B=σ2/(σ2+τ2)B = \sigma^2/(\sigma^2 + \tau^2), Bayes risk pσ2(1−B)p\sigma^2(1 - B). They are not. But we have pp observations of the marginal distribution: since Xi=μi+εiX_i = \mu_i + \eps_i sums independent normals (an affine transformation of a Gaussian vector), marginally Xi∼iidN(ν,σ2+τ2)X_i \iid \Normal(\nu, \sigma^2 + \tau^2). With known ν=0\nu = 0, S=∥X∥2∼(σ2+τ2)χp2S = \norm{\vb{X}}^2 \sim (\sigma^2 + \tau^2)\chi^2_p, and since E[1/χp2]=1/(p−2)\E[1/\chi^2_p] = 1/(p - 2),

E[(p−2)σ2∥X∥2]=(p−2)σ2(σ2+τ2)(p−2)=B.\E\Big[\frac{(p - 2)\sigma^2}{\norm{\vb{X}}^2}\Big] = \frac{(p - 2)\sigma^2}{(\sigma^2 + \tau^2)(p - 2)} = B.

James–Stein is the Bayes rule replacing BB by an unbiased estimate of BB 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 τ2\tau^2 is exact. Under the hierarchical model James–Stein Bayes risk is E[pσ2−(p−2)2σ4/S]=pσ2−(p−2)σ2B\E[p\sigma^2 - (p - 2)^2\sigma^4/S] = p\sigma^2 - (p - 2)\sigma^2 B, i.e.

r(π,δJS)=pσ2(1−B)⏟Bayes con τ2 conocido+2σ2B.r(\pi, \vb{\delta}^{\mathrm{JS}}) = \underbrace{p\sigma^2(1 - B)}_{\text{Bayes con } \tau^2 \text{ conocido}} + 2\sigma^2 B.

Extra cost is at most 2σ22\sigma^2 in total, independent of pp: with many units empirical Bayes is nearly as good as Bayes knowing the prior. It also retains a guarantee pure Bayes lacks: it dominates X\vb{X} even if the normal prior is false, because James–Stein holds for each fixed μ\vb{\mu}.

Two generalizations matter in real problems:

  • Unequal variances. If Xi∼N(μi,σi2)X_i \sim \Normal(\mu_i, \sigma_i^2), e.g. group ii has nin_i observations and σi2=s2/ni\sigma_i^2 = s^2/n_i, Bayes shrinks each unit by its own Bi=σi2/(σi2+τ2)B_i = \sigma_i^2/(\sigma_i^2 + \tau^2): small groups shrink more. Estimate ν\nu and τ2\tau^2 by maximizing marginal likelihood ∑ilog⁡N(Xi;ν,σi2+τ2)\sum_i \log \Normal(X_i; \nu, \sigma_i^2 + \tau^2). 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 (xi+a)/(ni+a+b)(x_i + a)/(n_i + a + b), with a,ba, b estimated by beta-binomial marginal maximum likelihood. The same shrinkage, with factor (a+b)/(ni+a+b)(a + b)/(n_i + a + b) 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 yiy_i be the first-45 average. Under a normal approximation, yi≈N(pi,σ2)y_i \approx \Normal(p_i, \sigma^2) and σ2=yˉ(1−yˉ)/45=0.00433\sigma^2 = \bar{y}(1 - \bar{y})/45 = 0.00433, where yˉ=0.2654\bar{y} = 0.2654 is the mean of the 18. Shrinking to grand mean (constant k−3=15k - 3 = 15 with k=18k = 18),

p^i=yˉ+c (yi−yˉ),c=1−15 σ2∑j(yj−yˉ)2=1−15⋅0.004330.0824=0.212.\hat{p}_i = \bar{y} + c\,(y_i - \bar{y}), \qquad c = 1 - \frac{15\,\sigma^2}{\sum_j (y_j - \bar{y})^2} = 1 - \frac{15 \cdot 0.00433}{0.0824} = 0.212.

Roberto Clemente, 18 hits in 45 at-bats (0.4000.400), moves to 0.265+0.212⋅0.135=0.2940.265 + 0.212 \cdot 0.135 = 0.294; his remaining-season average was 0.3460.346. Total squared error against the remainder drops from 0.07530.0753 (MLE) to 0.02130.0213 (James–Stein), a factor 3.53.5. Sixteen of 18 players improve.

InteractiveEfron and Morris's baseball players
Batting average: first 45 at-bats, forecast and rest of the 1970 season
  • first 45 at-bats yiy_i (MLE)
  • rest of the season
  • forecast better than MLE
  • worse
Total squared error ∑i(yˉ+c (yi−yˉ)−resti)2\sum_i (\bar y + c\,(y_i - \bar y) - \text{rest}_i)^2 versus cc
0.600
Grand mean yˉ\bar{y}.265
Total error with this cc0.0351
MLE error · JS0.0753 · 0.0213
MLE / this cc2.15
Improve · worsen16 · 2
Optimal cc in hindsight0.190
Each row is a player: blue point is first-45 batting average, ring is remaining 1970 season average, and arrow is forecast yˉ+c (yi−yˉ)\bar{y} + c\,(y_i - \bar{y}), aqua if it improves MLE and red if worse. Below: total squared error versus cc. Set cc to 1 (MLE, no arrows) and reduce slowly: error falls as arrows lengthen toward mean line. Press 'James–Stein': the cc estimated using only the first 45 at-bats is near the parabola's minimum, known only after season end. Which two players worsen, and why?

Best hindsight cc is 0.1900.190, error 0.02130.0213: James–Stein, without seeing the rest of the season, chooses 0.2120.212 and lies within 10−410^{-4} of optimum. Even full shrinkage, c=0c = 0 (predict the 18-player mean for all), with error 0.02430.0243, beats MLE: here 45-at-bat noise (σ≈0.066\sigma \approx 0.066) 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 Beta(2,60)\mathrm{Beta}(2, 60) (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, (vRˉ+mC)/(v+m)(v\bar{R} + mC)/(v + m) with vv votes averaging Rˉ\bar{R}, CC grand mean and mm pseudovotes, is exactly a conjugate posterior mean: shrink toward CC with weight m/(v+m)m/(v + m), more with fewer votes. Empirical Bayes chooses mm from data rather than by eye.

Regularization. Ridge is posterior mean (and MAP) in a linear model with Gaussian prior w∼N(0,τ2I)\vb{w} \sim \Normal(\vb{0}, \tau^2\mat{I}); with orthonormal design it shrinks each least-squares coefficient by 1/(1+λ)1/(1 + \lambda), this lesson’s 1−B1 - B. Choosing λ\lambda 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 ν\nu and τ\tau 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 n+1n + 1 possible XX values rather than using closed form, and numerically finds the beta prior minimizing maximum risk.

[ ]Exact risk and binomial minimaxBrowser
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 Beta(2,2)=Beta(16/2,16/2)\mathrm{Beta}(2, 2) = \mathrm{Beta}(\sqrt{16}/2, \sqrt{16}/2) without being told risk must be constant, and maximum risk matches formula 0.010.01. The table reproduces figure numbers: minimax has smallest maximum risk, Laplace smallest Bayes risk under uniform prior (1/(6(n+2))=0.009261/(6(n + 2)) = 0.00926, as expected since it is that prior’s Bayes rule), and constant wins at p=1/2p = 1/2 with zero risk.

Now Stein’s lemma and SURE by Monte Carlo.

[ ]Stein's lemma and SURE by simulationBrowser
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 g(z)=∣z∣g(z) = \abs{z}, 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 (−0.38-0.38). When noise shortens X\vb{X} by chance, ∥X∥2\norm{\vb{X}}^2 is small and SURE predicts low loss, yet James–Stein then shrinks strongly toward an origin far from μ\vb{\mu}, 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.

[ ]James–Stein from scratch: dominance by pBrowser
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 p=2p = 2 factor is exactly 1 and there is no gain. From p=3p = 3, James–Stein wins in risk, and probability of winning one realization grows with pp but never reaches 1: dominance concerns averages. At μ=0\vb{\mu} = \vb{0} risk is 2 in every dimension (at p=3p = 3 simulation is noisier because 1/∥X∥21/\norm{\vb{X}}^2 has infinite variance for p≤4p \le 4).

The fourth cell addresses the motivation: unequal-variance normal-normal empirical Bayes, estimating ν\nu and τ2\tau^2 by marginal maximum likelihood and validating against next-period data.

[ ]Empirical Bayes for 500 failure ratesBrowser
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 3.50⋅10−43.50\cdot 10^{-4} to 1.53⋅10−41.53\cdot 10^{-4}, 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.

[ ]Efron and Morris's baseball playersBrowser
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.

[ ]Empirical beta-binomial and Ledoit–WolfBrowser
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 (xi+a)/(ni+a+b)(x_i + a)/(n_i + a + b) shows each service shrinks with weight (a+b)/(ni+a+b)(a + b)/(n_i + a + b): 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

ProofThe squared-loss Bayes rule is posterior mean
Prove: If E[θ2∣x]<∞\E[\theta^2 \given x] < \infty, the action minimizing posterior expected loss ρ(a∣x)=E[(θ−a)2∣x]\rho(a \given x) = \E[(\theta - a)^2 \given x] is a∗=E[θ∣x]a^* = \E[\theta \given x], uniquely.
0
Fix xx and write m=E[θ∣x]m = \E[\theta \given x], finite because E[∣θ∣∣x]≤E[θ2∣x]\E[\abs{\theta} \given x] \le \sqrt{\E[\theta^2 \given x]}.

Step 1 of 4. How decompose ρ(a∣x)\rho(a \given x)?

ProofFrom Stein's lemma to James–Stein dominance
Prove: For Z∼N(μ,σ2)Z \sim \Normal(\mu, \sigma^2) and smooth gg with gφ→0g\varphi \to 0 at ±∞\pm\infty and E∣g′(Z)∣<∞\E\abs{g'(Z)} < \infty, E[(Z−μ)g(Z)]=σ2E[g′(Z)]\E[(Z - \mu)g(Z)] = \sigma^2\E[g'(Z)]; hence if p≥3p \ge 3, estimator (1−(p−2)σ2/∥X∥2)X(1 - (p - 2)\sigma^2/\norm{\vb{X}}^2)\vb{X} has risk below pσ2p\sigma^2 for every μ\vb{\mu}.
0
Let φ\varphi be the density of N(μ,σ2)\Normal(\mu, \sigma^2).

Step 1 of 4. What property of φ\varphi enables integration by parts?

NumericRisk of binomial minimax
With X∼Bin⁡(16,p)X \sim \Bin(16, p), what is the constant squared risk of minimax estimator (X+n/2)/(n+n)(X + \sqrt{n}/2)/(n + \sqrt{n})?
NumericBayes rule for absolute loss
Observe x=3x = 3 successes in n=10n = 10 trials and use uniform prior for pp. What is the Bayes estimate under absolute loss ∣a−p∣\abs{a - p}? (You may use scipy.stats.beta.)
NumericJames–Stein risk at the origin
With X∼N10(μ,I)\vb{X} \sim \Normal_{10}(\vb{\mu}, \mat{I}) and μ=0\vb{\mu} = \vb{0}, what is total squared risk of the James–Stein estimator (toward zero, without positive part)?
NumericShrinking Clemente
In the baseball example, yˉ=0.2654\bar{y} = 0.2654 and James–Stein factor is c=0.2117c = 0.2117. Clemente batted 0.4000.400 in his first 45 at-bats. What is his James–Stein forecast?
QuizWhat the paradox does and does not say
Which statements are correct?

More than one answer may be correct.

QuizBayes, minimax and admissible
With X∼Np(μ,I)\vb{X} \sim \Normal_p(\vb{\mu}, \mat{I}) and total squared loss, which are true?

More than one answer may be correct.

QuizWho shrinks more?
With beta-binomial empirical Bayes, a=2a = 2 and b=62b = 62, service A has 3 failures in 20 requests and B has 300 in 2000. Both have 15% raw rates. What happens to their estimates?
CodePositive-part James–Stein toward the grand mean
Implement js_media_global(x, sigma2=1.0), receiving a length-p≥4p \ge 4 vector x of independent Xi∼N(μi,σ2)X_i \sim \Normal(\mu_i, \sigma^2) and returning δi=xˉ+(1−(p−3)σ2/S)+(xi−xˉ)\delta_i = \bar{x} + \big(1 - (p - 3)\sigma^2/S\big)_+(x_i - \bar{x}), where xˉ\bar{x} is the mean of x and S=∑j(xj−xˉ)2S = \sum_j (x_j - \bar{x})^2. Return a float array of the same shape. Tests check specific values, truncation, translation equivariance and that with p=10p = 10 simulated risk is clearly below that of XX.
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()
Shift+Enter to run

Summary

Key idea
Comparing estimators means comparing risk functions; in dimension 3 or higher the sample mean loses to James–Stein throughout parameter space: shrinking all means toward a common center using a data-estimated factor is empirical Bayes and always reduces total error, though not each unit’s.
  • A decision problem specifies loss L(θ,a)L(\theta, a); risk R(θ,δ)=EθL(θ,δ(X))R(\theta, \delta) = \E_\theta L(\theta, \delta(X)) is a function of θ\theta, and except in trivial cases no rule minimizes risk at every θ\theta 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 (X+n/2)/(n+n)(X + \sqrt{n}/2)/(n + \sqrt{n}), risk 1/(4(1+n)2)1/(4(1 + \sqrt{n})^2), beats MLE only near p=1/2p = 1/2. X\vb{X} is minimax for a normal mean in every dimension.
  • Stein’s lemma E[(Z−μ)g(Z)]=σ2E[g′(Z)]\E[(Z - \mu)g(Z)] = \sigma^2\E[g'(Z)] yields unbiased risk estimator SURE. James–Stein has risk pσ2−(p−2)2σ4E[1/∥X∥2]<pσ2p\sigma^2 - (p - 2)^2\sigma^4\E[1/\norm{\vb{X}}^2] < p\sigma^2 for p≥3p \ge 3; positive part improves it and grand-mean shrinkage requires p≥4p \ge 4.
  • James–Stein is the normal-normal Bayes rule with factor B=σ2/(σ2+τ2)B = \sigma^2/(\sigma^2 + \tau^2) estimated unbiasedly from data. With unequal variances each group has its own BiB_i, shrinking more when smaller. Ridge, Ledoit–Wolf and hierarchical models share this idea.