Algorithm Search⌘K

Algorithmadvanced

James-Stein estimator

Also called Stein shrinkage estimator, Stein's paradox.

Shrinks the sample means of three or more normal means toward zero by a data-driven factor. It has lower total squared error than the sample means for every parameter value.

Time
Θ(p) worst · best
Space
Θ(p) extra
Where
p = the number of means
Properties
deterministicexactofflineiterative
Origin
Charles Stein, Willard James, 1961

The James-Stein estimator estimates p≥3p \ge 3 normal means at once. It takes the vector of observations XX and multiplies it by the factor 1−(p−2)σ2/∥X∥21 - (p-2)\sigma^2/\lVert X \rVert^2, which pulls every coordinate toward zero, more strongly when ∥X∥\lVert X \rVert is small. Its expected total squared error is smaller than that of XX itself for every value of the true means, so the obvious estimator XX, which is unbiased, minimax and the maximum likelihood estimator, is inadmissible. Stein (1956) proved that XX can be beaten, and James and Stein (1961) gave the estimator. The fact that combining unrelated estimation problems helps is called Stein's paradox. The computation is one pass over the data, Θ(p)\Theta(p) time.

In plain words

Suppose you measure several unrelated quantities, each with the same amount of normal noise, and you care about the total squared error. The natural answer is to report each measurement as it is. Stein found that, with three or more quantities, you can do better on average by pulling all the measurements part of the way toward zero, or toward any fixed point chosen in advance. How far to pull is decided by the data: if the measurements are close to the point, they are mostly noise and you pull hard; if they are far away, you pull little. The total error goes down for every possible truth, but the error of a single quantity can go up.

The problem

Input. One observation x∈Rpx \in \mathbb R^p of X∼Np(θ,σ2Ip)X \sim N_p(\theta, \sigma^2 I_p), with p≥3p \ge 3 and a known σ2>0\sigma^2 > 0, and optionally a target m∈Rpm \in \mathbb R^p fixed before seeing the data (default m=0m = 0). In practice XiX_i is often the mean of nin_i observations of group ii, with σ2\sigma^2 the variance of that mean.

Output. An estimate θ^∈Rp\hat\theta \in \mathbb R^p.

Goal. Small risk under the total squared error loss

L(θ,θ^)=∥θ^−θ∥2=∑i=1p(θ^i−θi)2,R(θ,θ^)=Eθ L(θ,θ^(X)).L(\theta, \hat\theta) = \lVert \hat\theta - \theta \rVert^2 = \sum_{i=1}^p (\hat\theta_i - \theta_i)^2, \qquad R(\theta, \hat\theta) = \mathbb{E}_\theta\, L(\theta, \hat\theta(X)).

The estimator θ^=X\hat\theta = X has risk pσ2p\sigma^2 for every θ\theta (see statistical decision theory).

The algorithm

  1. JAMES-STEIN(x, σ², m, positive) ▷ x, m ∈ ℝᵖ with p ≥ 3; σ² > 0
  2. 1p ← length of x
  3. 2s ← Σᵢ (xᵢ - mᵢ)²
  4. 3if s = 0 then return m
  5. 4k ← (p - 2) σ²
  6. 5if positive and s ≤ k then return m
  7. 6for i ← 1 to p do θ̂ᵢ ← mᵢ + (1 - k/s)(xᵢ - mᵢ)
  8. 7return θ̂

Line L2 measures the squared distance of the data from the target. Line L6 moves each coordinate toward mim_i by the common factor c=1−(p−2)σ2/sc = 1 - (p-2)\sigma^2/s. When s<(p−2)σ2s < (p-2)\sigma^2, the plain factor cc is negative and the estimate jumps past the target to the other side. The positive-part variant (L5, positive true) uses max⁡(c,0)\max(c, 0) and returns the target instead, which is never worse. Line L3 handles s=0s = 0, which has probability zero.

Example

Take p=5p = 5, σ2=1\sigma^2 = 1, m=0m = 0 and x=(2,−1,0.5,1.5,−0.5)x = (2, -1, 0.5, 1.5, -0.5).

  1. L2: s=4+1+0.25+2.25+0.25=7.75s = 4 + 1 + 0.25 + 2.25 + 0.25 = 7.75.
  2. L4: k=3k = 3, so c=1−3/7.75=19/31≈0.6129c = 1 - 3/7.75 = 19/31 \approx 0.6129.
  3. L6: θ^=c x≈(1.2258,−0.6129,0.3065,0.9194,−0.3065)\hat\theta = c\, x \approx (1.2258, -0.6129, 0.3065, 0.9194, -0.3065).

Every coordinate moves 38.7%38.7\% of the way to zero. With xx scaled by 1/41/4, s=0.484<3s = 0.484 < 3: the plain factor is 1−3/0.484≈−5.191 - 3/0.484 \approx -5.19, and the positive-part version returns 00.

Exact risk (from the theorem in Correctness, with σ2=1\sigma^2 = 1; XX itself has risk pp):

∥θ−m∥2\lVert \theta - m \rVert^2 00 11 55 1010 2525 100100
p=3p = 3 2.00002.0000 2.27522.2752 2.74372.7437 2.88432.8843 2.95822.9582 2.98992.9899
p=5p = 5 2.00002.0000 2.52302.5230 3.66133.6613 4.20414.2041 4.65514.6551 4.91094.9109
p=10p = 10 2.00002.0000 2.73782.7378 4.78374.7837 6.20916.2091 7.96407.9640 9.39699.3969

Measured risk. A simulation with random.Random(20240601), p=5p = 5, θ=(λ,0,0,0,0)\theta = (\sqrt\lambda, 0, 0, 0, 0) and 20000 draws for each λ\lambda gave the averages below. The plain column agrees with the exact risk within two standard errors; the positive-part column is only measured.

λ=∥θ∥2\lambda = \lVert \theta \rVert^2 exact plain risk plain, measured positive part, measured XX, measured
00 2.00002.0000 2.010±0.0282.010 \pm 0.028 1.4311.431 5.0515.051
55 3.66133.6613 3.655±0.0183.655 \pm 0.018 3.4983.498 4.9794.979
2525 4.65514.6551 4.687±0.0214.687 \pm 0.021 4.6864.686 5.0325.032

Correctness

With m=0m = 0 and σ2=1\sigma^2 = 1 (the general case follows by a change of variable), the risk is

R(θ,θ^JS)=p−(p−2)2 Eθ[1∥X∥2]<p.R(\theta, \hat\theta^{JS}) = p - (p - 2)^2\, \mathbb{E}_\theta\Big[\frac{1}{\lVert X \rVert^2}\Big] < p.

The proof writes θ^JS=X−g(X)\hat\theta^{JS} = X - g(X) with g(x)=(p−2)x/∥x∥2g(x) = (p-2)x/\lVert x \rVert^2 and uses Stein's identity E[(Xi−θi)gi(X)]=E[∂igi(X)]\mathbb{E}[(X_i - \theta_i) g_i(X)] = \mathbb{E}[\partial_i g_i(X)], which is integration by parts against the normal density. The divergence of gg is (p−2)2/∥x∥2(p-2)^2/\lVert x \rVert^2, and ∥g∥2\lVert g \rVert^2 is the same, which gives the formula. The expectation E[1/∥X∥2]\mathbb{E}[1/\lVert X \rVert^2] is finite only for p≥3p \ge 3, and equals the Poisson mixture ∑ke−λ/2(λ/2)kk!1p−2+2k\sum_k e^{-\lambda/2}\frac{(\lambda/2)^k}{k!}\frac{1}{p - 2 + 2k} with λ=∥θ∥2\lambda = \lVert \theta \rVert^2. At θ=0\theta = 0 it is 1/(p−2)1/(p-2), so the risk is exactly 22 for every p≥3p \ge 3. The risk rises with ∥θ∥\lVert \theta \rVert and tends to pp. The full proof is in proofs/correctness.md. It also shows that p−(p−2)2/∥X∥2p - (p-2)^2/\lVert X \rVert^2 is an unbiased estimate of the risk (Stein's unbiased risk estimate).

What is proved: the risk formula, the domination of XX, and the value 22 at the target. What is only cited and measured: the dominance of the positive-part version over the plain one (Baranchik 1964).

Proof: The James-Stein estimator has risk p - (p - 2)^2 E[1/||X||^2], below p for every thetafull

We use the pseudocode of the page with target m=0m = 0 and σ2=1\sigma^2 = 1; the general case follows by the change of variable Y=(X−m)/σY = (X - m)/\sigma, which maps Np(θ,σ2I)N_p(\theta, \sigma^2 I) to Np((θ−m)/σ,I)N_p((\theta - m)/\sigma, I) and multiplies every squared error by σ2\sigma^2. So let X∼Np(θ,Ip)X \sim N_p(\theta, I_p) with p≥3p \ge 3, and

δ(X)=(1−p−2∥X∥2)X=X−g(X),g(x)=(p−2) x∥x∥2.\delta(X) = \Big(1 - \frac{p-2}{\lVert X \rVert^2}\Big) X = X - g(X), \qquad g(x) = \frac{(p-2)\, x}{\lVert x \rVert^2}.

Claim 0 (the code computes δ\delta). Lines L1 and L2 compute pp and s=∥x−m∥2s = \lVert x - m \rVert^2. Line L3 handles s=0s = 0, an event of probability zero, so it does not change the risk. Line L4 sets k=(p−2)σ2k = (p-2)\sigma^2, and line L6 returns mi+di−k di/s=mi+(1−k/s) dim_i + d_i - k\, d_i / s = m_i + (1 - k/s)\, d_i with d=x−md = x - m, which is δ\delta. Line L5 is used only by the positive-part variant: when s≤ks \le k the factor 1−k/s1 - k/s is at most 00, and the variant returns mm. □\square

Lemma 1 (E[1/∥X∥2]\mathbb{E}[1/\lVert X \rVert^2] is finite). For p≥3p \ge 3, Eθ[1/∥X∥2]≤E0[1/∥X∥2]=1/(p−2)\mathbb{E}_\theta[1/\lVert X \rVert^2] \le \mathbb{E}_0[1/\lVert X \rVert^2] = 1/(p-2).

Proof. Let W=∥X∥2W = \lVert X \rVert^2 and λ=∥θ∥2\lambda = \lVert \theta \rVert^2. For t>0t > 0, the moment generating function of the noncentral chi-squared law gives E e−tW=(1+2t)−p/2exp⁡(−λt/(1+2t))\mathbb{E}\, e^{-tW} = (1 + 2t)^{-p/2} \exp(-\lambda t/(1 + 2t)). Since 1/W=∫0∞e−tW dt1/W = \int_0^\infty e^{-tW}\, dt, Tonelli's theorem gives

E[1/W]=∫0∞(1+2t)−p/2e−λt/(1+2t) dt=∫01wp−3 e−λ(1−w2)/2 dw,\mathbb{E}[1/W] = \int_0^\infty (1 + 2t)^{-p/2} e^{-\lambda t/(1+2t)}\, dt = \int_0^1 w^{p-3}\, e^{-\lambda(1 - w^2)/2}\, dw,

with w=(1+2t)−1/2w = (1 + 2t)^{-1/2}, dt=−w−3 dwdt = -w^{-3}\, dw. The integrand is at most wp−3w^{p-3}, whose integral is 1/(p−2)1/(p-2) for p≥3p \ge 3, with equality when λ=0\lambda = 0. The integrand decreases in λ\lambda, so E[1/W]\mathbb{E}[1/W] decreases in λ\lambda. □\square

Lemma 2 (the Poisson series). E[1/W]=∑k≥0e−λ/2(λ/2)kk!⋅1p−2+2k\mathbb{E}[1/W] = \sum_{k \ge 0} e^{-\lambda/2} \frac{(\lambda/2)^k}{k!} \cdot \frac{1}{p - 2 + 2k}.

Proof. Expand e−λ(1−w2)/2=e−λ/2∑k(λ/2)kw2k/k!e^{-\lambda(1-w^2)/2} = e^{-\lambda/2}\sum_k (\lambda/2)^k w^{2k}/k! in the integral of Lemma 1 and integrate term by term (all terms are nonnegative): ∫01wp−3+2k dw=1/(p−2+2k)\int_0^1 w^{p-3+2k}\, dw = 1/(p - 2 + 2k). □\square

The function inverse_moment_noncentral_chi2 sums this series; the tests compare it with Simpson's rule on the integral of Lemma 1.

Lemma 3 (Stein's identity). Let Z∼N(μ,1)Z \sim N(\mu, 1) and let h:R→Rh : \mathbb R \to \mathbb R be absolutely continuous with E∣h′(Z)∣<∞\mathbb{E}\lvert h'(Z) \rvert < \infty. Then E[(Z−μ)h(Z)]=E[h′(Z)]\mathbb{E}[(Z - \mu) h(Z)] = \mathbb{E}[h'(Z)].

Proof. Let φ\varphi be the standard normal density, so φ′(u)=−uφ(u)\varphi'(u) = -u\varphi(u). Write h(z)=h(μ)+∫μzh′(y) dyh(z) = h(\mu) + \int_\mu^z h'(y)\, dy. Then

E[(Z−μ)h(Z)]=∫−∞∞(z−μ)φ(z−μ)∫μzh′(y) dy dz,\mathbb{E}[(Z - \mu)h(Z)] = \int_{-\infty}^{\infty} (z - \mu)\varphi(z - \mu) \int_\mu^z h'(y)\, dy\, dz,

because E[Z−μ]=0\mathbb{E}[Z - \mu] = 0. For z>μz > \mu swap the order of integration (Fubini, justified by E∣h′(Z)∣<∞\mathbb{E}\lvert h'(Z) \rvert < \infty): ∫μ∞h′(y)∫y∞(z−μ)φ(z−μ) dz dy=∫μ∞h′(y)φ(y−μ) dy\int_\mu^\infty h'(y) \int_y^\infty (z - \mu)\varphi(z - \mu)\, dz\, dy = \int_\mu^\infty h'(y)\varphi(y - \mu)\, dy. The part z<μz < \mu gives ∫−∞μh′(y)φ(y−μ) dy\int_{-\infty}^\mu h'(y)\varphi(y - \mu)\, dy in the same way. The sum is E[h′(Z)]\mathbb{E}[h'(Z)]. □\square

Lemma 4 (the cross term). Eθ[(X−θ)⊤g(X)]=(p−2)2 Eθ[1/∥X∥2]\mathbb{E}_\theta[(X - \theta)^\top g(X)] = (p - 2)^2\, \mathbb{E}_\theta[1/\lVert X \rVert^2].

Proof. Fix ii and condition on the other coordinates X−iX_{-i}. When X−i≠0X_{-i} \ne 0, which has probability 1, the map xi↦gi(x)=(p−2)xi/(xi2+∥x−i∥2)x_i \mapsto g_i(x) = (p-2)x_i/(x_i^2 + \lVert x_{-i} \rVert^2) is smooth and bounded, with

∂igi(x)=(p−2)(1∥x∥2−2xi2∥x∥4),∣∂igi(x)∣≤p−2∥x∥2.\partial_i g_i(x) = (p - 2)\Big(\frac{1}{\lVert x \rVert^2} - \frac{2x_i^2}{\lVert x \rVert^4}\Big), \qquad \lvert \partial_i g_i(x) \rvert \le \frac{p-2}{\lVert x \rVert^2}.

So Lemma 3 applies given X−iX_{-i}, and then E[(Xi−θi)gi(X)]=E[∂igi(X)]\mathbb{E}[(X_i - \theta_i) g_i(X)] = \mathbb{E}[\partial_i g_i(X)]; the expectation is finite by Lemma 1. Summing over ii,

∑i=1p∂igi(x)=(p−2)(p∥x∥2−2∥x∥2)=(p−2)2∥x∥2.□\sum_{i=1}^p \partial_i g_i(x) = (p - 2)\Big(\frac{p}{\lVert x \rVert^2} - \frac{2}{\lVert x \rVert^2}\Big) = \frac{(p-2)^2}{\lVert x \rVert^2}. \qquad \square

Theorem (the risk). For every θ∈Rp\theta \in \mathbb R^p,

R(θ,δ)=Eθ∥δ(X)−θ∥2=p−(p−2)2 Eθ[1∥X∥2]<p=R(θ,X).R(\theta, \delta) = \mathbb{E}_\theta \lVert \delta(X) - \theta \rVert^2 = p - (p - 2)^2\, \mathbb{E}_\theta\Big[\frac{1}{\lVert X \rVert^2}\Big] < p = R(\theta, X).

Proof. Expand ∥X−θ−g(X)∥2\lVert X - \theta - g(X) \rVert^2:

R(θ,δ)=E∥X−θ∥2−2 E[(X−θ)⊤g(X)]+E∥g(X)∥2=p−2(p−2)2 E[1∥X∥2]+(p−2)2 E[1∥X∥2],R(\theta, \delta) = \mathbb{E}\lVert X - \theta \rVert^2 - 2\,\mathbb{E}[(X - \theta)^\top g(X)] + \mathbb{E}\lVert g(X) \rVert^2 = p - 2(p-2)^2\, \mathbb{E}\Big[\frac{1}{\lVert X \rVert^2}\Big] + (p-2)^2\, \mathbb{E}\Big[\frac{1}{\lVert X \rVert^2}\Big],

by Lemma 4 and ∥g(x)∥2=(p−2)2/∥x∥2\lVert g(x) \rVert^2 = (p-2)^2/\lVert x \rVert^2. All three expectations are finite by Lemma 1. The last term of the result is positive because 1/∥X∥2>01/\lVert X \rVert^2 > 0 with probability 1. ■\blacksquare

Corollaries.

  1. At the target. For θ=0\theta = 0, Lemma 1 gives E[1/∥X∥2]=1/(p−2)\mathbb{E}[1/\lVert X \rVert^2] = 1/(p-2), so R(0,δ)=p−(p−2)=2R(0, \delta) = p - (p - 2) = 2 for every p≥3p \ge 3.
  2. Shape. By Lemma 1 the risk depends on θ\theta only through λ=∥θ∥2\lambda = \lVert \theta \rVert^2, increases with λ\lambda, and tends to pp as λ→∞\lambda \to \infty (the integrand of Lemma 1 tends to 00 for w<1w < 1).
  3. Unbiased risk estimate. The proof shows that p−(p−2)2/∥X∥2p - (p-2)^2/\lVert X \rVert^2 has expectation R(θ,δ)R(\theta, \delta) for every θ\theta. This is Stein's unbiased risk estimate for δ\delta; the function stein_unbiased_risk_estimate returns it.
  4. Domination. Since R(θ,X)=pR(\theta, X) = p for every θ\theta, δ\delta dominates XX under total squared error when p≥3p \ge 3, so XX is inadmissible.

What is not proved here. The positive-part variant has risk no larger than the plain estimator at every θ\theta (Baranchik 1964; Lehmann and Casella, Chapter 5); this note does not prove it, and the tests only check it by simulation at three values of θ\theta. Lindley's variant toward the mean has risk 1+Rp−1(∥θ−θˉ1∥2)1 + R_{p-1}(\lVert \theta - \bar\theta \mathbf 1 \rVert^2), where Rp−1R_{p-1} is the plain risk in dimension p−1p - 1; this follows from the theorem applied in the subspace orthogonal to 1\mathbf 1, and the tests check its value 33 at a constant θ\theta by simulation.

Floating point. The code computes ss with math.fsum and forms di/sd_i/s before the multiplication by kk, so a tiny ss gives a large finite or infinite value but never 0⋅∞0 \cdot \infty. The exact risk sums the Poisson series over the terms within 40λ/2+5040\sqrt{\lambda/2} + 50 of the Poisson mean; the omitted mass is far below double precision.

Complexity

One pass computes ss, and a second pass writes the pp outputs: Θ(p)\Theta(p) arithmetic operations, best and worst case. Extra space is Θ(p)\Theta(p): the output, and in the implementation also the differences x−mx - m. The exact risk function in the implementation sums O(λ+1)O(\sqrt{\lambda} + 1) Poisson terms.

Properties

  • Dominates XX for p≥3p \ge 3. The risk is below pσ2p\sigma^2 at every θ\theta, with the largest gain, risk 2σ22\sigma^2 instead of pσ2p\sigma^2, at θ=m\theta = m.
  • Biased. Eθθ^JS≠θ\mathbb{E}_\theta \hat\theta^{JS} \ne \theta for θ≠m\theta \ne m. It does not contradict the Cramér-Rao bound, which concerns unbiased estimators, or the optimality of XX as the minimum variance unbiased estimator.
  • Minimax. XX is minimax with maximum risk pσ2p\sigma^2, and the James-Stein estimator has risk below pσ2p\sigma^2, so it is minimax too.
  • Not admissible. The positive-part estimator dominates it. The positive-part estimator is also inadmissible, but the known estimators that dominate it are complicated and the gain is very small.
  • Depends on the target. The gain is large only when θ\theta is near mm relative to p σ\sqrt p\,\sigma. Far from mm the factor is close to 11 and the estimate is close to XX.
  • Not translation equivariant unless the target moves with the data, as in the variant toward the mean.

Variants and improvements

  • Positive part. θ^JS+=m+max⁡(0,1−(p−2)σ2/∥x−m∥2)(x−m)\hat\theta^{JS+} = m + \max\big(0, 1 - (p-2)\sigma^2/\lVert x - m \rVert^2\big)(x - m). It dominates the plain estimator (Baranchik 1964).
  • Shrinking toward the mean (Lindley). For p≥4p \ge 4, θ^i=xˉ+(1−(p−3)σ2/∑j(xj−xˉ)2)(xi−xˉ)\hat\theta_i = \bar x + \big(1 - (p-3)\sigma^2/\sum_j (x_j - \bar x)^2\big)(x_i - \bar x). The mean direction is not shrunk, so the factor uses p−3p - 3, and the risk is below pσ2p\sigma^2 everywhere and equal to 3σ23\sigma^2 when all θi\theta_i are equal. The implementation has it as james_stein_toward_mean.
  • Unknown variance. If SS is independent of XX with S/σ2∼χν2S/\sigma^2 \sim \chi^2_\nu, the factor 1−(p−2)S/((ν+2)∥X∥2)1 - (p-2)S/((\nu + 2)\lVert X \rVert^2) also dominates XX (James and Stein 1961).
  • Empirical Bayes view. If θi∼N(0,τ2)\theta_i \sim N(0, \tau^2) independently, the Bayes estimator is (1−σ2/(σ2+τ2))X(1 - \sigma^2/(\sigma^2 + \tau^2))X. Marginally ∥X∥2∼(σ2+τ2)χp2\lVert X \rVert^2 \sim (\sigma^2 + \tau^2)\chi^2_p, so (p−2)σ2/∥X∥2(p-2)\sigma^2/\lVert X \rVert^2 is an unbiased estimate of the shrinkage σ2/(σ2+τ2)\sigma^2/(\sigma^2 + \tau^2). The James-Stein estimator is this Bayes rule with the prior variance estimated from the data, which is empirical Bayes (Efron and Morris 1973). A full hierarchical model puts a prior on τ2\tau^2 instead.
  • Regression. Ridge regression shrinks least squares coefficients toward zero with a fixed penalty; in an orthonormal design it multiplies each coefficient by the same factor, like the James-Stein rule with a factor chosen by the user instead of by the data.
  • Unequal variances and general quadratic loss. Versions exist for X∼Np(θ,Σ)X \sim N_p(\theta, \Sigma) and weighted losses; the factor uses Σ\Sigma and the loss matrix (Lehmann and Casella, Chapter 5).

When to use it

Use it when you estimate many similar means with known or well estimated noise levels, and the total error matters more than the error of any single mean: batting averages, small-area rates, test scores of many schools, the effects of many genes. Use the positive-part version, and shrink toward a sensible target, such as the grand mean, so that the gain is large. Do not use it when the error of one particular coordinate matters, when p≤2p \le 2, or when the noise is far from normal or has very different variances without a model for them.

Pitfalls

  • The gain is for the total, not for each coordinate. A single coordinate with an unusual true value can have a larger error than with XX. The coordinates with the most extreme true values usually suffer most. Rules that limit how far each coordinate can move reduce this problem.
  • The target must be fixed before seeing the data. Choosing mm after looking at xx breaks the risk formula. Shrinking toward the data mean is fine only with the p−3p - 3 factor of Lindley's variant.
  • The plain factor can be negative. When ∥x−m∥2<(p−2)σ2\lVert x - m \rVert^2 < (p-2)\sigma^2, the plain estimate is on the other side of the target. Use the positive-part version.
  • σ2\sigma^2 must be right. Using a wrong σ2\sigma^2 changes the factor; if it is too large, the estimator can lose to XX.
  • Confidence statements. The usual intervals Xi±zσX_i \pm z\sigma are not centered at the James-Stein estimate; recentering them without adjustment does not keep the coverage.

Implementations

Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.

james_stein_estimator.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/james-stein-estimator/. The authors are listed in prov/CYEN4M.jsonl.

import math
from typing import Optional, Sequence


def james_stein(
    x: Sequence[float],
    sigma2: float = 1.0,
    target: Optional[Sequence[float]] = None,
    positive_part: bool = False,
) -> list[float]:
    """Return the James-Stein estimate of theta from one draw x of N_p(theta, sigma2 I).

    The estimate is m + c (x - m) with c = 1 - (p - 2) sigma2 / ||x - m||^2,
    where m is the target (zero by default). With positive_part=True, c is
    replaced by max(c, 0). Needs p >= 3 and a known sigma2 > 0. If x equals
    the target (an event of probability zero), the target is returned.
    Cost: Theta(p) time, Theta(p) memory for the result.
    """
    p = len(x)  # @line L1
    if p < 3:
        raise ValueError("the James-Stein estimator needs p >= 3")
    if not sigma2 > 0.0:
        raise ValueError("sigma2 must be positive")
    m = [0.0] * p if target is None else [float(t) for t in target]
    if len(m) != p:
        raise ValueError("target must have the same length as x")
    d = [float(xi) - mi for xi, mi in zip(x, m)]
    s = math.fsum(t * t for t in d)  # @line L2
    if s == 0.0:  # @line L3
        return m
    k = (p - 2) * sigma2  # @line L4
    if positive_part and s <= k:  # @line L5
        return m
    theta = [mi + di - k * (di / s) for mi, di in zip(m, d)]  # @line L6
    return theta  # @line L7


def james_stein_toward_mean(
    x: Sequence[float], sigma2: float = 1.0, positive_part: bool = False
) -> list[float]:
    """Return Lindley's variant, which shrinks x toward its own mean.

    The estimate is xbar + c (x - xbar 1) with
    c = 1 - (p - 3) sigma2 / sum_i (x_i - xbar)^2. Needs p >= 4.
    """
    p = len(x)
    if p < 4:
        raise ValueError("shrinking toward the mean needs p >= 4")
    if not sigma2 > 0.0:
        raise ValueError("sigma2 must be positive")
    xbar = math.fsum(x) / p
    d = [float(xi) - xbar for xi in x]
    s = math.fsum(t * t for t in d)
    k = (p - 3) * sigma2
    if s == 0.0 or (positive_part and s <= k):
        return [xbar] * p
    return [xbar + di - k * (di / s) for di in d]


def stein_unbiased_risk_estimate(
    x: Sequence[float], sigma2: float = 1.0, target: Optional[Sequence[float]] = None
) -> float:
    """Return SURE for the plain James-Stein estimate: sigma2 (p - (p - 2)^2 sigma2 / ||x - m||^2).

    Its expectation under theta is the risk of james_stein at theta.
    """
    p = len(x)
    if p < 3:
        raise ValueError("needs p >= 3")
    m = [0.0] * p if target is None else [float(t) for t in target]
    s = math.fsum((float(xi) - mi) ** 2 for xi, mi in zip(x, m))
    if s == 0.0:
        return -math.inf
    return sigma2 * (p - (p - 2) ** 2 * sigma2 / s)


def inverse_moment_noncentral_chi2(p: int, lam: float) -> float:
    """Return E[1/W] for W ~ noncentral chi-squared with p >= 3 degrees of freedom and noncentrality lam.

    Uses the Poisson mixture: E[1/W] = sum_k Poisson(k; lam/2) / (p - 2 + 2k).
    Only the terms within 40 standard deviations of the Poisson mean are summed.
    """
    if p < 3:
        raise ValueError("E[1/W] is finite only for p >= 3")
    if lam < 0.0:
        raise ValueError("lam must be nonnegative")
    mu = lam / 2.0
    if mu == 0.0:
        return 1.0 / (p - 2)
    width = 40.0 * math.sqrt(mu) + 50.0
    lo = max(0, int(mu - width))
    hi = int(mu + width) + 1
    log_mu = math.log(mu)
    terms = []
    for k in range(lo, hi + 1):
        w = math.exp(-mu + k * log_mu - math.lgamma(k + 1))
        terms.append(w / (p - 2 + 2 * k))
    return math.fsum(terms)


def james_stein_risk(lam: float, p: int, sigma2: float = 1.0) -> float:
    """Return the exact risk E||JS(X) - theta||^2 of the plain James-Stein estimate.

    lam = ||theta - m||^2 is the squared distance from theta to the target.
    The risk is sigma2 (p - (p - 2)^2 E[1/W]) with W ~ chi-squared_p(lam / sigma2).
    """
    return sigma2 * (p - (p - 2) ** 2 * inverse_moment_noncentral_chi2(p, lam / sigma2))
test_james_stein_estimator.py 170 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/james-stein-estimator/. The authors are listed in prov/CYEN4M.jsonl.

import math
import random
from fractions import Fraction as F

import pytest

from james_stein_estimator import (
    inverse_moment_noncentral_chi2,
    james_stein,
    james_stein_risk,
    james_stein_toward_mean,
    stein_unbiased_risk_estimate,
)


def loss(est, theta):
    return math.fsum((a - b) ** 2 for a, b in zip(est, theta))


def simpson_inverse_moment(p, lam, n=4000):
    """E[1/W] = integral over (0, 1) of w^(p-3) exp(-lam (1 - w^2) / 2) dw, by Simpson's rule.

    This follows from E[1/W] = integral over t > 0 of E[exp(-t W)] dt and the
    moment generating function of the noncentral chi-squared law, with the
    change of variable w = (1 + 2t)^(-1/2). It is independent of the Poisson series.
    """
    h = 1.0 / n

    def f(w):
        return w ** (p - 3) * math.exp(-lam * (1.0 - w * w) / 2.0)

    s = f(0.0) + f(1.0)
    for i in range(1, n):
        s += (4 if i % 2 else 2) * f(i * h)
    return s * h / 3.0


def test_page_example():
    x = [2, -1, F(1, 2), F(3, 2), F(-1, 2)]
    s = sum(t * t for t in x)
    assert s == F(31, 4)
    c = 1 - 3 / s
    assert c == F(19, 31)
    got = james_stein([float(t) for t in x])
    for g, t in zip(got, x):
        assert g == pytest.approx(float(c * t), abs=1e-15)


def test_risk_at_zero_is_two_exactly():
    for p in range(3, 12):
        # At theta = 0, ||X||^2 is central chi-squared with p degrees of freedom and E[1/W] = 1/(p - 2).
        exact = p - (p - 2) ** 2 * F(1, p - 2)
        assert exact == 2
        assert james_stein_risk(0.0, p) == pytest.approx(2.0, abs=1e-12)


def test_series_against_quadrature():
    for p in (3, 4, 5, 10):
        for lam in (0.0, 0.5, 5.0, 30.0, 200.0):
            a = inverse_moment_noncentral_chi2(p, lam)
            b = simpson_inverse_moment(p, lam)
            assert a == pytest.approx(b, rel=1e-6)


def test_exact_risk_below_p_and_increasing():
    for p in (3, 5, 10):
        prev = 0.0
        for lam in (0.0, 0.1, 1.0, 5.0, 25.0, 100.0, 1e4):
            r = james_stein_risk(lam, p)
            assert 2.0 - 1e-12 <= r < p
            assert r >= prev
            prev = r
        # For large lam, E[1/W] is close to 1/(p - 2 + lam).
        lam = 1e6
        approx = p - (p - 2) ** 2 / (p - 2 + lam)
        assert james_stein_risk(lam, p) == pytest.approx(approx, rel=1e-6)


def test_sigma2_scaling():
    p = 6
    for lam in (0.0, 3.0, 40.0):
        for s2 in (0.25, 4.0):
            assert james_stein_risk(lam * s2, p, s2) == pytest.approx(s2 * james_stein_risk(lam, p), rel=1e-12)
    x = [1.0, -2.0, 0.5, 3.0, 0.0, -1.5]
    for k in (0.5, 3.0):
        a = james_stein([k * t for t in x], sigma2=k * k * 2.0)
        b = james_stein(x, sigma2=2.0)
        for u, v in zip(a, b):
            assert u == pytest.approx(k * v, rel=1e-12, abs=1e-12)


def test_monte_carlo_risk_matches_exact():
    rng = random.Random(20240601)
    p, n = 5, 20000
    for lam in (0.0, 5.0, 25.0):
        theta = [math.sqrt(lam)] + [0.0] * (p - 1)
        losses = []
        sures = []
        for _ in range(n):
            x = [t + rng.gauss(0.0, 1.0) for t in theta]
            losses.append(loss(james_stein(x), theta))
            sures.append(stein_unbiased_risk_estimate(x))
        exact = james_stein_risk(lam, p)
        for sample in (losses, sures):
            mean = math.fsum(sample) / n
            se = math.sqrt(math.fsum((t - mean) ** 2 for t in sample) / (n - 1) / n)
            assert abs(mean - exact) < 4.0 * se
        assert exact < p


def test_positive_part_beats_plain_in_simulation():
    rng = random.Random(77)
    p, n = 5, 20000
    for lam in (0.0, 2.0, 10.0):
        theta = [math.sqrt(lam / p)] * p
        diffs = []
        for _ in range(n):
            x = [t + rng.gauss(0.0, 1.0) for t in theta]
            diffs.append(loss(james_stein(x), theta) - loss(james_stein(x, positive_part=True), theta))
        mean = math.fsum(diffs) / n
        se = math.sqrt(math.fsum((t - mean) ** 2 for t in diffs) / (n - 1) / n)
        assert mean > -3.0 * se
        if lam == 0.0:
            assert mean > 4.0 * se


def test_toward_mean_risk_three_at_constant_theta():
    rng = random.Random(7)
    p, n = 6, 20000
    theta = [3.0] * p
    losses = [loss(james_stein_toward_mean([t + rng.gauss(0.0, 1.0) for t in theta]), theta) for _ in range(n)]
    mean = math.fsum(losses) / n
    se = math.sqrt(math.fsum((t - mean) ** 2 for t in losses) / (n - 1) / n)
    # The mean direction is not shrunk (risk 1); the other p - 1 directions are plain James-Stein at 0 (risk 2).
    exact = 1.0 + james_stein_risk(0.0, p - 1)
    assert exact == pytest.approx(3.0, abs=1e-12)
    assert abs(mean - exact) < 4.0 * se


def test_target_is_translation_equivariant():
    x = [1.0, 4.0, -2.0, 0.5]
    m = [0.5, 1.0, 1.0, -1.0]
    a = [3.0, -1.0, 2.0, 7.0]
    left = james_stein([u + v for u, v in zip(x, a)], target=[u + v for u, v in zip(m, a)])
    right = [u + v for u, v in zip(james_stein(x, target=m), a)]
    for u, v in zip(left, right):
        assert u == pytest.approx(v, rel=1e-12, abs=1e-12)


def test_edges():
    with pytest.raises(ValueError):
        james_stein([1.0, 2.0])
    with pytest.raises(ValueError):
        james_stein([1.0, 2.0, 3.0], sigma2=0.0)
    with pytest.raises(ValueError):
        james_stein([1.0, 2.0, 3.0], target=[0.0])
    with pytest.raises(ValueError):
        james_stein_toward_mean([1.0, 2.0, 3.0])
    assert james_stein([0.0, 0.0, 0.0]) == [0.0, 0.0, 0.0]
    assert james_stein([1.0, 1.0, 1.0], target=[1.0, 1.0, 1.0]) == [1.0, 1.0, 1.0]
    # ||x||^2 = 0.75 < p - 2 = 1: the plain factor is negative, the positive part gives the target.
    x = [0.5, 0.5, 0.5]
    plain = james_stein(x)
    assert plain[0] == pytest.approx(0.5 * (1.0 - 1.0 / 0.75))
    assert plain[0] < 0.0
    assert james_stein(x, positive_part=True) == [0.0, 0.0, 0.0]
    assert james_stein_toward_mean([2.0, 2.0, 2.0, 2.0]) == [2.0, 2.0, 2.0, 2.0]

History

Stein (1956) showed that for the mean of a pp-dimensional normal distribution under total squared error, XX is admissible when p=1p = 1 or 22 and inadmissible when p≥3p \ge 3. James and Stein (1961) gave the explicit estimator (1−(p−2)/∥X∥2)X(1 - (p-2)/\lVert X \rVert^2)X, computed its risk, and treated an unknown variance. Baranchik (1964) studied the positive-part rule. Efron and Morris (1973) explained the estimator as empirical Bayes, and their later papers made it popular with data examples, such as predicting baseball batting averages.

References

  1. James and Stein 1961, the estimator (1 - (p - 2)/||X||^2) X, its risk, and the version with an estimated variance
  2. Stein 1956, the sample mean is admissible for p = 1 and 2 and inadmissible for p of 3 or more
  3. Bradley Efron and Carl Morris, Stein's estimation rule and its competitors, an empirical Bayes approach, Journal of the American Statistical Association 68(341) (1973), pages 117 to 130, the empirical Bayes derivation and the positive-part rule
  4. Baranchik 1964, the positive-part estimator and its dominance over the James-Stein estimator
  5. E. L. Lehmann and George Casella, Theory of Point Estimation, second edition, Springer, 1998, Chapter 5 (minimaxity and admissibility, shrinkage estimators of a normal mean)
  6. Larry Wasserman, All of Statistics, Springer, 2004, Chapter 12, Section 12.7 (Stein's Paradox)

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.best
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • a scene preset for the example