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
- Model
- Real RAM
- Properties
- deterministicexactofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Charles Stein, Willard James, 1961
The James-Stein estimator estimates normal means at once. It takes the vector of observations and multiplies it by the factor , which pulls every coordinate toward zero, more strongly when is small. Its expected total squared error is smaller than that of itself for every value of the true means, so the obvious estimator , which is unbiased, minimax and the maximum likelihood estimator, is inadmissible. Stein (1956) proved that 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, 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 of , with and a known , and optionally a target fixed before seeing the data (default ). In practice is often the mean of observations of group , with the variance of that mean.
Output. An estimate .
Goal. Small risk under the total squared error loss
The estimator has risk for every (see statistical decision theory).
The algorithm
JAMES-STEIN(x, σ², m, positive) ▷ x, m ∈ ℝᵖ with p ≥ 3; σ² > 0- 1
p ← length of x - 2
s ← Σᵢ (xᵢ - mᵢ)² - 3
if s = 0 then return m - 4
k ← (p - 2) σ² - 5
if positive and s ≤ k then return m - 6
for i ← 1 to p do θ̂ᵢ ← mᵢ + (1 - k/s)(xᵢ - mᵢ) - 7
return θ̂
Line L2 measures the squared distance of the data from the target. Line L6 moves each coordinate toward by the common factor . When , the plain factor is negative and the estimate jumps past the target to the other side. The positive-part variant (L5, positive true) uses and returns the target instead, which is never worse. Line L3 handles , which has probability zero.
Example
Take , , and .
- L2: .
- L4: , so .
- L6: .
Every coordinate moves of the way to zero. With scaled by , : the plain factor is , and the positive-part version returns .
Exact risk (from the theorem in Correctness, with ; itself has risk ):
Measured risk. A simulation with random.Random(20240601), , and 20000 draws for each gave the averages below. The plain column agrees with the exact risk within two standard errors; the positive-part column is only measured.
| exact plain risk | plain, measured | positive part, measured | , measured | |
|---|---|---|---|---|
Correctness
With and (the general case follows by a change of variable), the risk is
The proof writes with and uses Stein's identity , which is integration by parts against the normal density. The divergence of is , and is the same, which gives the formula. The expectation is finite only for , and equals the Poisson mixture with . At it is , so the risk is exactly for every . The risk rises with and tends to . The full proof is in proofs/correctness.md. It also shows that is an unbiased estimate of the risk (Stein's unbiased risk estimate).
What is proved: the risk formula, the domination of , and the value 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 and ; the general case follows by the change of variable , which maps to and multiplies every squared error by . So let with , and
Claim 0 (the code computes ). Lines L1 and L2 compute and . Line L3 handles , an event of probability zero, so it does not change the risk. Line L4 sets , and line L6 returns with , which is . Line L5 is used only by the positive-part variant: when the factor is at most , and the variant returns .
Lemma 1 ( is finite). For , .
Proof. Let and . For , the moment generating function of the noncentral chi-squared law gives . Since , Tonelli's theorem gives
with , . The integrand is at most , whose integral is for , with equality when . The integrand decreases in , so decreases in .
Lemma 2 (the Poisson series). .
Proof. Expand in the integral of Lemma 1 and integrate term by term (all terms are nonnegative): .
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 and let be absolutely continuous with . Then .
Proof. Let be the standard normal density, so . Write . Then
because . For swap the order of integration (Fubini, justified by ): . The part gives in the same way. The sum is .
Lemma 4 (the cross term). .
Proof. Fix and condition on the other coordinates . When , which has probability 1, the map is smooth and bounded, with
So Lemma 3 applies given , and then ; the expectation is finite by Lemma 1. Summing over ,
Theorem (the risk). For every ,
Proof. Expand :
by Lemma 4 and . All three expectations are finite by Lemma 1. The last term of the result is positive because with probability 1.
Corollaries.
- At the target. For , Lemma 1 gives , so for every .
- Shape. By Lemma 1 the risk depends on only through , increases with , and tends to as (the integrand of Lemma 1 tends to for ).
- Unbiased risk estimate. The proof shows that has expectation for every . This is Stein's unbiased risk estimate for ; the function
stein_unbiased_risk_estimatereturns it. - Domination. Since for every , dominates under total squared error when , so is inadmissible.
What is not proved here. The positive-part variant has risk no larger than the plain estimator at every (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 . Lindley's variant toward the mean has risk , where is the plain risk in dimension ; this follows from the theorem applied in the subspace orthogonal to , and the tests check its value at a constant by simulation.
Floating point. The code computes with math.fsum and forms before the multiplication by , so a tiny gives a large finite or infinite value but never . The exact risk sums the Poisson series over the terms within of the Poisson mean; the omitted mass is far below double precision.
Complexity
One pass computes , and a second pass writes the outputs: arithmetic operations, best and worst case. Extra space is : the output, and in the implementation also the differences . The exact risk function in the implementation sums Poisson terms.
Properties
- Dominates for . The risk is below at every , with the largest gain, risk instead of , at .
- Biased. for . It does not contradict the Cramér-Rao bound, which concerns unbiased estimators, or the optimality of as the minimum variance unbiased estimator.
- Minimax. is minimax with maximum risk , and the James-Stein estimator has risk below , 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 is near relative to . Far from the factor is close to and the estimate is close to .
- Not translation equivariant unless the target moves with the data, as in the variant toward the mean.
Variants and improvements
- Positive part. . It dominates the plain estimator (Baranchik 1964).
- Shrinking toward the mean (Lindley). For , . The mean direction is not shrunk, so the factor uses , and the risk is below everywhere and equal to when all are equal. The implementation has it as
james_stein_toward_mean. - Unknown variance. If is independent of with , the factor also dominates (James and Stein 1961).
- Empirical Bayes view. If independently, the Bayes estimator is . Marginally , so is an unbiased estimate of the shrinkage . 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 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 and weighted losses; the factor uses 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 , 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 . 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 after looking at breaks the risk formula. Shrinking toward the data mean is fine only with the factor of Lindley's variant.
- The plain factor can be negative. When , the plain estimate is on the other side of the target. Use the positive-part version.
- must be right. Using a wrong changes the factor; if it is too large, the estimator can lose to .
- Confidence statements. The usual intervals 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.
# 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 -dimensional normal distribution under total squared error, is admissible when or and inadmissible when . James and Stein (1961) gave the explicit estimator , 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
- James and Stein 1961, the estimator (1 - (p - 2)/||X||^2) X, its risk, and the version with an estimated variance
- Stein 1956, the sample mean is admissible for p = 1 and 2 and inadmissible for p of 3 or more
- 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
- Baranchik 1964, the positive-part estimator and its dominance over the James-Stein estimator
- 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)
- 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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag CYEN4M Edit this page History Report an error Markdown