CPNS LabUniversity of Exeter

CPNS / An intuitive introduction

Bayesian
hierarchical models

How can we learn about a person and a population at the same time? Follow uncertainty from individual measurements to shared structure—and predictions for someone new.

Three experiments · equations explained in words · MATLAB examples included
A companion to Bayesian & variational inference

01 / From one person to a population

Similar people, different parameters

A hierarchical model learns what individuals have in common, while allowing them to differ.

In the Bayesian and variational inference introduction, we fitted an unknown parameter using a prior and uncertain data. Now imagine fitting the same model to several people. Each person has their own parameters, but those parameters may have a shared structure.

For example, a decaying response might have a different amplitude and decay rate in each person. A neural model might have different connection strengths. We want to estimate those individual differences and the population they come from.

There are three familiar ways to approach this:

No pooling

Fit each person separately. Reliable individual differences survive, but noisy estimates can be extreme.

Complete pooling

Assume everyone shares the same parameter. More data support that estimate, but real variation is excluded.

Partial pooling

Give each person a parameter, with a shared population distribution. Uncertain estimates borrow more information.

Partial pooling is not an instruction to make everyone identical. It is the consequence of a model in which individual parameters are related. How much they move towards a shared mean depends on the evidence and on the inferred amount of real variation.

Two different questions. “How different are people?” concerns between-person variation. “How uncertain is my estimate of this person?” concerns measurement and inference. A hierarchical model keeps these quantities separate.

02 / Write down the hierarchy

A prior can have its own parameters

Start with one noisy estimate per person. Let yiy_i be person ii’s observed estimate, sis_i its known measurement standard error, and θi\theta_i the underlying quantity we want to infer:

yi∣θi∼𝒩(θi,si2).y_i\mid\theta_i\sim\mathcal N(\theta_i,s_i^2).

The next level says that individual parameters come from a population with mean μ\mu and standard deviation τ\tau:

θi∣μ,τ∼𝒩(μ,τ2).\theta_i\mid\mu,\tau\sim\mathcal N(\mu,\tau^2).

We can also be uncertain about the population. Put hyperpriors on its mean and spread. For the browser examples we use:

μ∼𝒩(10,52),τ∼HalfNormal(3).\mu\sim\mathcal N(10,5^2),\qquad \tau\sim\operatorname{HalfNormal}(3).

The half-normal is a normal distribution restricted to positive values. Its argument is a scale in the same units as θ\theta, not a variance or a precision. These are illustrative priors for this synthetic problem; meaningful priors depend on the parameter’s units and plausible range.

A population model generates individual parameters, which generate observations Hyperpriors describe the population mean and spread. The population generates three separate individual parameters. Each parameter generates an observation with its own measurement noise. Inference works back from all observations to the joint posterior.POPULATION + HYPERPRIORSMean μ · spread τPerson A · θ₁Person B · θ₂Person C · θ₃Data y₁ · SE s₁Data y₂ · SE s₂Data y₃ · SE s₃

Arrows describe how the model generates data. Inference uses all the observations to learn the population and the individuals together.

The joint posterior is proportional to the likelihoods, the population distributions, and the hyperpriors:

p(θ1:N,μ,τ∣y)∝p(μ)p(τ)∏i=1Np(yi∣θi)p(θi∣μ,τ).p(\theta_{1:N},\mu,\tau\mid y)\propto p(\mu)p(\tau)\prod_{i=1}^{N}p(y_i\mid\theta_i)\,p(\theta_i\mid\mu,\tau).

The hierarchy is statistical. Its levels could be trials within sessions, sessions within people, or people within sites. This does not, by itself, imply a hierarchy of brain areas.

03 / The familiar Bayesian update

Partial pooling is precision weighting

For a moment, suppose the population mean and spread are known. Each person then has a Gaussian prior, 𝒩(μ,τ2)\mathcal N(\mu,\tau^2). We can reuse the exact update from the companion page:

mi=si−2yi+τ−2μsi−2+τ−2,Vi=1si−2+τ−2.m_i=\frac{s_i^{-2}y_i+\tau^{-2}\mu}{s_i^{-2}+\tau^{-2}},\qquad V_i=\frac{1}{s_i^{-2}+\tau^{-2}}.

An equivalent expression makes the shrinkage easy to see:

mi=μ+wi(yi−μ),wi=τ2τ2+si2.m_i=\mu+w_i(y_i-\mu),\qquad w_i=\frac{\tau^2}{\tau^2+s_i^2}.

wiw_i is the fraction of the individual-to-population difference retained. Reliable measurements have a larger wiw_i. A smaller population spread gives stronger pooling. With a very large spread, the population tells us little about any particular person.

Experiment 1 / Exact, conditional inference

Two observations of 14. Two different updates.

All six people share a fixed population prior. A and B have the same observed value, but different measurement errors.

Observed values: 14, 14, 7, 9, 12, 11.
Baseline SEs: 1, 4, 1, 2, 0.5, 3.

Individual observations and conditional posterior estimates Crosses show observations; circles show posterior means with 95 percent credible intervals. A dashed line shows the fixed population mean.
× Observed estimate● Posterior + 95% interval– – Fixed population mean
A · measurement SE 113.2080% of the difference retained
B · measurement SE 410.8020% of the difference retained
B · posterior SD1.79Uncertainty about B’s parameter

The less reliable estimate moves further towards the same population mean.

At the default values, A’s posterior mean is 13.2, while B’s is 10.8. B contributes less precise evidence, so the shared prior has more influence. Shrinkage also occurs for well-measured people; its amount is just smaller.

This experiment conditions on μ and τ. Its intervals exclude uncertainty about the population. A fully Bayesian hierarchy learns those quantities and propagates their uncertainty.

04 / Learn the shared distribution

Who sets the population mean and spread?

The group informs each person, and each person informs the group.

In the full hierarchy, μ\mu and τ\tau are unknown. A reliable individual estimate provides more information about the population. If reliable estimates differ substantially, the model supports more between-person variation. If much of the observed spread can be explained by measurement error, less genuine variation may be needed.

For this small Gaussian problem, we can integrate out each person’s parameter:

yi∣μ,τ∼𝒩(μ,τ2+si2).y_i\mid\mu,\tau\sim\mathcal N(\mu,\tau^2+s_i^2).

This expression separates two reasons observed estimates can differ: real variation, τ2\tau^2, and measurement variance, si2s_i^2. The same observed differences can support different population conclusions when their reliability changes.

Experiment 2 / Numerical full-posterior integration

Learn the population, then revisit the people

Change the synthetic data and the prior on population spread. Both the group and individual distributions are recalculated.

Learned individual parameters and population mean Individual posterior estimates include uncertainty in population parameters. A shaded band shows the population mean’s 95 percent credible interval.
× Observed estimate● Individual posterior + 95% intervalBand · uncertainty about μ
Prior and posterior density for between-person standard deviation The posterior over population spread is compared with its half-normal prior.
– – Prior on τ— Posterior on τ
Population mean · E[μ | y]—95% credible interval
Population spread · E[τ | y]—95% credible interval
Mean uncertainty · SD(μ | y)—A different quantity from population spread

The population mean is uncertain; individuals are not pulled towards a perfectly known target.

Read the individual estimates as numbers
Current Experiment 2 data and individual posterior summaries
PersonObservedSEPosterior mean95% interval

Try Reliable differences, then Noisy differences. The observed values remain the same, while their standard errors change. Also reduce the half-normal scale: with only six people, the prior on variation can influence the answer. It is part of the model, rather than a tuning parameter with no scientific meaning.

How does this browser calculate the posterior?

For any fixed τ\tau, μ\mu has a Gaussian conditional posterior. If vi=τ2+si2v_i=\tau^2+s_i^2 and the prior is 𝒩(m0,V0)\mathcal N(m_0,V_0), then

Vμ(τ)=(V0−1+∑ivi−1)−1,mμ(τ)=Vμ(τ)(V0−1m0+∑ivi−1yi).V_\mu(\tau)=\left(V_0^{-1}+\sum_i v_i^{-1}\right)^{-1},\qquad m_\mu(\tau)=V_\mu(\tau)\left(V_0^{-1}m_0+\sum_i v_i^{-1}y_i\right).

The code integrates over the remaining positive scale τ\tau on a log-spaced grid, using its half-normal prior and the marginal likelihood. The change of variable includes the Jacobian. Individual and predictive distributions are mixtures across that posterior, including uncertainty in μ\mu and τ\tau.

This is numerical integration for this particular small model. The displayed 95% intervals are equal-tail posterior quantiles, not a normal approximation formed from a mean and standard deviation. The fixed sis_i values are assumed known; estimating measurement error would add another layer.

Full Bayes and empirical Bayes. Full Bayesian inference retains a distribution over hyperparameters. A plug-in empirical Bayes approach estimates population hyperparameters from the data and uses those values to inform individuals. Both share information, but treating learned values as fixed omits a source of uncertainty. Implementations differ in how much uncertainty they retain.

05 / Connect the model to the algorithm

Hierarchical describes the model. Variational describes inference.

A hierarchical model specifies how observations, individual parameters, and population parameters depend on each other. Variational inference is one way to approximate its joint posterior. The same hierarchy could instead be analysed using quadrature, posterior sampling, or another suitable method.

For a larger problem, collect the unknowns into z=(θ1:N,μ,τ,…)z=(\theta_{1:N},\mu,\tau,\ldots) and choose an approximate distribution q(z)q(z). Fit it by maximising the evidence lower bound:

ℒ(q)=𝔼q[logp(y,z)]−𝔼q[logq(z)].\mathcal L(q)=\mathbb E_q[\log p(y,z)]-\mathbb E_q[\log q(z)].

The first term rewards distributions that put mass where the joint model fits well. The second is entropy: the approximation is fitting a distribution, not just choosing a best point. Maximising this bound is equivalent to minimising KL(q(z)∥p(z∣y))\operatorname{KL}(q(z)\,\|\,p(z\mid y)).

A simple mean-field family might separate individual factors from group and precision factors. It is computationally convenient, but it removes some posterior dependencies. Population and individual estimates are coupled in the true posterior, so this approximation can understate marginal uncertainty.

The same precision-weighted errors, at two levels

Replace the direct observation by a forward model fi(θi)f_i(\theta_i) and a population regression with design row xi⊤x_i^\top:

yi∣θi∼𝒩(fi(θi),Σyi),θi∣B,Σb∼𝒩(B⊤xi,Σb).y_i\mid\theta_i\sim\mathcal N(f_i(\theta_i),\Sigma_{y_i}),\qquad \theta_i\mid B,\Sigma_b\sim\mathcal N(B^\top x_i,\Sigma_b).

There is a data residual ei=yi−fi(θi)e_i=y_i-f_i(\theta_i), and a population residual ri=θi−B⊤xir_i=\theta_i-B^\top x_i. Holding the covariance matrices fixed, the quadratic part of the negative log posterior is

ℰ=12∑iei⊤Πyiei+12∑iri⊤Πbri+hyperprior terms.\mathcal E=\frac12\sum_i e_i^\top\Pi_{y_i}e_i+\frac12\sum_i r_i^\top\Pi_b r_i+\text{hyperprior terms}.

Here Πyi=Σyi−1\Pi_{y_i}=\Sigma_{y_i}^{-1} and Πb=Σb−1\Pi_b=\Sigma_b^{-1}. A MAP-style gradient step for an individual becomes

θi←θi+η[Ji⊤Πyiei−Πbri].\theta_i\leftarrow\theta_i+\eta\left[J_i^\top\Pi_{y_i}e_i-\Pi_b r_i\right].

The first term improves that person’s data prediction; the second improves agreement with the population model. Covariance or precision learning also needs the Gaussian log-determinant terms and hyperpriors. Minimising squared errors alone is not enough.

This step updates a point estimate. A Gaussian approximation based on local curvature adds uncertainty, but MAP plus an inverse Hessian is not automatically a complete variational Laplace algorithm. Variational Laplace also uses a variational objective and the appropriate updates for its model.

For linear Gaussian models, conjugate variational updates are often available. For nonlinear neural or behavioural models, local Gaussian approximations can be useful, while multimodality and strong nonlinearities may require richer approximations or sampling. A successful optimiser does not establish that an approximate posterior is well calibrated.

06 / Ask what you are predicting

The average person is not a new person

A precise population mean can coexist with substantial individual variation.

Estimating μ\mu asks where the population is centred. Predicting a new person’s latent parameter θnew\theta_{\mathrm{new}} also includes real between-person variation. Predicting their measurement ynewy_{\mathrm{new}} adds observation noise:

Var(θnew∣y)=Var(μ∣y)+𝔼[τ2∣y],\operatorname{Var}(\theta_{\mathrm{new}}\mid y)=\operatorname{Var}(\mu\mid y)+\mathbb E[\tau^2\mid y],
Var(ynew∣y)=Var(θnew∣y)+snew2.\operatorname{Var}(y_{\mathrm{new}}\mid y)=\operatorname{Var}(\theta_{\mathrm{new}}\mid y)+s_{\mathrm{new}}^2.

These identities apply to this scalar model with conditionally independent, zero-mean new-person deviations and known future measurement variance. More people can sharpen the group mean without making the population itself homogeneous.

Experiment 3 / Posterior prediction

Three questions, three distributions

Uses the learned posterior from Experiment 2. Change those controls to see every distribution respond.

Change the population ↑

Population mean: where is the group centred?
New person: what might their underlying parameter be?
New measurement: what might we observe?

Posterior population mean and predictive distributions Three curves compare uncertainty in the population mean with prediction for a new latent individual parameter and a future noisy measurement.
— Population mean μ– – New person θ··· New measurement y
Population mean · 95% width—Interval width
New person · 95% width—Interval width
New measurement · 95% width—Interval width

All three have the same mean in this model. Their spreads answer different questions. Predictions are for a person from the same modelled population.

For someone whose data we have already observed, use their individual posterior instead. Also consider who a “new person” is: a new site, a different clinical population, or a changed task may need a different model.

07 / Neural models and group effects

DCM + PEB is already a hierarchical model

In Dynamic Causal Modelling, each person’s generative model relates neural parameters to measured data. Parametric Empirical Bayes (PEB) then models those parameters at the group level, including group means and effects of covariates. Importantly, it uses uncertainty from the individual models, rather than treating their fitted parameters as perfectly known observations.

The population mean need not be the same for everybody. With an intercept, a group indicator, and a centred age covariate, for example,

xi⊤=[1,gi,ai],𝔼[θi∣B,xi]=B⊤xi.x_i^\top=[1,\ g_i,\ a_i],\qquad \mathbb E[\theta_i\mid B,x_i]=B^\top x_i.

The hierarchy pools residual differences around the appropriate predicted mean. It does not require shrinking a patient and a control towards one identical grand mean. The design matrix determines which systematic differences the model can represent.

Earlier idea Hierarchical extension
Prior on one parameter A population distribution over individual parameters, with its own unknown mean and variation.
Data prediction error Data errors within each person, plus deviations from the population prediction.
Precision weighting Measurement precision and between-person precision control different levels of the update.
Variational approximation An approximate joint distribution over individual, group, and precision parameters.
A fitted response curve A family of person-specific curves, related through population parameters.

The SPM PEB documentation explains the DCM-to-group workflow, Bayesian model reduction, and prediction. The browser’s scalar example illustrates a statistical principle; it is not a replacement for SPM’s DCM/PEB implementation.

A hierarchy assumes that units are suitably comparable after accounting for included predictors. Missing covariates, site effects, heavy tails, or unmodelled subgroups can make pooling misleading. Partial pooling improves estimation under useful assumptions; it does not guarantee improvement for every individual or dataset.

08 / Build, check, and extend

A reusable MATLAB framework

Start by separating the forward model from the inference machinery. The forward function produces predictions for one person. The inference function handles individual distributions, the population regression, precision updates, and convergence.

The accompanying framework uses this interface:

fit = hbayes_fit(model, subjects, X, priors, opts);

subjects contains each person’s data and inputs. X is the population design matrix. priors defines the group and precision priors. model.forward can describe a constant, a regression, or a nonlinear response.

Code + worked examples

MATLAB hierarchical Bayes framework

A generic fitting function, posterior sampling and prediction helpers, four examples, and twelve tests. No additional MATLAB toolbox is required.

Download MATLAB code ↓

The archive is included in this page and can be downloaded offline. Validation used GNU Octave 8.4; native MATLAB execution has not been checked here.

Unzip, open the matlab_hierarchical_bayes folder in MATLAB, and run:

addpath(genpath(pwd))
report = run_tests();
examples = run_examples(true);

For a small Gaussian summary-data problem, the model definition is just:

y = [14, 14, 7, 9, 12, 11];
s = [1, 4, 1, 2, 0.5, 3];
subjects = cell(numel(y), 1);
for i = 1:numel(y)
    subjects{i} = struct('y', y(i), 'covariance', s(i)^2);
end

model.forward = @(theta, subject) theta(1) + zeros(size(subject.y));
model.jacobian = @(theta, subject) ones(numel(subject.y), 1);
model.isLinear = true;

X = ones(numel(y), 1);             % Population intercept
priors.betaMean = 10;
priors.betaCov = 25;
priors.betweenShape = 2;           % Gamma prior on PRECISION
priors.betweenRate = 4;            % Shape/rate convention
opts.fixedNoisePrecision = 1;     % Covariances s(i)^2 are known

fit = hbayes_fit(model, subjects, X, priors, opts);
disp(fit.betaMean)
disp(fit.thetaMean)
disp(fit.objectiveKind)
assert(fit.converged, 'Inspect the convergence diagnostics.');
How does the MATLAB algorithm relate to these experiments?

For affine forward models, the framework uses Gaussian/Gamma coordinate-ascent variational inference. The updates are exact within its chosen mean-field family, while the posterior remains approximate. Its ELBO is a genuine bound for the stated affine model.

For nonlinear forward models, it uses damped Gauss–Newton updates, local Gaussian covariance estimates, and linearised expected residuals. The recorded objective is a local surrogate, not a guaranteed lower bound on the nonlinear model evidence. A returned convergence flag describes numerical stopping, rather than proof of exact Bayesian inference.

The framework models diagonal residual between-person covariance. Individual Gaussian factors can have full covariance. These are different statements: uncertainty about correlated parameters within a person does not imply that full population residual correlations are being learned.

Notation and prior choice differ. Here τ\tau is a population standard deviation with a half-normal prior. In the framework, betweenPrecision is inverse variance and has a Gamma prior. The browser integrates its small model numerically; the MATLAB framework uses variational approximations. Their numerical results should not be expected to coincide.

Four problems to try

Example function What it teaches
example_gaussian_pooling Check the conditional Gaussian update against 13.2 and 10.8.
example_linear_regression Learn person-specific intercepts and slopes with population covariates.
example_exponential_decay Fit amplitudes and rates in log space, including sparse or noisy recordings.
example_prediction Separate fitted-person prediction from new-person and observation uncertainty.

For the decay model, use θi=(logAi,logki)\theta_i=(\log A_i,\log k_i) and define the forward function as

f(t;θi)=exp(θi1)exp[−exp(θi2)t].f(t;\theta_i)=\exp(\theta_{i1})\exp[-\exp(\theta_{i2})t].

This gives positive physical parameters while placing the hierarchy explicitly on log parameters. A difference on the log scale becomes a multiplicative difference on the physical scale.

Check the model, as well as the fit

Before fitting, simulate from the prior: do the generated parameters and responses make sense? After fitting, simulate replicated data from the posterior predictive distribution: does the model reproduce the features that matter? Compare against analytic results in simple cases, and check sensitivity to priors, initialisation, and approximation choices.

For prediction across people, hold out people. For prediction across sites, hold out sites where possible. More observations from the same person do not provide the same validation as genuinely new individuals.

For the inference background, see Blei, Kucukelbir & McAuliffe (2017) on variational inference, and Friston et al. (2007) on variational Laplace. All experiments use synthetic data. Equations and explanations work offline; the interactive calculations run in your browser.