Module contents
Lesson 24 of 27Core 120 min

Bayesian hierarchical models

Hierarchical models learn how much to pool across groups by sharing a distribution over group-level parameters. Study de Finetti’s theorem, partial pooling, priors for scales, the funnel geometry and noncentered parameterization, multilevel regression, and horseshoe and spike-and-slab priors for sparse regression.

After this lesson you can

  • Use exchangeability and de Finetti’s theorem to motivate a hierarchical model.
  • Compute shrinkage of group estimates and relate it to the James–Stein estimator.
  • Choose priors for hierarchical scales and check them with the prior predictive distribution.
  • Diagnose a funnel and address it with a noncentered parameterization.
  • Fit multilevel regression with varying intercepts and slopes in a probabilistic programming language.
  • Fit sparse regression with a regularized horseshoe and compare it with lasso and ARD.

Before you start

Sharing information across groups

When each group has little data, fitting each separately can produce noisy estimates; forcing the same parameter can hide real differences. A hierarchical model places group parameters under a common distribution and learns or specifies its hyperparameters. In the historical eight schools, the data are estimates and standard errors from eight exam-preparation experiments, not eight individual observations. Values come from the Stan documented example.

For yj∣θj∼N(θj,σj2)y_j\mid\theta_j\sim\Normal(\theta_j,\sigma_j^2) and θj∣μ,τ∼N(μ,τ2)\theta_j\mid\mu,\tau\sim\Normal(\mu,\tau^2), with μ\mu and τ\tau known,

E[θj∣yj,μ,τ]=(1−Bj)yj+Bjμ,Bj=σj2σj2+τ2.\E[\theta_j\mid y_j,\mu,\tau]=(1-B_j)y_j+B_j\mu,\qquad B_j=\frac{\sigma_j^2}{\sigma_j^2+\tau^2}.

Partial pooling shrinks groups with larger measurement error more. When τ→0\tau\to0 all share μ\mu; when τ→∞\tau\to\infty it approaches the separate fit. If μ\mu and τ\tau are uncertain, the full posterior mean integrates this uncertainty: substituting a point estimate without saying so is insufficient. The figure integrates μ∼N(0,102)\mu\sim\Normal(0,10^2) conditional on τ\tau and uses τ∼HalfNormal⁡(5)\tau\sim\operatorname{HalfNormal}(5) for its marginal curve, calculated on a grid truncated to [0,30].

InteractiveThe eight schools
Horizontal axis: estimated effect. Blue point: observation; orange: conditional posterior mean. Each line joins the two values.
Marginal posterior of τ, integrating μ and with a half-normal(5) prior
Pooling
5.0
Conditional population mean6.53
Move τ, observe each shrinkage and compare with the no-pooling limit. Below is the marginal posterior of τ with the stated priors; the upper means condition on the selected value.

Exchangeability and shrinkage

A sequence is exchangeable if any finite permutation preserves its joint distribution. De Finetti’s theorem represents an infinitely exchangeable sequence as a mixture of conditionally independent and identically distributed sequences, under appropriate assumptions. It does not say that every finite exchangeable set has exactly this representation, or that groups are identical after their data are known. Group covariates and systematic differences may require a common distribution conditioned on those covariates.

Shrinkage introduces bias relative to each separate estimate but can reduce its variance and total squared error. The James–Stein result shows an advantage under specific assumptions for normal means in dimension at least three; it does not claim that every prior or hierarchical rule improves every group and dataset. Empirical Bayes estimates and fixes hyperparameters; full Bayes integrates their posterior. With few groups, a point estimate τ^=0\hat\tau=0 can convey certainty that the full analysis does not have.

Scales and geometry

Hierarchical scale priors should be chosen in the problem’s units. Half-normal or half-t distributions can express plausible scales; an inverse-gamma with small parameters is not automatically innocuous and can behave undesirably near zero or in the tails. An improper uniform prior does not itself define a prior predictive distribution; to simulate it one must make it proper, for example by truncating it. In the figure [−5,5] is a hypothetical reference, not a universal rule of plausibility.

InteractiveUninformative priors that are not
Prior for τ
5th percentile−1.48
95th percentile1.56
Outside [−5,5]0.4 %
Group values are simulated from three scale priors, including a uniform truncated to [0,100]. Changing units or context changes which values are plausible.

In the centered form, θj∼N(μ,τ)\theta_j\sim\Normal(\mu,\tau) narrows as τ\tau approaches zero and can create a funnel. The non-centered parameterization uses zj∼N(0,1)z_j\sim\Normal(0,1) and θj=μ+τzj\theta_j=\mu+\tau z_j: it represents the same distribution but changes the geometry seen by the integrator. It often helps with weak data; with very informative data, centering or an intermediate strategy may be preferable.

InteractiveFrom the funnel to another geometry
  • State
  • Divergent transition
Parameterization
Divergences45
Outside window0
Samples2000
Two custom HMC chains on the eight schools use the same model and priors. Log τ is shown against θ₁ or z₁, with divergent transitions marked; each chain is short and does not demonstrate convergence.

Group lines and global-local priors

A multilevel regression can give each group an intercept and slope, with bj∼N(μ,Σ)\vb b_j\sim\Normal(\vb\mu,\mat\Sigma). An Σ=DRD\mat\Sigma=\mat D\mat R\mat D decomposition separates scales from the correlation matrix; an LKJ prior can regularize R\mat R. If a group has little predictor variation, its slope will be especially hard to identify. The figure uses synthetic data, fixed residual and group scales, and a population line estimated by complete pooling: this illustrates empirical Bayes, not a full Bayesian fit.

InteractiveLines that shrink
  • Group 1
  • Group 2
  • Group 3
  • Group 4
Model
1
Group data3
Displayed intercept−0.05
Displayed slope1.18
Compare complete, no and partial pooling. Only the selected group's points are shown; group sizes are 3, 5, 12 and 35.

In sparse regression, a Laplace prior yields lasso as MAP under an appropriate parameterization, but a MAP does not summarize the posterior. Spike-and-slab combines a part concentrated near zero and a wide part. Global-local priors give each coefficient a local scale λj\lambda_j in addition to the global scale τ\tau. The classical horseshoe uses half-Cauchy scales and can shrink noise strongly without imposing the same degree of shrinkage on large signals. The regularized horseshoe limits the spread of large signals with a finite slab; calibration requires considering noise, sample size and expected sparsity.

InteractiveHow much each prior shrinks
  • Normal: mean
  • Laplace: MAP
  • Horseshoe: mean
0.5
Horseshoe mean for y = 43.35
Normal problem with noise σ=1. The normal and horseshoe curves are posterior means; the Laplace curve is MAP, not a mean. The half-Cauchy local scale is integrated numerically.

For a particular local scale, κj=1/(1+τ2λj2)\kappa_j=1/(1+\tau^2\lambda_j^2) is the shrinkage fraction of the normal mean conditional on that scale. In the full horseshoe λj\lambda_j is uncertain and also integrated out; the figure calculates that mean by quadrature.

Labs

Eight schools with custom HMC

This lab uses the HMC from m14-l23, identity mass, μ∼N(0,102)\mu\sim\Normal(0,10^2) and τ∼HalfNormal⁡(5)\tau\sim\operatorname{HalfNormal}(5). We sample s=log⁡τs=\log\tau and include the Jacobian +s+s; the centered version also includes the normalization of the eight conditional normals. Each parameterization uses a short chain, 600 adaptation steps and 2000 saved draws. We define a divergence operationally as ∣ΔH∣>1000|\Delta H|>1000 or non-finite energy; it is not identical to every library diagnostic.

[ ]Eight schools HMC and gradientsBrowser
import numpy as np
def leapfrog(grad_logp,q,p,eps,L):
    q=q.copy();p=p.copy();p+=.5*eps*grad_logp(q)
    for i in range(L):
        q+=eps*p
        if i<L-1:p+=eps*grad_logp(q)
    p+=.5*eps*grad_logp(q)
    return q,p

def hmc(logp,grad,start,seed,warmup=500,draws=1000,L=8,eps0=.05,target=.8):
    rng=np.random.default_rng(seed);q=np.array(start,dtype=float);logs=np.log(eps0);mu=np.log(10*eps0);bar=0.;logavg=logs;out=[];accept=[];energies=[]
    for t in range(1,warmup+draws+1):
        p=rng.normal(size=q.size);H0=-logp(q)+.5*(p@p)
        prop,p1=leapfrog(grad,q,p,np.exp(logs),L);H1=-logp(prop)+.5*(p1@p1)
        delta=H1-H0;prob=np.exp(min(0.,-delta)) if np.isfinite(delta) else 0.
        if rng.random()<prob:q=prop
        if t<=warmup:
            bar=(1-1/(t+10))*bar+(target-prob)/(t+10)
            logs=np.clip(mu-np.sqrt(t)*bar/.05,-10,2)
            weight=t**(-.75);logavg=weight*logs+(1-weight)*logavg
            if t==warmup:logs=logavg
        else:out.append(q.copy());accept.append(prob);energies.append(delta)
    return np.array(out),np.mean(accept),np.exp(logs),np.array(energies)

def ess(x):
    x=x-x.mean();n=len(x);size=1<<(2*n-1).bit_length();f=np.fft.rfft(x,n=size);a=np.fft.irfft(f*np.conjugate(f),n=size)[:n];rho=a/a[0];pairs=[]
    for i in range(0,n-1,2):
        pair=rho[i]+rho[i+1]
        if pair<0:break
        pairs.append(min(pair,pairs[-1]) if pairs else pair)
    return n/max(1/np.log10(n),-1+2*sum(pairs))

y=np.array([28,8,-3,7,-1,1,18,12],float);sigma=np.array([15,10,16,11,9,11,10,18],float)

def log_center(q):
    mu,s=q[:2];theta=q[2:]
    if abs(s)>50:return -np.inf
    return -.5*np.sum(((y-theta)/sigma)**2)-.5*np.sum((theta-mu)**2)*np.exp(-2*s)-7*s-.5*(mu/10)**2-np.exp(2*s)/50
def grad_center(q):
    mu,s=q[:2];theta=q[2:]
    if abs(s)>50:return np.full_like(q,np.nan)
    u=theta-mu;inv=np.exp(-2*s)
    return np.r_[u.sum()*inv-mu/100,-7+np.sum(u*u)*inv-np.exp(2*s)/25,(y-theta)/sigma**2-u*inv]
def log_noncenter(q):
    mu,s=q[:2];z=q[2:]
    if abs(s)>50:return -np.inf
    tau=np.exp(s);theta=mu+tau*z
    return -.5*np.sum(((y-theta)/sigma)**2)-.5*np.sum(z*z)-.5*(mu/10)**2-tau*tau/50+s
def grad_noncenter(q):
    mu,s=q[:2];z=q[2:]
    if abs(s)>50:return np.full_like(q,np.nan)
    tau=np.exp(s);err=(y-mu-tau*z)/sigma**2
    return np.r_[err.sum()-mu/100,1-tau*tau/25+np.sum(err*tau*z),-z+err*tau]
from scipy.optimize._numdiff import approx_derivative
for name,f,g,q in [('centrada',log_center,grad_center,np.r_[1.,np.log(3.),np.linspace(-2,2,8)]),('no centrada',log_noncenter,grad_noncenter,np.r_[1.,np.log(3.),np.linspace(-1,1,8)])]:
    print(name,'error de gradiente',np.max(np.abs(approx_derivative(f,q)-g(q))))
[ ]CenteredBrowser
q0=np.r_[0.,np.log(5.),np.zeros(8)]
a,prob,step,energy=hmc(log_center,grad_center,q0,241,warmup=600,draws=2000,L=10,eps0=.04)
tau=np.exp(a[:,1]);mu=a[:,0];theta=a[:,2:]
expected=(tau[:,None]**2*y+sigma**2*mu[:,None])/(sigma**2+tau[:,None]**2)
print('ESS tau',ess(tau),'probabilidad media aceptación',prob,'paso',step,'divergencias',np.sum((~np.isfinite(energy))|(np.abs(energy)>1000)))
print('media theta muestreada',theta.mean(0),'media condicional promediada',expected.mean(0))
[ ]Non-centeredBrowser
a,prob,step,energy=hmc(log_noncenter,grad_noncenter,q0,241,warmup=600,draws=2000,L=10,eps0=.04)
tau=np.exp(a[:,1]);mu=a[:,0];theta=mu[:,None]+tau[:,None]*a[:,2:]
expected=(tau[:,None]**2*y+sigma**2*mu[:,None])/(sigma**2+tau[:,None]**2)
print('ESS tau',ess(tau),'probabilidad media aceptación',prob,'paso',step,'divergencias',np.sum((~np.isfinite(energy))|(np.abs(energy)>1000)))
print('media theta muestreada',theta.mean(0),'media condicional promediada',expected.mean(0))

Comparing conditional means with sampled means is a Monte Carlo check, not an exact equality in a finite chain. Both parameterizations represent the same posterior; differences in ESS or divergences show behavior in these runs and can change with initialization, mass or adaptation.

Radon: county lines with PyMC

The radon.csv file from the PyMC examples repository contains 919 Minnesota observations and 85 counties in the checked version. The local cell needs a connection to download it and checks its SHA-256 before use. Log radon is fit against floor, with county intercepts and slopes, a non-centered joint distribution and LKJ correlation. Three splits hold out houses within counties already seen; the three counties with a single observation always remain in training. This is not an evaluation on new counties.

Baselines are a common line and county lines with ridge 0.01 for cases with little floor variation. The partial version uses PyMC 6.4, two chains of 200 warmup steps and 200 draws per split. We compare weighted MSEs across the three test sets and distances of intercepts from the common line by group size; divergences and R-hat for μ\mu and σ\sigma are printed. In the checked run the maximum of those R-hats per split was 1.011, 1.049 and 1.027, respectively; increase the budget and also check the other parameters. This short run establishes neither convergence nor a general ranking of models. PyTensor used the available backend without a C++ compiler.

[ ]Radon: split validationLocal GPU
import io,hashlib,time
import numpy as np,pandas as pd,pymc as pm,arviz as az
from sklearn.linear_model import LinearRegression,Ridge
from sklearn.metrics import mean_squared_error

raw=pm.get_data('radon.csv').read()
digest=hashlib.sha256(raw).hexdigest()
if digest!='4101a87aa11d161b2eb85cb65bdc8a09cb3eddadbd4d34078a4e0329b3df8c77':
    raise RuntimeError('El archivo fuente ha cambiado; revisar procedencia y resultados antes de continuar')
data=pd.read_csv(io.BytesIO(raw)).dropna(subset=['county','floor','log_radon']).copy()
codes,names=pd.factorize(data['county'],sort=True);floor=data['floor'].to_numpy(float);y=data['log_radon'].to_numpy(float);G=len(names)
print('rows counties sha256',len(y),G,hashlib.sha256(raw).hexdigest())
rng=np.random.default_rng(2424);fold=np.full(len(y),-1,dtype=int)
for g in range(G):
    ids=np.flatnonzero(codes==g)
    if len(ids)>1:
        ids=rng.permutation(ids);fold[ids]=np.arange(len(ids))%3
        if len(ids)==2:fold[ids]=[0,1]

results=[]
for f in range(3):
    test=fold==f;train=~test
    overall=LinearRegression().fit(floor[train,None],y[train]);p_pool=overall.predict(floor[test,None])
    p_none=np.empty(test.sum());idx_test=np.flatnonzero(test);separate_intercept=np.empty(G);sizes=np.bincount(codes[train],minlength=G)
    for g in range(G):
        tr=train&(codes==g);idx=np.flatnonzero(codes[idx_test]==g)
        model=Ridge(alpha=.01).fit(floor[tr,None],y[tr]);separate_intercept[g]=model.intercept_
        if len(idx):p_none[idx]=model.predict(floor[idx_test[idx],None])
    with pm.Model() as model:
        mu=pm.Normal('mu',mu=0,sigma=[3,2],shape=2)
        chol,corr,std=pm.LKJCholeskyCov('chol',n=2,eta=2,sd_dist=pm.HalfNormal.dist(1),compute_corr=True)
        z=pm.Normal('z',0,1,shape=(G,2));effects=pm.Deterministic('effects',mu+pm.math.dot(z,chol.T))
        sigma=pm.HalfNormal('sigma',1)
        pred=effects[codes[train],0]+effects[codes[train],1]*floor[train]
        pm.Normal('obs',mu=pred,sigma=sigma,observed=y[train])
        start=time.perf_counter();fit=pm.sample(draws=200,tune=200,chains=2,cores=1,random_seed=2424+f,target_accept=.9,progressbar=False,compute_convergence_checks=False)
    a=fit['posterior']['effects'].values.mean(axis=(0,1));p_part=a[codes[test],0]+a[codes[test],1]*floor[test]
    mse=[mean_squared_error(y[test],p) for p in (p_pool,p_none,p_part)]
    div=int(fit['sample_stats']['diverging'].values.sum())
    results.append((int(test.sum()),mse,div))
    rh=az.rhat(fit,var_names=['mu','sigma'],method='rank');maxrh=max(float(rh['mu'].values.max()),float(rh['sigma'].values))
    print('fold',f,'test',test.sum(),'MSE pooled, separate, partial',np.round(mse,4),'divergences',div,'max Rhat mu/sigma',round(maxrh,3),'seconds',round(time.perf_counter()-start,1))
    for low,high in [(1,3),(4,9),(10,10000)]:
        mask=(sizes>=low)&(sizes<=high)
        print('training group size',low,'to',high,'groups',mask.sum(),'mean |intercept - pooled| separate / partial',np.mean(abs(separate_intercept[mask]-overall.intercept_)),np.mean(abs(a[mask,0]-overall.intercept_)))
print('weighted MSE',np.average(np.array([r[1] for r in results]),axis=0,weights=[r[0] for r in results]))
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Regularized horseshoe, lasso and ARD

The local experiment generates n=200n=200 observations with p=200p=200 independent normal variables, ten known relevant coefficients, normal noise with standard deviation 1 and 500 independent test examples, using seed 2426. The known generating sparsity is used to calibrate the prior’s initial global scale: this is privileged information in this simulation. The slab has fixed scale 2. The horseshoe is continuous; to compare support recovery the arbitrary threshold ∣β^j∣>0.2|\hat\beta_j|>0.2 is applied to the means, and is not an inclusion probability. Lasso uses three-fold cross-validation and ARD uses the scikit-learn estimator.

NUTS uses two chains with 150 adaptation steps and 150 saved draws, with maximum allowed depth 9. In the checked run there were 0 divergences, no transition hit the depth limit and the highest coefficient R-hat was approximately 1.037: too high to consider exploration complete. This comparison is a short test on one synthetic dataset, not evidence of superiority; increase chains and budget and check diagnostics before interpreting parameters.

[ ]Regularized horseshoe, lasso and ARDLocal GPU
import time
import numpy as np,pymc as pm,arviz as az
from sklearn.linear_model import LassoCV,ARDRegression
from sklearn.metrics import mean_squared_error,precision_recall_fscore_support

rng=np.random.default_rng(2426);n,p,active=200,200,10
X=rng.normal(size=(n,p));Xt=rng.normal(size=(500,p));truth=np.zeros(p)
idx=rng.choice(p,size=active,replace=False);truth[idx]=rng.choice([-1.,1.],size=active)*rng.uniform(1.5,2.5,size=active)
y=X@truth+rng.normal(size=n);yt=Xt@truth+rng.normal(size=500)
def score(name,coef,seconds,div=0,intercept=0.):
    support=np.abs(coef)>.2;real=truth!=0
    precision,recall,f1,_=precision_recall_fscore_support(real,support,average='binary',zero_division=0)
    print(name,'test MSE',mean_squared_error(yt,Xt@coef+intercept),'coef RMSE',np.sqrt(np.mean((coef-truth)**2)),
          'precision recall F1',precision,recall,f1,'selected',support.sum(),'divergences',div,'seconds',seconds)

start=time.perf_counter();lasso=LassoCV(cv=3,random_state=1).fit(X,y);score('lasso',lasso.coef_,time.perf_counter()-start,intercept=lasso.intercept_)
start=time.perf_counter();ard=ARDRegression().fit(X,y);score('ARD',ard.coef_,time.perf_counter()-start,intercept=ard.intercept_)
tau0=(active/(p-active))/np.sqrt(n)
with pm.Model() as model:
    tau=pm.HalfCauchy('tau',beta=tau0);lam=pm.HalfCauchy('lam',beta=1,shape=p)
    z=pm.Normal('z',0,1,shape=p);slab=2.
    scale=tau*lam*pm.math.sqrt(slab**2/(slab**2+tau**2*lam**2))
    coef=pm.Deterministic('coef',z*scale);sigma=pm.HalfNormal('sigma',1)
    pm.Normal('obs',mu=pm.math.dot(X,coef),sigma=sigma,observed=y)
    start=time.perf_counter();step=pm.NUTS(target_accept=.9,max_treedepth=9)
    fit=pm.sample(draws=150,tune=150,chains=2,cores=1,step=step,random_seed=[2426,2427],progressbar=False,compute_convergence_checks=False)
    elapsed=time.perf_counter()-start
posterior=fit['posterior']['coef'].values.mean(axis=(0,1));div=int(fit['sample_stats']['diverging'].values.sum())
score('horseshoe',posterior,elapsed,div)
depth=fit['sample_stats']['tree_depth'].values
print('prior tau0',tau0,'max tree depth',int(depth.max()),'at limit',int((depth>=9).sum()),'max Rhat',float(az.rhat(fit,var_names=['coef'])['coef'].values.max()),'min ESS bulk',float(az.ess(fit,var_names=['coef'])['coef'].values.min()),'true indices',sorted(idx.tolist()))
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Exercises

NumericNormal shrinkage
With group standard error σj=15\sigma_j=15 and between-group deviation τ=10\tau=10, what is Bj=σj2/(σj2+τ2)B_j=\sigma_j^2/(\sigma_j^2+\tau^2)?
NumericConditional shrinkage
With noise σ=1\sigma=1, local scale λ=3\lambda=3 and global scale τ=0.1\tau=0.1, calculate κ=1/(1+λ2τ2)\kappa=1/(1+\lambda^2\tau^2).
QuizWhat de Finetti guarantees
What is the scope of de Finetti’s representation theorem?
QuizAn apparently vague prior
Why should an inverse-gamma(ε, ε) for a hierarchical variance not be used without examination?
ProofPrecision-weighted mean
Prove: With μ\mu and τ\tau known, the posterior mean of θj\theta_j is a weighted mean of yjy_j and μ\mu.
0
Use a normal likelihood with variance σj2\sigma_j^2 and a normal prior with variance τ2\tau^2.

Step 1 of 2. What is the posterior precision?

CodeNon-centered log posterior
Implement logp_grad(q, y, sigma) for the eight schools with q = [mu, s, z1, ..., z8], tau = exp(s), mu ~ Normal(0,10), tau ~ HalfNormal(5), z ~ Normal(0,1) and y_j ~ Normal(mu + tau*z_j, sigma_j). Return the log density up to constants and the gradient with respect to q, including the Jacobian of s.
def logp_grad(q, y, sigma):
  pass
Shift+Enter to run

Summary

Key idea
The hierarchy shares information across groups and lets uncertainty about scales control how much their parameters shrink.
  • Exchangeability is a modeling assumption and shrinkage balances bias and variance.
  • Scale priors are interpreted through predictions and parameterization affects sampling geometry.
  • Global-local priors allow different shrinkage for each coefficient, but require calibration and diagnostics.

Main sources: eight schools data and model; Betancourt y Girolami, hierarchical geometry; Piironen y Vehtari, regularized horseshoe; PyMC radon example.