Chapter 8
Group Comparisons and Hierarchical Modeling
Whenever data come in groups—students nested inside schools, patients nested inside hospitals, or baseball players across a league—two naive extremes tempt the analyst. No pooling fits each group completely separately, leaving small groups noisy and erratic. Complete pooling lumps all groups into one common mean, erasing genuine differences between groups. Chapter 8 resolves this tension cleanly through hierarchical modelingPeter D. Hoff. A First Course in Bayesian Statistical Methods. Springer Texts in Statistics. Springer, New York, 2009. ISBN 978-0-387-92299-7. doi: 10.1007/978-0-387-92407-6; Dennis V. Lindley and Adrian F. M. Smith. Bayes Estimates for the Linear Model. Journal of the Royal Statistical Society, Series B, 34:1–41, 1972; and Andrew Gelman and Jennifer Hill. Data Analysis Using Regression and Multilevel/Hierarchical Models. Cambridge University Press, New York, 2007, where groups share information smoothly (partial pooling) in direct proportion to their sample sizes and between-group variance.
8.1Two-Group Comparisons: Continuous Pooling via #
Start with urban public high schools from the 2002 Educational Longitudinal Study (ELS): tenth graders in School 1 () and in School 2 (), a sample gap of points. Classical practice runs a two-sample -test: if , report separate means ; if , pool both schools into a single grand mean. That binary switch is discontinuous and wastes information when groups are similar yet non-identical.
Hoff replaces the binary switch with a reparameterization into an overall level and a half-difference :
(8.1)with a shared variance . With , the prior variance dials continuously between the two extremes: as , (complete pooling); as together with , and become prior-independent (no pooling); for finite , the data themselves determine how far apart the two school means should be pulled.
8.2Many Groups: Double Exchangeability and the Hierarchical Normal Model#
Now suppose we observe public high schools from the 2002 ELS, with tenth-grade students in school ( ranging from to ). Two symmetries hold simultaneously:
- Within-group exchangeability: given school ’s mean and within-school variance , student scores are exchangeable, so .
- Between-group exchangeability: the 100 schools are themselves a sample from the population of U.S. public high schools, so their means are exchangeable across schools: .
Remark 8.1 (Sampling model vs. prior in hierarchical models). Hoff emphasizes a vital conceptual distinction: is not merely a fixed prior—it is a between-group sampling model describing variation across schools, whose population parameters are estimated from the data! Only the top-level distribution is a subjective prior.
Equipping with independent semiconjugate priors,
(8.2)yields the directed acyclic graph (DAG) in Figure 8.1 (left panel) and the joint posterior factorization
(8.3)8.2.1Full Conditionals and Modular Gibbs Sampling#
Reading directly off the DAG factorization (8.3), each parameter depends only on its immediate Markov blanket (parents, children, and co-parents), yielding four standard full conditionals:
Proposition 8.2 (Full Conditionals of the Hierarchical Normal Model). Under (8.2)–(8.3), let and . Then:
Group means (conditionally independent across ):
(8.4)Population grand mean (depends on only through ):
(8.5)Between-group precision:
(8.6)Within-group precision:
(8.7)
Notice how every single equation in Proposition 8.2 is just the Chapter 6 semiconjugate normal update applied at two levels: treat as their “data,” while each treats as its “prior.”Note a minor typographical slip on p. 135 of the 2009 printing of Hoff, which prints instead of in the numerator of (8.4) (Hoff’s R code on p. 138 correctly writes mu/tau2); see Appendix C.
8.3Adaptive Shrinkage and Stein’s Paradox#
Rewriting the conditional expectation in (8.4) exposes the exact shrinkage weight for group :
(8.8)Two forces control how aggressively group borrows strength from the grand mean :
- Sample size : small groups (small ) receive smaller weight and shrink strongly toward ; large groups stay near (Figure 8.1, right).
- Variance ratio : when schools are genuinely similar (), is large and shrinkage is strong; when schools truly differ widely (), and the model lets each school stand on its own.
In the 2002 ELS math scores ( schools, posterior , , , so ), this produces a dramatic ranking reversal among low-scoring schools: School 82 has the lower raw sample mean () based on only students, so its hierarchical estimate shrinks strongly upward toward to ; School 46 has a slightly higher raw mean () based on students, so it shrinks far less to —reversing their order so that ! This echoes Stein’s phenomenonCharles Stein. Inadmissibility of the Usual Estimator for the Mean of a Multivariate Normal Distribution. In Proceedings of the Third Berkeley Symposium on Mathematical Statistics and Probability, volume 1, pages 197–206, Berkeley, 1956. University of California Press; and Bradley Efron and Carl Morris. Stein’s Estimation Rule and Its Competitors—An Empirical Bayes Approach. Journal of the American Statistical Association, 68:117–130, 1973: with known equal variances, suitable shrinkage toward a fixed point () or toward the estimated grand mean () strictly dominates the unpooled sample means under total squared error .
Remark 8.3 (Two modern caveats: variance priors and non-centered parameterizations).
- Prior sensitivity for when is small: With schools, the data pin down easily. When is small (say ), however, standard priors on can severely distort inference near ; weakly informative half- or half-Cauchy priors on the standard deviation are far saferAndrew Gelman. Prior Distributions for Variance Parameters in Hierarchical Models. Bayesian Analysis, 1(3):515–534, 2006.
- Centered vs. non-centered mixing: When is small relative to , the centered parameterization creates a narrow “funnel” geometry where Gibbs steps stall. Writing with (the non-centered parameterizationOmiros Papaspiliopoulos, Gareth O. Roberts, and Martin Sköld. A General Framework for the Parametrization of Hierarchical Models. Statistical Science, 22(1):59–73, 2007) decouples from and restores fast mixing.
8.4Heterogeneous Group Variances#
What if different schools also have different within-school spreads ? Adding a second hierarchy for the variances borrows strength across groups for variance estimation as well:
(8.9)Each now has its own conjugate gamma full conditional . Multiplying by yields the exact conjugate full conditional for the shared variance hyperparameter :
(8.10)which is .Watch out for a missing factor of in the rate parameter printed on p. 144 of Hoff (2009), which writes instead of ; see Appendix C. Because enters inside the gamma function , it has no standard conjugate density; restricting to a discrete grid lets us evaluate its exact log-full conditional (using the log-sum-exp trick for numerical stability) and draw from a categorical distribution at every Gibbs step:
(8.11)import numpy as np
# Hierarchical normal Gibbs sampler on synthetic 60-school ELS-like data
rng = np.random.default_rng(42)
m = 60
n_j = rng.integers(4, 25, size=m)
th_true = rng.normal(48.1, 4.5, size=m)
groups = [rng.normal(th, 9.2, size=nj) for th, nj in zip(th_true, n_j)]
ybar = np.array([g.mean() for g in groups])
ss_within = np.array([np.sum((g - g.mean())**2) for g in groups])
N = int(n_j.sum())
# Weakly informative hyperparameters (matching Hoff Ch. 8)
mu0, g20 = 50.0, 25.0
eta0, t20 = 1.0, 100.0
nu0, s20 = 1.0, 100.0
S = 4_000
mu_s, tau2_s, sig2_s = np.empty(S), np.empty(S), np.empty(S)
theta_s = np.empty((S, m))
th_cur, mu_cur, t2_cur, s2_cur = ybar.copy(), ybar.mean(), np.var(ybar, ddof=1), 85.0
for s in range(S):
# 1. Vectorized full conditional for all m group means theta_j
v_j = 1.0 / (n_j / s2_cur + 1.0 / t2_cur)
m_j = v_j * (n_j * ybar / s2_cur + mu_cur / t2_cur)
th_cur = rng.normal(m_j, np.sqrt(v_j))
# 2. Grand mean mu | theta, tau^2
v_mu = 1.0 / (m / t2_cur + 1.0 / g20)
m_mu = v_mu * (m * th_cur.mean() / t2_cur + mu0 / g20)
mu_cur = rng.normal(m_mu, np.sqrt(v_mu))
# 3. Between-group variance tau^2 | theta, mu
t2_cur = 1.0 / rng.gamma((eta0 + m) / 2.0,
2.0 / (eta0 * t20 + np.sum((th_cur - mu_cur)**2)))
# 4. Within-group variance sigma^2 | theta, y (fast O(m) sum of squares)
sse = np.sum(ss_within + n_j * (ybar - th_cur)**2)
s2_cur = 1.0 / rng.gamma((nu0 + N) / 2.0, 2.0 / (nu0 * s20 + sse))
theta_s[s], mu_s[s], tau2_s[s], sig2_s[s] = th_cur, mu_cur, t2_cur, s2_cur
th_hat = theta_s[500:].mean(axis=0)
print(f"Posterior means: mu={mu_s[500:].mean():.2f}, tau={np.sqrt(tau2_s[500:]).mean():.2f}, "
f"sigma={np.sqrt(sig2_s[500:]).mean():.2f}")
print(f"Total MSE vs truth: unpooled={np.mean((ybar - th_true)**2):.2f}, "
f"hierarchical={np.mean((th_hat - th_true)**2):.2f}")8.5Modern Developments: Complexity Priors, Assisted Intervals, and Ranking#
8.5.1Penalized Complexity Priors#
A penalized complexity (PC) prior derives the prior on from how far the hierarchical model departs from complete pooling.Beyond Hoff (2009). This material is not in Hoff’s book; Simpson et al. (2017) supply a general construction that complements the half- advice for .Daniel Simpson, Håvard Rue, Andrea Riebler, Thiago G. Martins, and Sigrunn H. Sørbye. Penalising Model Component Complexity: A Principled, Practical Approach to Constructing Priors. Statistical Science, 32(1):1–28, 2017. doi: 10.1214/16-STS576 Take as the simple base model, measure departure by , and put a constant-rate (exponential) prior on . Approaching the base through with ,
(8.12)where encodes one interpretable statement, . Distance is proportional to , and the constant is absorbed into .
Compare (8.2) with , , under which and : the prior virtually forbids strong pooling. Taking gives and , with its density maximal, rather than vanishing, at .
When to use it. With schools the choice hardly matters. For small (see Remark 8.3), or several variance components needing comparable scaling, prefer the PC prior; the update (8.6) is then no longer conjugate, so draw by a one-dimensional slice or Metropolis step.
8.5.2Frequentist-Assisted Bayes Confidence Intervals#
FAB intervals borrow strength across groups, yet cover each with exactly the nominal frequency.Beyond Hoff (2009). This material is not in Hoff’s book; Yu and Hoff himself (2018) develop it, extending an older idea of Pratt to adaptive multigroup intervals.C Yu and P D Hoff. Adaptive multigroup confidence intervals with constant coverage. Biometrika, 105(2):319–335, 2018. doi: 10.1093/biomet/asy009 The credible interval centered at (8.8) covers only on average over , undercovering schools far from . With known, split the test error unevenly as below and above, with depending on the tested :
(8.13)Every test has level for any , so coverage is exactly at every , even if the prior is wrong, provided are estimated independently of —for instance, from the other schools. The stated minimizes expected length under the prior: equating the ratio of the to the marginal density at both endpoints of the acceptance region puts its midpoint at . As , recovers the usual -interval.
For School 82 (plug-in , , ) the -interval is , FAB gives , and the credible interval is .
When to use it. Report Hoff’s credible intervals for prior-averaged accuracy; choose FAB when every group must be covered at the nominal rate. Unknown calls for the -version.
8.5.3Ranking as a Compound Decision and the NPMLE#
Ranking schools is a decision problem with its own loss, and the posterior mean need not be the right ranking score.Beyond Hoff (2009). This material is not in Hoff’s book; Gu and Koenker (2023) treat ranking and selection as compound decisions, while the nonparametric MLE—an idea from the 1950s—became routinely computable through the convex optimization of Koenker and Mizera (2014).Jiaying Gu and Roger Koenker. Invidious Comparisons: Ranking and Selection as Compound Decisions. Econometrica, 91(1):1–41, 2023. doi: 10.3982/ECTA19304; and Roger Koenker and Ivan Mizera. Convex Optimization, Shape Constraints, Compound Decisions, and Empirical Bayes Rules. Journal of the American Statistical Association, 109(506):674–685, 2014. doi: 10.1080/01621459.2013.869224 Suppose we flag a fraction of schools as belonging to the lowest of the population, with and the -quantile of . Subject to a cap on the number flagged, the expected number of correct flags is maximized by thresholding the posterior tail probability
(8.14)because the expected number of correct flags is the sum of the flagged , so one should take the largest. With equal this agrees with ranking by (8.8); with unequal it need not.
Revisit the reversal of Schools 46 and 82, whose plug-in posteriors are and . For the lowest decile (), for School 46 and for School 82, agreeing with the posterior means. For the lowest (), against : School 82’s wider posterior puts it first, reversing the reversal.
Normality of matters in such tails. The NPMLE is a convex problem with a discrete solution, and replaces in (8.14).
When to use it. Hoff’s posterior means suit squared-error estimation. To select or rank, use at the cutoff that matters, with when is large and normality doubtful.
8.5.4Computational & Symbolic Check#
The script checks the PC tail statement below (8.12), solves (8.13) for School 82, and simulates the coverage of FAB and credible intervals at fixed values of .Beyond Hoff (2009). This computational check and its Wolfram symbolic counterpart below verify the modern methods in this section and are not in Hoff’s book.
import numpy as np
from scipy import optimize, stats
U, al, rng, q = 10.0, 0.05, np.random.default_rng(8), stats.norm.ppf
lam = -np.log(al) / U
tau = rng.exponential(1 / lam, size=1_000_000) # NumPy scale = 1/rate
print(f"PC: lambda = {lam:.4f}, Pr(tau > U) = {np.mean(tau > U):.4f}, Pr(tau < 3) = {np.mean(tau < 3):.4f}")
mu, t, s, yb = 48.1, 5.0, 9.2 / np.sqrt(5), 38.76
def w(th): # optimal split of the test error alpha at the tested value th
return optimize.brentq(lambda x: q(al * x) - q(al * (1 - x)) - 2 * s * (th - mu) / t**2, 1e-15, 1 - 1e-15)
lo = optimize.brentq(lambda th: yb + s * q(al * (1 - w(th))) - th, 30, 60)
hi = optimize.brentq(lambda th: yb - s * q(al * w(th)) - th, 30, 60) # -q(p) = q(1 - p)
print(f"School 82 FAB interval: [{lo:.1f}, {hi:.1f}]")
B = t**2 / (t**2 + s**2)
for th in (35.0, 48.1, 60.0):
Y, wt = rng.normal(th, s, size=400_000), w(th)
fab = (Y + s * q(al * (1 - wt)) <= th) & (th <= Y - s * q(al * wt))
cred = np.abs(B * Y + (1 - B) * mu - th) <= q(1 - al / 2) * np.sqrt(B) * s
print(f"theta = {th}: coverage FAB {fab.mean():.4f}, credible {cred.mean():.4f}")// Chapter 8 (modern): exact PC-prior tail probability & exact FAB coverage
const pcTail = await show`Assuming[lam > 0 && u > 0, Integrate[lam*Exp[-lam*x], {x, u, Infinity}]]`await show`Simplify[${pcTail} /. lam -> -Log[al]/u]`await show`N[{lam, 1 - (${pcTail} /. u -> 3)} /. lam -> -Log[5/100]/10]`// Normal quantile: Phi^(-1)(p) = -Sqrt[2]*InverseErfc[2*p]
const qLo = await show`-Sqrt[2]*InverseErfc[2*al*(1 - w)]`const qHi = await show`-Sqrt[2]*InverseErfc[2*(1 - al*w)]`await show`FullSimplify[1/2*Erfc[-(${qHi})/Sqrt[2]] - 1/2*Erfc[-(${qLo})/Sqrt[2]]]`await show`Simplify[(-Sqrt[2]*InverseErfc[2*al*w] + Sqrt[2]*InverseErfc[2*al*(1 - w)]) /. w -> 1/2]`8.6Symbolic Check in Wolfram Language#
Derives the two-group prior correlation from , the shrinkage weight , the symbolic shrunk-mean gap governing ranking reversals between two groups and , and (non-circularly from the log-density derivative) both the shape and -scaled rate of , then evaluates plug-in shrinkage on Schools 46 and 82 (compare Hoff’s full MCMC means and ).
Push through to get the prior covariance of the two group means.// Chapter 8: Symbolic two-group correlation, ranking-reversal condition & sigma_0^2 full conditional
const A = [[1, 1], [1, -1]]
const cov2 = await show`${A} . DiagonalMatrix[{g0^2, t0^2}] . Transpose[${A}]`await show`Together[${cov2}[[1, 2]] / ${cov2}[[1, 1]]]`// Shrinkage weight B_j and symbolic shrunk-mean gap thetaHat_2 - thetaHat_1
const Bj = await show`Together[(nj / s2) / (nj / s2 + 1 / t2)]`const gapSym = await show`FullSimplify[((${Bj} /. nj -> n2)*yb2 + (1 - (${Bj} /. nj -> n2))*mu)
- ((${Bj} /. nj -> n1)*yb1 + (1 - (${Bj} /. nj -> n1))*mu)]`// Non-circular derivation of sigma_0^2 full conditional shape & rate (m = 3)
const logp = await show`(a - 1)*Log[s0] - b*s0 + Sum[nu0/2*Log[nu0*s0/2] - LogGamma[nu0/2]
+ (nu0/2 - 1)*Log[x] - nu0*s0*x/2, {x, {x1, x2, x3}}]`const dLogp = await show`Expand[D[${logp}, s0]]`await show`Simplify[1 + Coefficient[${dLogp}, s0, -1]]`await show`Simplify[-Coefficient[${dLogp}, s0, 0]]`// Instantiate plug-in shrinkage on School 46 (n1=21, yb1=40.18) vs School 82 (n2=5, yb2=38.76)
await show`N[Table[{w, w*p[[2]] + (1 - w)*48.1} /. w -> (${Bj} /. {nj -> p[[1]], t2 -> 25, s2 -> 84.64}), {p, {{21, 40.18}, {5, 38.76}}}]]`await show`N[${gapSym} /. {n1 -> 21, yb1 -> 40.18, n2 -> 5, yb2 -> 38.76, mu -> 48.1, t2 -> 25, s2 -> 84.64}]`8.7Exercises#
Exercise 8.4. In the Python script above, vary the true between-school standard deviation while holding fixed. Compare the total estimation MSE of the hierarchical posterior mean against both the unpooled sample means and the completely pooled grand mean . When is the gain from partial pooling largest?
Symbolic Solution & Instantiation
Simplify the oracle hierarchical Bayes risk (MSE) for equal group sizes .// Ex 8.1: Oracle Bayes risk (MSE, equal n) of unpooled, completely pooled, and hierarchical partial pooling
const rPart = await show`FullSimplify[(s2/n)*t2 / (s2/n + t2)]`await show`FullSimplify[${rPart} / (s2/n)]`await show`FullSimplify[${rPart} / t2]`// Instantiate {unpooled, pooled, hierarchical} MSE at s2 = 84.64, n = 10 for tau in {1, 3, 5, 15}
await show`N[Table[{s2/n, tau^2, ${rPart} /. t2 -> tau^2} /. {s2 -> 84.64, n -> 10}, {tau, {1, 3, 5, 15}}]]`Exercise 8.5. Extend the Python Gibbs sampler to allow heterogeneous school variances using (8.10) and (8.11) over the grid (remembering to subtract log_p.max() before exponentiating when normalizing ). Verify that the factor in the rate of (8.10) is required by checking whether your sampler recovers known synthetic values .
Symbolic Solution & Instantiation
Compute the posterior mean of under the correct full-conditional rate .// Ex 8.2: Bias of omitting nu0 in the full conditional rate of sigma_0^2 (plugging in sum sigma_j^{-2} = m / sigma_0^2)
const meanCorrect = await show`FullSimplify[(a + m*nu0/2) / (b + (nu0/2)*m/s0True)]`const meanBuggy = await show`FullSimplify[(a + m*nu0/2) / (b + (1/2)*m/s0True)]`await show`Assuming[nu0 > 0 && s0True > 0, Limit[${meanBuggy} / ${meanCorrect}, m -> Infinity]]`await show`N[{${meanCorrect}, ${meanBuggy}, ${meanBuggy}/${meanCorrect}} /. {a -> 1, b -> 1/100, m -> 100, nu0 -> 10, s0True -> 80}]`Exercise 8.6. Simulate groups with , , and very small true between-group spread . Compare the lag-1 autocorrelation and of under (a) the centered Gibbs sampler Proposition 8.2 and (b) the non-centered reparameterization (see Remark 8.3).
Symbolic Solution & Instantiation
Derive the posterior correlation across groups under centered parameterization.// Ex 8.3: Centered posterior coupling across m groups & centered mu-chain lag-1 ACF at fixed tau
const corrCent = await show`FullSimplify[Sqrt[(s2/nj) / (s2/nj + m*t2)]]`const acfMu = await show`FullSimplify[(s2/nj) / (s2/nj + t2)]`await show`N[{${corrCent}, ${acfMu}} /. {s2 -> 100, nj -> 5, m -> 8, t2 -> 1/4}]`