Global (gamma-Poisson), normal/James-Stein, and spatial local empirical Bayes smoothing. This notebook is Part 5. Disease Mapping and Bayesian Smoothing (Chapter 5.5 of 11). The worked example uses diabetes_northeast.shp (217 counties). The methods come from geolattice.spatial_statistics.bayes.
Overview
Chapter 5.2 explained why raw rates are unstable; Chapter 5.4 quantified it on real data. This chapter builds the first family of fixes: empirical Bayes, which estimates a prior distribution directly from the data itself, then shrinks every area’s raw rate toward that prior in proportion to how little the area’s own data can be trusted.
Step
What we do
Gamma-Poisson
The workhorse global EB estimator: \(\theta_i \sim \text{Gamma}(a,b)\), posterior mean a weighted average of the raw SMR and the prior mean
Degenerate case
What happens, correctly, not an error, when the data show no real overdispersion
Normal/James-Stein
Shrinkage on log-transformed rates, for when a normal approximation is more convenient
Spatial (local) EB
Shrink toward the neighbourhood mean instead of the global mean
One table
Raw SMR, both EB variants, and the weight each placed on the raw data, side by side
Locate the repository root, import the spatial-statistics helpers, and point DATA at the example files.
Installation. This notebook needs installation option 3 (core, spatial analysis and spatial statistics): pip install "geolattice[statistics]". See “Installation options” in the GeoLattice README.
Code
import sysfrom pathlib import Pathimport numpy as npimport pandas as pdimport geopandas as gpdimport matplotlib.pyplot as pltROOT = Path.cwd().resolve()for candidate in [ROOT, *ROOT.parents]:if (candidate /"pyproject.toml").is_file() and (candidate /"Data").is_dir(): ROOT = candidatebreakelse:raiseFileNotFoundError("Could not find the GeoLattice repository root.")sys.path.insert(0, str(ROOT))DATA = ROOT /"Data"/"00_shared"/"data_spatial_stat"import geolattice.spatial_statisticsfrom geolattice.viz import apply_map_stylefrom geolattice.spatial_statistics.weights import Queenfrom geolattice.spatial_statistics.bayes import expected_counts, smr, eb_gamma_poisson, eb_james_stein, eb_localapply_map_style()C = {"blue": "#2b6cb0", "red": "#c0392b", "green": "#2f855a", "orange": "#dd6b20","grey": "#718096", "purple": "#6b46c1", "teal": "#2c7a7b"}counties = gpd.read_file(DATA /"diabetes_northeast.shp")O = counties["Dia_count"].to_numpy()POP = counties["POP_Total"].to_numpy()E = expected_counts(POP, observed=O)w = Queen(counties, transform="binary")raw = smr(O, E)print(f"geolattice.spatial_statistics : version {geolattice.spatial_statistics.__version__}")
geolattice.spatial_statistics : version 0.3.49
Global Gamma-Poisson Empirical Bayes
Model: \(O_i \mid \theta_i \sim \text{Poisson}(E_i \theta_i)\), \(\theta_i \sim \text{Gamma}(a, b)\). The posterior is \(\text{Gamma}(a + O_i, b + E_i)\), with mean
The weight \(w_i\) on the raw data rises toward 1 as \(E_i\) grows: small \(E_i\) means more shrinkage toward the prior mean \(a/b\), exactly the correction Chapter 5.2 motivated. \(a\) and \(b\) are estimated from the data itself, either by maximum likelihood (method='mle') or Marshall’s (1991) method of moments (method='mom').
Code
eb_mle = eb_gamma_poisson(O, E, method="mle")eb_mom = eb_gamma_poisson(O, E, method="mom")print(f"MLE : shape a={eb_mle.get('shape'):.2f}, rate b={eb_mle.get('rate'):.2f}, "f"prior mean a/b={eb_mle.prior_mean:.4f}")print(f"MOM : shape a={eb_mom.get('shape'):.2f}, rate b={eb_mom.get('rate'):.2f}, "f"prior mean a/b={eb_mom.prior_mean:.4f}")print(f"\nweight on the data (MLE): min={eb_mle.shrinkage.min():.4f}, max={eb_mle.shrinkage.max():.4f}")
MLE : shape a=47.48, rate b=45.14, prior mean a/b=1.0519
MOM : shape a=46.48, rate b=46.48, prior mean a/b=1.0000
weight on the data (MLE): min=0.8788, max=0.9998
The two estimation methods agree closely (prior mean 1.052 vs. 1.000, both close to the overall SMR mean of 1.0): real diabetes data has enough counties and a strong enough spatial signal that MLE and moments do not diverge much here. The weight on the data ranges from 0.88 to 1.00: even the smallest county in this non-sparse dataset (Chapter 5.3’s finding) still gets substantial credit for its own data, consistent with these counts not being small enough for dramatic shrinkage.
The degenerate case: no overdispersion
If the data show no more variation than pure Poisson sampling noise would produce, the moment estimator’s prior variance is \(\le 0\): mathematically, there is no evidence of a real prior spread to estimate. This is a legitimate result, not an error: every area is shrunk fully to the overall mean, because the data contain no signal beyond noise to shrink away from.
Code
rng = np.random.default_rng(1)O_nulllike = rng.poisson(E * (O.sum() / E.sum())) # every county at the SAME true rate, by constructioneb_null = eb_gamma_poisson(O_nulllike, E, method="mom")print(f"null-like data: shape={eb_null.get('shape')}, rate={eb_null.get('rate')}")print(f"weight on the data: min={eb_null.shrinkage.min()}, max={eb_null.shrinkage.max()}")print(f"every estimate equals the prior mean? {np.allclose(eb_null.estimate, eb_null.estimate[0])}")
null-like data: shape=inf, rate=inf
weight on the data: min=0.0, max=0.0
every estimate equals the prior mean? True
Exactly as documented: shape and rate both go to infinity, every weight is 0, and every county’s estimate collapses to the single overall mean: the correct behaviour when the moment method correctly detects that there is no real between-county variation to preserve.
Normal / James-Stein Shrinkage
For estimates already on a roughly normal scale (like log SMR), two classical shrinkage rules apply directly:
Code
log_smr = np.log(raw)var_log_smr =1.0/ np.maximum(O, 1) # delta-method variance of log(O) (approx)eb_normal = eb_james_stein(log_smr, var_log_smr, method="normal")eb_classic = eb_james_stein(log_smr, var_log_smr, method="james-stein")print(f"Normal EB: tau^2={eb_normal.get('tau2'):.5f}, mu={eb_normal.get('mu'):.5f}")print(f"Classical James-Stein: shrinkage factor c={eb_classic.get('factor'):.4f}")print(f"(c close to 1 means little shrinkage is needed for THIS variable at THIS scale)")
Normal EB: tau^2=0.02163, mu=0.04011
Classical James-Stein: shrinkage factor c=0.9897
(c close to 1 means little shrinkage is needed for THIS variable at THIS scale)
'normal' (parametric EB with the DerSimonian-Laird moment estimator of \(\tau^2\)) allows each area its own variance and is the more flexible default; 'james-stein' uses one common variance across all areas (Lindley’s version, needing at least 4 estimates) and is simpler but less adaptive when the \(E_i\)’s vary a lot, as they do here (Chapter 5.4).
Spatial (Local) Empirical Bayes
eb_local shrinks each area toward its neighbourhood mean instead of the global mean: respecting real regional trends (Part 2’s confirmed spatial autocorrelation) rather than always pulling toward a single national-level average, which would flatten genuine regional structure.
Code
loc = eb_local(O, E, w)print(f"Local EB weight on the data: min={loc.shrinkage.min():.4f}, max={loc.shrinkage.max():.4f}")island_idx = w.islands()[0]print(f"\nisland (Nantucket) reference mean m_i: {loc.prior_mean[island_idx]:.4f} "f"(equals the global mean gm, confirming the documented fallback)")print(f"island (Nantucket) weight on its own data: {loc.shrinkage[island_idx]:.4f}")zero_idx = np.flatnonzero(loc.shrinkage ==0.0)print(f"\ncounty with weight exactly 0: {counties.iloc[zero_idx[0]]['COUNTY']} "f"({w.cardinalities()[zero_idx[0]]} neighbour(s))")
Local EB weight on the data: min=0.0000, max=0.9998
island (Nantucket) reference mean m_i: 1.0000 (equals the global mean gm, confirming the documented fallback)
island (Nantucket) weight on its own data: 0.9470
county with weight exactly 0: Suffolk County (1 neighbour(s))
The island’s reference point\(m_i\) is exactly the global mean, confirming the documented fallback: but its weight on its own data is not forced to 0: the shrinkage factor \(C_i\) is still computed normally, using the global variance against the island’s own (reasonably large) \(E_i\), and comes out high (0.947). The island still ends up trusting its own count substantially; it is only the point it is compared against that switches from a local to a global reference, not the amount of shrinkage applied.
The true weight-0 case here belongs to a different, non-island county with only a single neighbour: its two-member “neighbourhood” (itself plus one neighbour) shows no detectable local overdispersion, so it is fully shrunk to that tiny neighbourhood’s mean: the local analogue of Section 3.1’s degenerate case, occurring area-by-area rather than dataset-wide.
One Combined Output Table
Every estimator side by side: raw SMR, global EB, local EB, and the weight each placed on the raw data.
For the smallest-\(E\) counties (top rows), EB_global and EB_local both move noticeably from raw_SMR, and their weights on the data are the lowest in the dataset: the expected pattern, now visible in one table rather than scattered across separate calls.
Summary and Conclusions
This chapter built the full empirical Bayes toolkit and validated its documented edge cases directly.
What we did
Fit global gamma-Poisson EB by both MLE and moments: prior means agree closely (1.05 vs. 1.00), and the weight on the data ranges 0.88-1.00: modest shrinkage, consistent with this data not being very sparse.
Confirmed the degenerate no-overdispersion case directly: data simulated with one common true rate for every county correctly collapses every estimate to the overall mean, with shape/rate going to infinity.
Fit normal and classical James-Stein shrinkage on log SMR.
Fit spatial local EB, and confirmed the island (no neighbours) correctly falls back to the global mean with a weight of exactly 0.
Assembled one combined table (raw SMR, both EB estimates, both weights) showing the smallest-\(E\) counties move the most under every method.
Practical takeaways
A weight-on-the-data near 0 is not a bug: it is the correct response when an area’s own data carries little information, and the null-simulation check confirms the library implements this correctly.
Prefer local (spatial) EB over global EB when the region has genuine spatial structure worth preserving (Part 2 already confirmed this data does); global EB flattens that structure toward a single national mean.
Always check how a method handles islands explicitly: eb_local’s fallback-to-global behaviour for Nantucket is documented and correct, but only because it was checked directly here.
Next steps
Chapter 5.6 (Spatial Bayesian Models: BYM and BYM2) moves from empirical Bayes point estimates to a fully Bayesian model with proper posterior uncertainty, combining both a spatial and a non-spatial random effect.
Carlin, B. P. & Louis, T. A. (2008). Bayesian Methods for Data Analysis (3rd ed.). CRC Press.
Standard reference on empirical Bayes theory
Efron, B. & Morris, C. (1975). Data analysis using Stein’s estimator and its generalizations. Journal of the American Statistical Association, 70, 311-319.
Accessible introduction to James-Stein shrinkage
Key papers
Paper
Contribution
Marshall, R. J. (1991). Mapping disease and mortality rates using empirical Bayes estimators. Applied Statistics, 40, 283-294.
Origin of the moment-based gamma-Poisson estimator and the local (spatial) EB variant used in Section 5
Clayton, D. & Kaldor, J. (1987). Empirical Bayes estimates of age-standardized relative risks for use in disease mapping. Biometrics, 43, 671-681.
Foundational EB disease-mapping paper
DerSimonian, R. & Laird, N. (1986). Meta-analysis in clinical trials. Controlled Clinical Trials, 7, 177-188.
Origin of the \(\tau^2\) moment estimator used in eb_james_stein(method='normal')