Algorithm Search⌘K

Techniquecore

Empirical Bayes

Also called empirical Bayes method, type II maximum likelihood.

Estimates the prior from many parallel cases, often by maximizing the marginal likelihood, and then applies the Bayes rule with that prior. The James-Stein estimator is one case.

Empirical Bayes is a way to use Bayes's rule when you have many similar cases but no trusted prior. It estimates the prior, or the marginal law of the data that the prior induces, from all the cases together, and then applies the Bayes estimator to each case as if the estimated prior were known. Robbins (1956) introduced it with a formula that needs no model for the prior at all. Efron and Morris (1973) showed that the James-Stein estimator is the empirical Bayes rule of the normal model, and the same idea is behind local false discovery rates and the shrinkage estimates of mixed models.

In plain words

Suppose you must estimate the accident rate of each of nine thousand drivers from one year of claims. One driver's record says little. But the whole group tells you how rates are spread among drivers, and that spread is the prior. With it, you can say how much of a good or bad year is luck. A driver with no claims is probably not perfect, and a driver with seven claims is probably not as bad as seven. Empirical Bayes learns the spread from the group and then applies the ordinary Bayes answer to each driver. The price is that the spread is itself estimated, and simple versions forget this uncertainty.

When it applies

  • Many parallel cases with the same structure. Observations x1,…,xNx_1, \ldots, x_N with xi∣θi∼f(x∣θi)x_i \mid \theta_i \sim f(x \mid \theta_i), the θi\theta_i drawn independently from an unknown prior gg. The cases share gg but not θi\theta_i.
  • The marginal law identifies what you need. Each xix_i has the marginal law mg(x)=∫f(x∣θ) g(θ) dθm_g(x) = \int f(x \mid \theta)\, g(\theta)\, d\theta, and mgm_g can be estimated from the xix_i. Either gg itself is identified from mgm_g, or, as in Robbins's and Tweedie's formulas, the Bayes rule is a function of mgm_g alone.
  • NN is large enough. The estimate of gg has error of order 1/N1/\sqrt N in parametric models and slower in nonparametric ones. With few cases, such as the eight schools below, a full hierarchical model that puts a prior on the parameters of gg is safer.
  • Not for one case. With N=1N = 1 there is nothing to borrow.

The template

The holes are the sampling model f, the class G of priors, the fitting method FIT and the decision RULE.

  1. EMPIRICAL-BAYES(x₁, ..., x_N, f, G, FIT, RULE)
  2. 1m_g(x) ← ∫ f(x | θ) g(θ) dθ for g ∈ G ▷ the marginal law of one observation
  3. 2ĝ ← FIT(x₁, ..., x_N; m) ▷ type II ML: ĝ = argmax over G of Σᵢ log m_g(xᵢ)
  4. 3for i ← 1 to N do
  5. 4δᵢ ← RULE(posterior p(θ | xᵢ) under ĝ) ▷ posterior mean, interval, or P(null | xᵢ)
  6. 5return δ₁, ..., δ_N

Common choices:

  • FIT by type II maximum likelihood (g-modeling): maximize the marginal likelihood ∏img(xi)\prod_i m_g(x_i) over a parametric family, or over all priors (the nonparametric maximum likelihood estimate of Kiefer and Wolfowitz, computed by EM or convex optimization).
  • FIT by moments: match the mean and the variance of mgm_g to those of the data.
  • f-modeling: skip gg and estimate mgm_g directly, then plug it into a formula for the Bayes rule in terms of mgm_g.

Robbins's formula. Let x∣θ∼x \mid \theta \sim Poisson(θ)(\theta) and θ∼g\theta \sim g, any prior on (0,∞)(0, \infty). Then

E[θ∣x]=(x+1) m(x+1)m(x),m(x)=∫e−θθxx! g(dθ).\mathbb{E}[\theta \mid x] = (x + 1)\, \frac{m(x + 1)}{m(x)}, \qquad m(x) = \int e^{-\theta} \frac{\theta^x}{x!}\, g(d\theta).

Proof. By Bayes's theorem the posterior is g(dθ∣x)=e−θθxg(dθ)/(x! m(x))g(d\theta \mid x) = e^{-\theta}\theta^x g(d\theta)/(x!\, m(x)). So

E[θ∣x]=1x! m(x)∫θ e−θθx g(dθ)=(x+1)! m(x+1)x! m(x)=(x+1)m(x+1)m(x).■\mathbb{E}[\theta \mid x] = \frac{1}{x!\, m(x)} \int \theta\, e^{-\theta}\theta^x\, g(d\theta) = \frac{(x + 1)!\, m(x + 1)}{x!\, m(x)} = (x + 1)\frac{m(x + 1)}{m(x)}. \qquad \blacksquare

Robbins's estimate replaces m(x)m(x) by the observed frequency of the value xx: E^[θ∣x]=(x+1)Nx+1/Nx\hat{\mathbb{E}}[\theta \mid x] = (x + 1) N_{x+1}/N_x, where NxN_x is the number of cases with value xx.

Tweedie's formula. Let z∣μ∼N(μ,σ2)z \mid \mu \sim N(\mu, \sigma^2) with σ2\sigma^2 known, and μ∼g\mu \sim g, any prior. Let f(z)=∫φσ(z−μ) g(dμ)f(z) = \int \varphi_\sigma(z - \mu)\, g(d\mu) be the marginal density, with φσ\varphi_\sigma the N(0,σ2)N(0, \sigma^2) density. Then

E[μ∣z]=z+σ2ddzlog⁡f(z).\mathbb{E}[\mu \mid z] = z + \sigma^2 \frac{d}{dz} \log f(z).

Proof. Since φσ′(u)=−(u/σ2)φσ(u)\varphi_\sigma'(u) = -(u/\sigma^2)\varphi_\sigma(u), the integrand of ff has zz-derivative μ−zσ2φσ(z−μ)\frac{\mu - z}{\sigma^2}\varphi_\sigma(z - \mu). Its absolute value is at most sup⁡u∣u∣φσ(u)/σ2=1/(σ22πe)\sup_u \lvert u \rvert \varphi_\sigma(u)/\sigma^2 = 1/(\sigma^2\sqrt{2\pi e}), a constant, which is integrable against the probability measure gg. So dominated convergence lets us differentiate under the integral:

f′(z)=1σ2∫(μ−z) φσ(z−μ) g(dμ)=f(z)σ2(E[μ∣z]−z),f'(z) = \frac{1}{\sigma^2}\int (\mu - z)\, \varphi_\sigma(z - \mu)\, g(d\mu) = \frac{f(z)}{\sigma^2}\big(\mathbb{E}[\mu \mid z] - z\big),

because φσ(z−μ) g(dμ)/f(z)\varphi_\sigma(z - \mu)\, g(d\mu)/f(z) is the posterior. Divide by f(z)/σ2f(z)/\sigma^2. ■\blacksquare

Both formulas give the Bayes rule from the marginal density alone, so a good estimate of mm or ff from many cases gives a good estimate of the rule. Efron (2011) uses Tweedie's formula to correct the selection bias of the largest zz-values.

Classic examples

Insurance claims (Robbins). Efron and Hastie (2016, Table 6.1) give the number of claims of 94619461 policy holders in one year: 7840,1317,239,42,14,4,4,17840, 1317, 239, 42, 14, 4, 4, 1 holders had 0,1,…,70, 1, \ldots, 7 claims. Robbins's formula and a gamma prior fitted by maximum marginal likelihood (the marginal is negative binomial; the fit is shape ν^=0.7015\hat\nu = 0.7015 and scale 0.30560.3056, so the prior mean equals the sample mean 0.21440.2144) give these estimates of next year's rate:

claims xx 0 1 2 3 4 5 6
Robbins (x+1)Nx+1/Nx(x+1)N_{x+1}/N_x 0.168 0.363 0.527 1.333 1.429 6.000 1.750
gamma prior, (x+ν^)σ^/(1+σ^)(x + \hat\nu)\hat\sigma/(1 + \hat\sigma) 0.164 0.398 0.632 0.866 1.100 1.334 1.568

The two rules agree where the counts are large. For x≥3x \ge 3 Robbins's estimate rests on a handful of holders and jumps around, and it is not even monotone; the gamma prior gives a smooth line. Table 6.1 of the book prints 1.251.25 for Robbins at x=6x = 6; the formula gives 7⋅1/4=1.757 \cdot 1/4 = 1.75.

Normal means and James-Stein. Let xi∼N(θi,σ2)x_i \sim N(\theta_i, \sigma^2) and θi∼N(μ,τ2)\theta_i \sim N(\mu, \tau^2). The marginal law is xi∼N(μ,σ2+τ2)x_i \sim N(\mu, \sigma^2 + \tau^2), so type II maximum likelihood gives μ^=xˉ\hat\mu = \bar x and τ^2=max⁡(0,1N∑i(xi−xˉ)2−σ2)\hat\tau^2 = \max\big(0, \frac1N\sum_i (x_i - \bar x)^2 - \sigma^2\big). The rule is θ^i=μ^+(1−B^)(xi−μ^)\hat\theta_i = \hat\mu + (1 - \hat B)(x_i - \hat\mu) with the shrinkage factor B^=σ2/(σ2+τ^2)\hat B = \sigma^2/(\sigma^2 + \hat\tau^2). With μ=0\mu = 0 fixed, replacing the maximum likelihood estimate of 1/(σ2+τ2)1/(\sigma^2 + \tau^2) by the unbiased one gives the James-Stein estimator, and with μ\mu estimated by xˉ\bar x it gives Lindley's variant toward the mean; their risks are on that page. With ten means drawn by random.Random(2) (θi∼N(0,1)\theta_i \sim N(0, 1), σ=1\sigma = 1), x=(1.83,−0.95,−0.51,0.57,0.29,−4.6,0.78,−1.14,−1.82,−0.58)x = (1.83, -0.95, -0.51, 0.57, 0.29, -4.6, 0.78, -1.14, -1.82, -0.58) gives μ^=−0.613\hat\mu = -0.613, τ^2=1.788\hat\tau^2 = 1.788 and B^=0.359\hat B = 0.359. The total squared error falls from 14.0714.07 for xx to 7.407.40 for the empirical Bayes rule.

Large-scale testing. In the two-groups model each zz-value is null with prior probability π0\pi_0, and the marginal density is f=π0f0+(1−π0)f1f = \pi_0 f_0 + (1 - \pi_0) f_1. The posterior probability of the null is the local false discovery rate π0f0(z)/f(z)\pi_0 f_0(z)/f(z). Efron estimates ff from all the zz-values, which is f-modeling again.

Mixed models. In a linear mixed model the random effects are the θi\theta_i, the variance components are the parameters of gg, and REML or maximum likelihood fits them from the marginal law. The predicted random effects (BLUPs) are the posterior means under the fitted gg: empirical Bayes under another name.

Variations

  • Parametric and nonparametric gg. Parametric families (normal, gamma, beta) give stable fits and smooth rules. The nonparametric maximum likelihood estimate of gg is discrete and adapts to any shape, at a slower rate.
  • Hierarchical Bayes. Put a prior on the parameters of gg and integrate them out, as on the hierarchical model page. The answers agree with empirical Bayes when NN is large, and the hierarchical version is better calibrated when NN is small.
  • Empirical Bayes intervals. Morris (1983) widens the plug-in posterior variance to account for the error in μ^\hat\mu and τ^2\hat\tau^2. Robust versions keep their coverage over a whole class of priors.
  • Empirical Bayes priors in variable selection. The prior inclusion probability of a spike-and-slab prior or the global scale of a horseshoe prior can be set by maximizing the marginal likelihood. The estimate of the global scale can collapse to 00, so a full prior is usually preferred.
  • Type II maximum likelihood in machine learning. The hyperparameters of a Gaussian process are usually fitted by maximizing the marginal likelihood. This is the same template with one case.

Pitfalls

  • Plug-in intervals are too short. They treat g^\hat g as known. The table at the end of this section shows how much coverage they lose.
  • τ^2=0\hat\tau^2 = 0 is common. For the eight schools of Rubin (1981), y=(28,8,−3,7,−1,1,18,12)y = (28, 8, -3, 7, -1, 1, 18, 12) with standard errors (15,10,16,11,9,11,10,18)(15, 10, 16, 11, 9, 11, 10, 18), the marginal log-likelihood with μ\mu profiled out is −29.674,−29.687,−29.725,−29.994,−30.892,−33.318-29.674, -29.687, -29.725, -29.994, -30.892, -33.318 at τ=0,1,2,5,10,20\tau = 0, 1, 2, 5, 10, 20. The maximum is at τ=0\tau = 0, so empirical Bayes pools all eight schools to 7.697.69 and claims there is no variation at all. The likelihood is almost flat up to τ=5\tau = 5, which the plug-in answer hides.
  • Using the data twice. The prior is fitted to the same data that it is then applied to. This is fine for the averaged risk across cases, which is the point of the method, but statements about one case must account for it.
  • Few or unlike cases. Borrowing strength across cases that do not share a prior pulls each case toward the wrong center. Group the cases first.
  • Robbins's formula with sparse counts. The ratio Nx+1/NxN_{x+1}/N_x is noisy where NxN_x is small, and the estimate need not be monotone in xx. Smooth the counts or fit a parametric gg.
  • Selection. Reporting only the largest raw estimates overstates them. The empirical Bayes estimates correct this, as Tweedie's formula shows, but only if the rule is applied to all cases, not to the selected ones after a separate fit.

Coverage of plug-in intervals. The simulation draws θi∼N(0,τ2)\theta_i \sim N(0, \tau^2) and xi∼N(θi,1)x_i \sim N(\theta_i, 1), fits μ^\hat\mu and τ^2\hat\tau^2 by type II maximum likelihood, and forms the 95% plug-in intervals θ^i±1.96(1−B^)σ2\hat\theta_i \pm 1.96\sqrt{(1 - \hat B)\sigma^2}. It uses random.Random(100 + N), with 4000 runs for N≤20N \le 20 and 1000 runs for N=50N = 50. When τ^2=0\hat\tau^2 = 0, every interval has length 00.

cases NN τ2\tau^2 coverage share of runs with τ^2=0\hat\tau^2 = 0
8 0.5 53.4% 36.8%
20 0.5 70.9% 17.8%
50 0.5 85.3% 4.1%
8 2 80.4% 7.6%
8 10 92.9% 0.3%

Code

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.

empirical_bayes.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/empirical-bayes/. The authors are listed in prov/NGX20X.jsonl.
"""Empirical Bayes: estimate the prior from many parallel cases, then use the Bayes rule.

Three instances of the template on the page:

* robbins: Poisson counts, no model for the prior (f-modeling). The Bayes rule
  E[theta | x] = (x + 1) f(x + 1) / f(x) is estimated with the observed frequencies.
* gamma_poisson_fit and gamma_poisson_posterior_mean: Poisson counts with a gamma
  prior fitted by maximum marginal likelihood (g-modeling).
* normal_eb: normal means x_i ~ N(theta_i, s_i^2) with theta_i ~ N(mu, tau^2), where
  mu and tau^2 are fitted by maximum marginal likelihood (type II maximum likelihood).

tweedie_posterior_mean gives E[mu | z] = z + sigma^2 d/dz log f(z) for a normal mixture
f, and discrete_prior_posterior_mean computes the same posterior mean directly. Both are
used to check Tweedie's formula and Robbins's formula against the exact Bayes rule.
"""

import math
from typing import Sequence


def robbins(counts: Sequence[float]) -> list[float]:
    """Robbins's estimate of E[theta | x] for x = 0, ..., len(counts) - 2.

    counts[x] is the number (or frequency) of cases with value x. The estimate at x is
    (x + 1) counts[x + 1] / counts[x]; it is None where counts[x] is 0.
    """
    out = []
    for x in range(len(counts) - 1):
        out.append(None if counts[x] == 0 else (x + 1) * counts[x + 1] / counts[x])
    return out


def poisson_mixture_posterior_mean(x: int, atoms: Sequence, weights: Sequence):
    """Exact E[theta | x] when theta has the discrete prior P(theta = atoms[k]) = weights[k].

    Works with Fractions if the factor exp(-theta) is already folded into the weights:
    pass weights w_k = g_k exp(-theta_k), then the result is sum w theta^(x+1) / sum w theta^x.
    """
    num = sum(w * a ** (x + 1) for a, w in zip(atoms, weights))
    den = sum(w * a ** x for a, w in zip(atoms, weights))
    return num / den


def poisson_mixture_marginal(x: int, atoms: Sequence, weights: Sequence):
    """f(x) * x! for the same discrete prior: sum_k w_k theta_k^x (w_k includes exp(-theta_k))."""
    return sum(w * a ** x for a, w in zip(atoms, weights))


def _nb_loglik(counts: Sequence[float], nu: float, scale: float) -> float:
    """Log-likelihood of grouped counts under the negative binomial marginal of a
    Poisson law with a Gamma(shape nu, scale) prior."""
    p = scale / (1.0 + scale)
    total = 0.0
    for x, c in enumerate(counts):
        if c:
            total += c * (math.lgamma(x + nu) - math.lgamma(nu) - math.lgamma(x + 1)
                          + x * math.log(p) + nu * math.log1p(-p))
    return total


def _golden_max(f, lo: float, hi: float, tol: float = 1e-10) -> float:
    """Maximize a unimodal function on [lo, hi] by golden section search."""
    g = (math.sqrt(5.0) - 1.0) / 2.0
    a, b = lo, hi
    c, d = b - g * (b - a), a + g * (b - a)
    fc, fd = f(c), f(d)
    while b - a > tol * (1.0 + abs(a) + abs(b)):
        if fc >= fd:
            b, d, fd = d, c, fc
            c = b - g * (b - a)
            fc = f(c)
        else:
            a, c, fc = c, d, fd
            d = a + g * (b - a)
            fd = f(d)
    return (a + b) / 2.0


def gamma_poisson_fit(counts: Sequence[float]) -> tuple[float, float]:
    """Maximum marginal likelihood (shape nu, scale) of a gamma prior for Poisson counts.

    For a fixed shape the likelihood is maximized at scale = mean / nu, because the
    maximum likelihood estimate of a negative binomial mean is the sample mean. The
    shape is then found by a one-dimensional search on log(nu).
    """
    n = sum(counts)
    mean = sum(x * c for x, c in enumerate(counts)) / n
    if mean <= 0:
        raise ValueError("all counts are zero")

    def prof(t: float) -> float:
        nu = math.exp(t)
        return _nb_loglik(counts, nu, mean / nu)

    t = _golden_max(prof, math.log(1e-4), math.log(1e4))
    nu = math.exp(t)
    return nu, mean / nu


def gamma_poisson_posterior_mean(x: int, nu: float, scale: float) -> float:
    """E[theta | x] = (x + nu) scale / (1 + scale) under a Gamma(nu, scale) prior."""
    return (x + nu) * scale / (1.0 + scale)


def _normal_marginal_loglik(x, s2, mu, tau2) -> float:
    """Log-likelihood of the marginal law x_i ~ N(mu, s2_i + tau2)."""
    terms = [math.log(2 * math.pi * (v + tau2)) + (a - mu) ** 2 / (v + tau2) for a, v in zip(x, s2)]  # @line L1
    return -0.5 * math.fsum(terms)


def _weighted_mean(x, s2, tau2) -> float:
    w = [1.0 / (v + tau2) for v in s2]
    return math.fsum(a * b for a, b in zip(w, x)) / math.fsum(w)


def normal_eb(x: Sequence[float], s2: Sequence[float]) -> dict:
    """Type II maximum likelihood for x_i ~ N(theta_i, s2_i), theta_i ~ N(mu, tau^2).

    The marginal law is x_i ~ N(mu, s2_i + tau^2) (line L1 of the template). For
    equal s2_i the maximum is tau^2 = max(0, mean((x - xbar)^2) - s2), mu = xbar. For
    unequal s2_i, mu is profiled out as the weighted mean and tau is found by a
    search on [0, upper]. Returns mu, tau2, the shrinkage factors B_i = s2_i/(s2_i +
    tau^2), the posterior means and the plug-in posterior variances.
    """
    p = len(x)
    if len(set(s2)) == 1:
        v = s2[0]
        xbar = math.fsum(x) / p
        tau2 = max(0.0, math.fsum((a - xbar) ** 2 for a in x) / p - v)  # @line L2
        mu = xbar
    else:
        spread = max(x) - min(x)
        upper = (spread + math.sqrt(max(s2))) ** 2

        def prof(tau: float) -> float:
            t2 = tau * tau
            return _normal_marginal_loglik(x, s2, _weighted_mean(x, s2, t2), t2)

        grid = [upper * j / 400.0 for j in range(401)]
        vals = [prof(t) for t in grid]
        j = max(range(len(grid)), key=lambda i: vals[i])
        lo = grid[max(j - 1, 0)]
        hi = grid[min(j + 1, len(grid) - 1)]
        tau = _golden_max(prof, lo, hi) if j > 0 else 0.0
        if j > 0 and prof(0.0) >= prof(tau):
            tau = 0.0
        tau2 = tau * tau
        mu = _weighted_mean(x, s2, tau2)
    shrink, mean, var = [], [], []
    for a, v in zip(x, s2):  # @line L3
        b = v / (v + tau2) if v + tau2 > 0 else 1.0
        shrink.append(b)
        mean.append(mu + (1.0 - b) * (a - mu))  # @line L4
        var.append((1.0 - b) * v)
    return {"mu": mu, "tau2": tau2, "shrink": shrink, "post_mean": mean, "post_var": var,  # @line L5
            "loglik": _normal_marginal_loglik(x, s2, mu, tau2)}


def tweedie_posterior_mean(z: float, atoms: Sequence[float], weights: Sequence[float],
                           sigma2: float = 1.0) -> float:
    """Tweedie's formula E[mu | z] = z + sigma2 * f'(z)/f(z) for the normal mixture
    f(z) = sum_k g_k N(z; mu_k, sigma2), with the derivative computed analytically."""
    dens = [g * math.exp(-(z - m) ** 2 / (2 * sigma2)) for m, g in zip(atoms, weights)]
    f = math.fsum(dens)
    fprime = math.fsum(d * (m - z) / sigma2 for d, m in zip(dens, atoms))
    return z + sigma2 * fprime / f


def discrete_prior_posterior_mean(z: float, atoms: Sequence[float], weights: Sequence[float],
                                  sigma2: float = 1.0) -> float:
    """E[mu | z] for z ~ N(mu, sigma2) and the discrete prior P(mu = atoms[k]) = weights[k]."""
    post = [g * math.exp(-(z - m) ** 2 / (2 * sigma2)) for m, g in zip(atoms, weights)]
    return math.fsum(p * m for p, m in zip(post, atoms)) / math.fsum(post)
test_empirical_bayes.py 147 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/empirical-bayes/. The authors are listed in prov/NGX20X.jsonl.
"""Tests for empirical Bayes: Robbins and Tweedie against exact Bayes rules, gamma-Poisson
and normal type II maximum likelihood, and the undercoverage of plug-in intervals."""

import math
import random
import unittest
from fractions import Fraction as F
from statistics import NormalDist

from empirical_bayes import (
    _normal_marginal_loglik,
    discrete_prior_posterior_mean,
    gamma_poisson_fit,
    gamma_poisson_posterior_mean,
    normal_eb,
    poisson_mixture_marginal,
    poisson_mixture_posterior_mean,
    robbins,
    tweedie_posterior_mean,
)

CLAIMS = [7840, 1317, 239, 42, 14, 4, 4, 1]
SCHOOLS_Y = [28, 8, -3, 7, -1, 1, 18, 12]
SCHOOLS_S = [15, 10, 16, 11, 9, 11, 10, 18]


def poisson(rng, lam):
    """Knuth's multiplication method; fine for small lam."""
    limit, k, p = math.exp(-lam), 0, rng.random()
    while p > limit:
        k += 1
        p *= rng.random()
    return k


class Robbins(unittest.TestCase):
    def test_exact_on_true_marginal(self):
        # w_k = g_k exp(-theta_k) are arbitrary positive rationals: Robbins's formula is
        # an identity, so it holds for every such choice.
        atoms = [F(1, 3), F(1), F(5, 2), F(4)]
        weights = [F(2, 7), F(1, 5), F(3, 11), F(1, 13)]
        counts = [poisson_mixture_marginal(x, atoms, weights) / math.factorial(x) for x in range(9)]
        for x, est in enumerate(robbins(counts)):
            self.assertEqual(est, poisson_mixture_posterior_mean(x, atoms, weights))

    def test_claims_table(self):
        got = robbins(CLAIMS)
        for est, want in zip(got, [0.168, 0.363, 0.527, 1.333, 1.429, 6.0, 1.75]):
            self.assertAlmostEqual(est, want, places=3)

    def test_zero_count(self):
        self.assertIsNone(robbins([3, 0, 1])[1])

    def test_simulated_gamma_prior(self):
        rng = random.Random(4)
        nu, scale = 2.0, 0.5
        counts = [0] * 30
        for _ in range(60000):
            counts[poisson(rng, rng.gammavariate(nu, scale))] += 1
        est = robbins(counts)
        for x in range(3):
            # delta method: the relative error of a ratio of counts is about
            # sqrt(1/c[x] + 1/c[x + 1]); allow four of these
            sd = est[x] * math.sqrt(1 / counts[x] + 1 / counts[x + 1])
            self.assertLess(abs(est[x] - gamma_poisson_posterior_mean(x, nu, scale)), 4 * sd)


class GammaPoisson(unittest.TestCase):
    def test_claims_fit_matches_book_column(self):
        nu, scale = gamma_poisson_fit(CLAIMS)
        book = [0.164, 0.398, 0.633, 0.87, 1.10, 1.34, 1.57]
        for x, want in enumerate(book):
            self.assertLess(abs(gamma_poisson_posterior_mean(x, nu, scale) - want), 0.006)

    def test_mean_is_matched(self):
        nu, scale = gamma_poisson_fit(CLAIMS)
        mean = sum(x * c for x, c in enumerate(CLAIMS)) / sum(CLAIMS)
        self.assertAlmostEqual(nu * scale, mean, places=12)


class Tweedie(unittest.TestCase):
    def test_against_direct_posterior_mean(self):
        atoms = [-2.0, 0.0, 3.0]
        weights = [0.2, 0.5, 0.3]
        for z in (-3.0, -1.0, 0.0, 0.5, 2.0, 4.0):
            for s2 in (1.0, 0.25):
                a = tweedie_posterior_mean(z, atoms, weights, s2)
                b = discrete_prior_posterior_mean(z, atoms, weights, s2)
                self.assertLess(abs(a - b), 1e-12)

    def test_normal_prior_limit(self):
        # many atoms on a fine grid approximate N(0, 1): E[mu | z] -> z/2
        atoms = [i / 50.0 for i in range(-400, 401)]
        weights = [math.exp(-a * a / 2) for a in atoms]
        for z in (-2.0, 0.7, 3.0):
            self.assertAlmostEqual(tweedie_posterior_mean(z, atoms, weights), z / 2, places=6)


class NormalEB(unittest.TestCase):
    def test_eight_schools_tau_zero(self):
        r = normal_eb(SCHOOLS_Y, [s * s for s in SCHOOLS_S])
        self.assertEqual(r["tau2"], 0.0)
        w = [1 / (s * s) for s in SCHOOLS_S]
        pooled = sum(a * b for a, b in zip(w, SCHOOLS_Y)) / sum(w)
        self.assertAlmostEqual(r["mu"], pooled, places=10)
        self.assertAlmostEqual(pooled, 7.6856, places=4)
        for m in r["post_mean"]:
            self.assertAlmostEqual(m, pooled, places=10)

    def test_equal_variances_closed_form_is_the_maximum(self):
        x = [1.83, -0.95, -0.51, 0.57, 0.29, -4.6, 0.78, -1.14, -1.82, -0.58]
        r = normal_eb(x, [1.0] * 10)
        best = r["loglik"]
        for mu in (r["mu"] - 0.1, r["mu"], r["mu"] + 0.1):
            for t2 in (0.0, 0.5, r["tau2"] * 0.95, r["tau2"] * 1.05, 3.0):
                self.assertLessEqual(_normal_marginal_loglik(x, [1.0] * 10, mu, t2), best + 1e-12)
        self.assertAlmostEqual(r["tau2"], 1.787961, places=6)
        self.assertAlmostEqual(r["shrink"][0], 1 / (1 + 1.787961), places=6)

    def test_unequal_variances_search_is_a_maximum(self):
        x = [2.0, -1.0, 4.0, 0.5, 6.0, -3.0]
        s2 = [1.0, 2.0, 0.5, 1.5, 3.0, 1.0]
        r = normal_eb(x, s2)
        self.assertGreater(r["tau2"], 0.0)
        for t2 in (r["tau2"] * 0.98, r["tau2"] * 1.02):
            w = [1 / (v + t2) for v in s2]
            mu = sum(a * b for a, b in zip(w, x)) / sum(w)
            self.assertLess(_normal_marginal_loglik(x, s2, mu, t2), r["loglik"])

    def test_plug_in_intervals_undercover(self):
        z = NormalDist().inv_cdf(0.975)
        rng = random.Random(108)
        cover = total = 0
        for _ in range(1000):
            theta = [rng.gauss(0.0, math.sqrt(0.5)) for _ in range(8)]
            x = [t + rng.gauss(0.0, 1.0) for t in theta]
            r = normal_eb(x, [1.0] * 8)
            for t, m, v in zip(theta, r["post_mean"], r["post_var"]):
                total += 1
                cover += abs(t - m) <= z * math.sqrt(v)
        self.assertLess(cover / total, 0.8)


if __name__ == "__main__":
    unittest.main()

Exercises

  1. Prove Robbins's formula for the geometric model P(x∣θ)=(1−θ)θxP(x \mid \theta) = (1 - \theta)\theta^x, x=0,1,…x = 0, 1, \ldots: show E[θ∣x]=m(x+1)/m(x)\mathbb{E}[\theta \mid x] = m(x + 1)/m(x).
  2. In the normal-normal model with known σ2\sigma^2 and μ=0\mu = 0, show that ∥x∥2/(σ2+τ2)∼χN2\lVert x \rVert^2/(\sigma^2 + \tau^2) \sim \chi^2_N and that (N−2)σ2/∥x∥2(N - 2)\sigma^2/\lVert x \rVert^2 is unbiased for B=σ2/(σ2+τ2)B = \sigma^2/(\sigma^2 + \tau^2). Which estimator of BB does type II maximum likelihood give?
  3. Apply Tweedie's formula to the prior μ∼N(0,A)\mu \sim N(0, A) and check that it gives the posterior mean AA+σ2z\frac{A}{A + \sigma^2} z.
  4. Show that for the gamma prior with shape ν\nu and scale ss, the marginal of a Poisson count is negative binomial, and that the maximum likelihood estimate of its mean is the sample mean for any fixed ν\nu.
  5. Explain why the plug-in posterior variance (1−B^)σ2(1 - \hat B)\sigma^2 is 00 when τ^2=0\hat\tau^2 = 0, and propose a correction that adds a term for the uncertainty in B^\hat B.

References

  1. Robbins 1956, the Poisson case and the estimate (x + 1) f(x + 1)/f(x) of the Bayes rule (general locator)
  2. Bradley Efron and Trevor Hastie, Computer Age Statistical Inference, Cambridge University Press, 2016, Chapter 6, Section 6.1 (Robbins's formula and Table 6.1, the automobile insurance claims, with the gamma maximum likelihood column)
  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 normal-normal model, the marginal estimate of the shrinkage factor and the James-Stein rule as empirical Bayes)
  4. Bradley Efron, Tweedie's formula and selection bias, Journal of the American Statistical Association 106(496), 2011, pages 1602 to 1614 (Tweedie's formula E[mu | z] = z + sigma^2 d/dz log f(z), and its use against selection bias; general locator)
  5. Carl N. Morris, Parametric empirical Bayes inference: theory and applications, Journal of the American Statistical Association 78(381), 1983, pages 47 to 55 (the sections on error estimates and empirical Bayes confidence intervals; general locator)
  6. Bradley Efron, Large-Scale Inference: Empirical Bayes Methods for Estimation, Testing, and Prediction, Cambridge University Press, 2010, Chapter 1 (empirical Bayes and the James-Stein estimator) and Chapters 5 and 6 (local false discovery rates)

Where this leads

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 proofH0 no proof
  • add a proof in proofs/ (06.5)
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
  • three classic examples