par(family="serif", las=1, bty="l",
cex.axis=1, cex.lab=1, cex.main=1,
xaxs="i", yaxs="i", mar = c(5, 5, 3, 1))
library(rstan)
rstan_options(auto_write = TRUE) # Cache compiled Stan programs
options(mc.cores = parallel::detectCores()) # Parallelize chains
parallel:::setDefaultClusterOptions(setup_strategy = "sequential")Implementing Hierarchical Models In Practice
More modeling technique chapters are available on my website.
In practice, hierarchical models are almost always implemented by elevating the population configuration variables to parameters that are inferred jointly with the individual parameters. Because this approach is so often used by default, the underlying theoretical motivation for the joint implementation is often taken for granted. In particular, it can be easy to forget that, technically, it is not the only possible implementation of hierarchical models.
1 Hierarchical Models
As I discuss in my hierarchical modeling chapter, hierarchical models are a consequence of assuming exchangeability. Any probabilistic model p( \theta_{1}, \ldots, \theta_{K} ) that is invariant to permutations of the variables \theta_{1}, \ldots, \theta_{K} is almost always of the form p( \theta_{1}, \ldots, \theta_{K} ) = \int \mathrm{d} \phi \, p( \phi ) \prod_{k = 1}^{K} p( \theta_{k} \mid \phi ). Here, \phi is known as the population variable, p( \theta_{k} \mid \phi ) is known as the population model, and p( \phi ) is known as the population prior model.
Intuitively, the individual parameters \theta_{k} can always be interpreted as being drawn from some latent population whose behavior is defined by the population model.
For some applications, this latent population corresponds to a meaningful phenomenon. In this case, inferences for the population variable \phi are just as important, if not more important, than inferences for the \theta_{k}, and the relevant model is actually p( \theta_{1}, \ldots, \theta_{K}, \phi ) = p( \phi ) \prod_{k = 1}^{K} p( \theta_{k} \mid \phi ).
Otherwise, however, the latent population is just a mathematical trick that allows us construct an exchangeable model p( \theta_{1}, \ldots, \theta_{K} ). In order to implement this exchangeable model in practice, we have to be able to implement the integral over \phi.
2 Practical Implementations
Unfortunately, analytic integration over \phi is rarely feasible in practice. Fortunately, we don’t have to implement this integral by itself.
Recall that, in practice, all well-defined posterior inferences are given by posterior expectation values, \begin{align*} \mathbb{E}[f] &= \int \mathrm{d} \theta_{1} \, \cdots \, \mathrm{d} \theta_{K} \, \hspace{23.5mm} p( \theta_{1}, \ldots, \theta_{K} \mid \tilde{y} ) \, \hspace{23.5mm} f( \theta_{1}, \ldots, \theta_{K} ) \\ &= \int \mathrm{d} \theta_{1} \, \cdots \, \mathrm{d} \theta_{K} \, \frac{ p( \tilde{y} \mid \theta_{1}, \ldots, \theta_{K} ) \, p( \theta_{1}, \ldots, \theta_{K} ) }{ \int \mathrm{d} \theta'_{1} \, \cdots \, \mathrm{d} \theta'_{K} \, p( \tilde{y} \mid \theta'_{1}, \ldots, \theta'_{K} ) \, p( \theta'_{1}, \ldots, \theta'_{K} ) } \, f( \theta_{1}, \ldots, \theta_{K} ) \\ &= \frac{ \int \mathrm{d} \theta^{\hphantom{'}}_{1} \, \cdots \, \mathrm{d} \theta^{\hphantom{'}}_{K} \, p( \tilde{y} \mid \theta^{\hphantom{'}}_{1}, \ldots, \theta^{\hphantom{'}}_{K} ) \, p( \theta^{\hphantom{'}}_{1}, \ldots, \theta^{\hphantom{'}}_{K} ) \, f( \theta_{1}, \ldots, \theta_{K} ) }{ \int \mathrm{d} \theta'_{1} \, \cdots \, \mathrm{d} \theta'_{K} \, p( \tilde{y} \mid \theta'_{1}, \ldots, \theta'_{K} ) \, p( \theta'_{1}, \ldots, \theta'_{K} ) \hspace{23mm} }, \end{align*} or more compactly, \mathbb{E}[f] = \frac{ \int \mathrm{d} \boldsymbol{\theta}^{\hphantom{'}} \, p( \tilde{y} \mid \boldsymbol{\theta}^{\hphantom{'}} ) \, p( \boldsymbol{\theta}^{\hphantom{'}} ) \, f( \boldsymbol{\theta} ) }{ \int \mathrm{d} \boldsymbol{\theta}' \, p( \tilde{y} \mid \boldsymbol{\theta}' ) \, p( \boldsymbol{\theta}' ) \hspace{9mm} }.
If p( \theta_{1}, \ldots, \theta_{K} ) is a hierarchical model, then writing it in its marginal form gives \begin{align*} \mathbb{E}[f] &= \frac{ \int \mathrm{d} \boldsymbol{\theta}^{\hphantom{'}} \, p( \tilde{y} \mid \boldsymbol{\theta}^{\hphantom{'}} ) \, p( \boldsymbol{\theta}^{\hphantom{'}} ) \, f( \boldsymbol{\theta} ) }{ \int \mathrm{d} \boldsymbol{\theta}' \, p( \tilde{y} \mid \boldsymbol{\theta}' ) \, p( \boldsymbol{\theta}' ) \, \hspace{9mm} } \\ &= \frac{ \int \mathrm{d} \boldsymbol{\theta}^{\hphantom{'}} \, p( \tilde{y} \mid \boldsymbol{\theta}^{\hphantom{'}} ) \, \int \mathrm{d} \phi^{\hphantom{'}} \, p(\phi^{\hphantom{'}} ) \, p( \boldsymbol{\theta}^{\hphantom{'}} \mid \phi^{\hphantom{'}} ) \, f( \boldsymbol{\theta} ) }{ \int \mathrm{d} \boldsymbol{\theta}' \, p( \tilde{y} \mid \boldsymbol{\theta}' ) \, \int \mathrm{d} \phi' \, p(\phi') \, p( \boldsymbol{\theta}' \mid \phi' ) \hspace{9mm} } \\ &= \frac{ \int \mathrm{d} \boldsymbol{\theta}^{\hphantom{'}} \, \mathrm{d} \phi^{\hphantom{'}} \, p( \tilde{y} \mid \boldsymbol{\theta}^{\hphantom{'}} ) \, p( \boldsymbol{\theta}^{\hphantom{'}} \mid \phi^{\hphantom{'}} ) \, p(\phi^{\hphantom{'}} ) \, f( \boldsymbol{\theta} ) }{ \int \mathrm{d} \boldsymbol{\theta}' \, \mathrm{d} \phi' \, p( \tilde{y} \mid \boldsymbol{\theta}' ) \, p( \boldsymbol{\theta}' \mid \phi' ) \, p(\phi') \hspace{9mm} } \\ &= \int \mathrm{d} \boldsymbol{\theta} \, \mathrm{d} \phi \, \frac{ p( \tilde{y} \mid \boldsymbol{\theta} ) \, p( \boldsymbol{\theta} \mid \phi ) \, p(\phi) \, }{ \int \mathrm{d} \boldsymbol{\theta}' \, \mathrm{d} \phi' \, p( \tilde{y} \mid \boldsymbol{\theta}' ) \, p( \boldsymbol{\theta}' \mid \phi' ) \, p(\phi') } f( \boldsymbol{\theta} ) \\ &= \int \mathrm{d} \boldsymbol{\theta} \, \mathrm{d} \phi \, \hspace{18mm} p( \boldsymbol{\theta}, \phi \mid \tilde{y} ) \, \hspace{18mm} f( \boldsymbol{\theta} ) \end{align*} where p( \boldsymbol{\theta}, \phi \mid \tilde{y} ) = \frac{ p( \tilde{y} \mid \boldsymbol{\theta}) \, p( \boldsymbol{\theta} \mid \phi ) \, p(\phi) \, }{ \int \mathrm{d} \boldsymbol{\theta}' \, \mathrm{d} \phi' \, p( \tilde{y} \mid \boldsymbol{\theta}' ) \, p( \boldsymbol{\theta}' \mid \phi' ) \, p(\phi') } is the posterior density function that we would derive from the joint model p( y, \theta_{1}, \ldots, \theta_{K}, \phi ) = p( y, \theta_{1}, \ldots, \theta_{K} ) \, p( \phi ) \prod_{k = 1}^{K} p( \theta_{k} \mid \phi ).
In words, we can derive any inferences for the \theta_{k} using the nominal hierarchical model with an explicit marginalization, p( \theta_{1}, \ldots, \theta_{K}, \phi ) = \int \mathrm{d} \phi \, p( \phi ) \prod_{k = 1}^{K} p( \theta_{k} \mid \phi ), or the joint model p( \theta_{1}, \ldots, \theta_{K}, \phi ) = p( \phi ) \prod_{k = 1}^{K} p( \theta_{k} \mid \phi ). The practical advantage of the joint implementation is that we are not responsible for integrating over \phi. Instead, the integration is performed implicitly by our probabilistic computational tooling whenever we evaluate posterior expectation values.
3 Demonstration
Because the marginal form of a hierarchical model cannot be implemented in most applications, it is easy to take the joint implementation for granted. That said, there are a few exceptionally simple applications where we can implement both, and directly compare them.
3.1 Population Model
Consider the positive, real-valued individual parameters \theta_{k} \in \mathbb{R}^{+} and the hierarchical population model \begin{align*} p( \boldsymbol{\theta}, \beta) &= p( \boldsymbol{\theta} \mid \beta) \, p(\beta) \\ &= \Bigg[ \prod_{k = 1}^{K} p( \theta_{k} \mid \beta) \Bigg] \, p( \beta ) \\ &= \Bigg[ \prod_{k = 1}^{K} \mathrm{exponential}( \theta_{k} \mid \beta) \Bigg] \, \mathrm{exponential}( \beta \mid \gamma ). \end{align*}
If we combine all of the exponential functions together, then this simplifies to \begin{align*} p( \theta_{1}, \ldots, \theta_{K}, \beta) &= \Bigg[ \prod_{k = 1}^{K} \mathrm{exponential}( \theta_{k} \mid \beta) \Bigg] \, \mathrm{exponential}( \beta \mid \gamma ) \\ &= \Bigg[ \prod_{k = 1}^{K} \beta \, \exp(- \beta \, \theta_{k} ) \Bigg] \, \gamma \, \exp(- \gamma \, \beta ) \\ &= \beta^{K} \, \gamma \, \exp \left[ - \left( \gamma \, \beta + \sum_{k = 1}^{K} \beta \, \theta_{k} \right) \right] \\ &= \beta^{K} \, \gamma \, \exp \left[ - \beta \, \left( \gamma + \sum_{k = 1}^{K} \theta_{k} \right) \right]. \end{align*}
Defining \zeta = \gamma + \sum_{k = 1}^{K} \theta_{k}, we can organize some of the terms to a gamma density function, \begin{align*} p( \theta_{1}, \ldots, \theta_{K}, \beta) &= \beta^{K} \, \gamma \, \exp ( - \beta \, \zeta ) \\ &= \gamma \, \left[ \frac{ \Gamma(K + 1) }{ \zeta^{K + 1} } \frac{ \zeta^{K + 1} } { \Gamma(K + 1) } \right] \beta^{(K + 1) - 1} \, \exp ( - \zeta \, \beta ) \\ &= \gamma \, \frac{ \Gamma(K + 1) }{ \zeta^{K + 1} } \left[ \frac{ \zeta^{K + 1} } { \Gamma(K + 1) } \beta^{(K + 1) - 1} \, \exp ( - \zeta \, \beta ) \right] \\ &= \gamma \, \frac{ \Gamma(K + 1) }{ \zeta^{K + 1} } \Bigg[ \mathrm{gamma}( \beta \mid K + 1, \zeta ) \Bigg]. \end{align*}
Conveniently, this allows us to immediately marginalize the population parameter \beta, \begin{align*} p( \theta_{1}, \ldots, \theta_{K} ) \\ &= \int \mathrm{d} \beta \, p( \theta_{1}, \ldots, \theta_{K}, \beta) \\ &= \gamma \, \frac{ \Gamma(K + 1) }{ \zeta^{K + 1} } \int \mathrm{d} \beta \, \mathrm{gamma}( \beta \mid K + 1, \zeta ) \\ &= \gamma \, \frac{ \Gamma(K + 1) }{ \zeta^{K + 1} } \\ &= \frac{ \gamma \, \Gamma(K + 1) }{ \left( \gamma + \sum_{k = 1}^{K} \theta_{k} \right)^{K + 1} }. \end{align*}
As far as I am aware, this probability density function does not fall into any common family; the neatest relation I can surmise is that it is equivalent to modeling \sqrt{ \sum_{k = 1}^{K} \theta_{k} } with a Student’s t density function. It does, however, exhibit some nice properties. In particular, it is inherently exchangeable: permuting the \theta_{k} changes only the order of the sum in the denominator, which does not affect the summed value.
We can also verify that this probability density function is properly normalized by integrating one \theta_{k} at a time. Starting with \theta_{1}, we have \begin{align*} \int_{0}^{\infty} \mathrm{d} \theta_{1} \, p( \theta_{1}, \ldots, \theta_{K} ) &= \int_{0}^{\infty} \mathrm{d} \theta_{1} \, \frac{ \gamma \, \Gamma(K + 1) }{ \left( \gamma + \sum_{k = 1}^{K} \theta_{k} \right)^{K + 1} } \\ &= \gamma \, \Gamma(K + 1) \int_{0}^{\infty} \mathrm{d} \theta_{1} \, \left( \theta_{1} + \gamma + \sum_{k = 2}^{K} \theta_{k} \right)^{-K - 1} \\ &= \gamma \, \Gamma(K + 1) \frac{1}{-K} \left[ \left( \theta_{1} + \gamma + \sum_{k = 2}^{K} \theta_{k} \right)^{-K} \right]^{\theta_{1} = \infty}_{\theta_{1} = 0} \\ &= \gamma \, \Gamma(K + 1) \frac{1}{-K} \left[ 0 - \left( \gamma + \sum_{k = 2}^{K} \theta_{k} \right)^{-K} \right] \\ &= \gamma \, \frac{\Gamma(K + 1)}{K} \, \left( \gamma + \sum_{k = 2}^{K} \theta_{k} \right)^{-K}. \end{align*}
Integration of \theta_{2}, \theta_{3} and so on follows with almost the exact same calculation. The kth integral pulls out a factor of K + 1 - k, reduces the exponent in the denominator by one, and eliminates the corresponding \theta_{k} from the sum in the denominator. After integrating over all of the \theta_{k}, we are left with \begin{align*} \int_{0}^{\infty} \mathrm{d} \theta_{1} \, \cdots \int_{0}^{\infty} \mathrm{d} \theta_{K} \, p( \theta_{1}, \ldots, \theta_{K} ) &= \gamma \, \frac{\Gamma(K + 1)}{K \, (K - 1) \, (K - 2) \, \cdots \, 1} \, \left( \gamma \right)^{-1}. \\ &= \frac{\gamma}{\gamma} \, \frac{\Gamma(K + 1)}{K!} \\ &= \frac{\gamma}{\gamma} \, \frac{\Gamma(K + 1)}{\Gamma(K + 1)} \\ &= 1, \end{align*} as desired.
3.2 Code Setup
With analytic forms of both the marginal and joint forms of this hierarchical model, we can implement both and verify their equivalence. We just need to set up our probabilistic computation environment first.
util <- new.env()
source('support/mcmc_analysis_tools_rstan.R',
local=util, chdir=TRUE)
source('support/mcmc_visualization_tools.R',
local=util, chdir=TRUE)3.3 Prior Comparison
Let’s begin by comparing the hierarchical model in isolation.
K <- 9marginal\_prior.stan
data {
int<lower=1> K; // Number of contexts
}
transformed data {
real<lower=0> gamma = 2;
}
parameters {
array[K] real<lower=0> theta;
}
model {
// Prior model
target += -(K + 1) * log(gamma + sum(theta));
}fit <- stan(file="stan_programs/marginal_prior.stan",
data=list('K' = K), seed=8438338,
warmup=1000, iter=2024, refresh=0)diagnostics <- util$extract_hmc_diagnostics(fit)
util$check_all_hmc_diagnostics(diagnostics) All Hamiltonian Monte Carlo diagnostics are consistent with reliable
Markov chain Monte Carlo.
samples_m <- util$extract_expectand_vals(fit)
base_samples <- util$filter_expectands(samples_m,
c('theta'),
check_arrays=TRUE)
util$check_all_expectand_diagnostics(base_samples)theta[1]:
Chain 1: Right tail hat{xi} (0.898) exceeds 0.25.
Chain 2: Right tail hat{xi} (0.935) exceeds 0.25.
Chain 3: Right tail hat{xi} (1.380) exceeds 0.25.
Chain 4: Right tail hat{xi} (1.093) exceeds 0.25.
theta[2]:
Chain 1: Right tail hat{xi} (0.757) exceeds 0.25.
Chain 2: Right tail hat{xi} (0.963) exceeds 0.25.
Chain 3: Right tail hat{xi} (1.201) exceeds 0.25.
Chain 4: Right tail hat{xi} (1.155) exceeds 0.25.
theta[3]:
Chain 1: Right tail hat{xi} (0.713) exceeds 0.25.
Chain 2: Right tail hat{xi} (0.951) exceeds 0.25.
Chain 3: Right tail hat{xi} (1.435) exceeds 0.25.
Chain 4: Right tail hat{xi} (1.088) exceeds 0.25.
theta[4]:
Chain 1: Right tail hat{xi} (0.822) exceeds 0.25.
Chain 2: Right tail hat{xi} (1.021) exceeds 0.25.
Chain 3: Right tail hat{xi} (1.436) exceeds 0.25.
Chain 4: Right tail hat{xi} (1.081) exceeds 0.25.
theta[5]:
Chain 1: Right tail hat{xi} (0.811) exceeds 0.25.
Chain 2: Right tail hat{xi} (0.954) exceeds 0.25.
Chain 3: Right tail hat{xi} (1.328) exceeds 0.25.
Chain 4: Right tail hat{xi} (1.046) exceeds 0.25.
theta[6]:
Chain 1: Right tail hat{xi} (0.825) exceeds 0.25.
Chain 2: Right tail hat{xi} (0.868) exceeds 0.25.
Chain 3: Right tail hat{xi} (1.278) exceeds 0.25.
Chain 4: Right tail hat{xi} (1.181) exceeds 0.25.
theta[7]:
Chain 1: Right tail hat{xi} (0.743) exceeds 0.25.
Chain 2: Right tail hat{xi} (0.924) exceeds 0.25.
Chain 3: Right tail hat{xi} (1.359) exceeds 0.25.
Chain 4: Right tail hat{xi} (1.141) exceeds 0.25.
theta[8]:
Chain 1: Right tail hat{xi} (0.609) exceeds 0.25.
Chain 2: Right tail hat{xi} (0.975) exceeds 0.25.
Chain 3: Right tail hat{xi} (1.348) exceeds 0.25.
Chain 4: Right tail hat{xi} (0.924) exceeds 0.25.
theta[9]:
Chain 1: Right tail hat{xi} (0.788) exceeds 0.25.
Chain 2: Right tail hat{xi} (0.851) exceeds 0.25.
Chain 3: Right tail hat{xi} (1.372) exceeds 0.25.
Chain 4: Right tail hat{xi} (1.099) exceeds 0.25.
Large tail hat{xi}s suggest that the expectand might not be
sufficiently integrable.
joint\_prior.stan
data {
int<lower=1> K; // Number of contexts
}
transformed data {
real<lower=0> gamma = 2;
}
parameters {
real<lower=0> beta;
array[K] real<lower=0> theta;
}
model {
// Prior model
target += exponential_lpdf(beta | gamma);
target += exponential_lpdf(theta | beta);
}fit <- stan(file="stan_programs/joint_prior.stan",
data=list('K' = K), seed=8438338,
warmup=1000, iter=2024, refresh=0)
diagnostics <- util$extract_hmc_diagnostics(fit)
util$check_all_hmc_diagnostics(diagnostics) All Hamiltonian Monte Carlo diagnostics are consistent with reliable
Markov chain Monte Carlo.
samples_j <- util$extract_expectand_vals(fit)
base_samples <- util$filter_expectands(samples_j,
c('beta', 'theta'),
check_arrays=TRUE)
util$check_all_expectand_diagnostics(base_samples)theta[1]:
Chain 1: Right tail hat{xi} (1.216) exceeds 0.25.
Chain 2: Right tail hat{xi} (0.926) exceeds 0.25.
Chain 3: Right tail hat{xi} (1.069) exceeds 0.25.
Chain 4: Right tail hat{xi} (0.958) exceeds 0.25.
theta[2]:
Chain 1: Right tail hat{xi} (1.174) exceeds 0.25.
Chain 2: Right tail hat{xi} (0.956) exceeds 0.25.
Chain 3: Right tail hat{xi} (1.116) exceeds 0.25.
Chain 4: Right tail hat{xi} (1.024) exceeds 0.25.
theta[3]:
Chain 1: Right tail hat{xi} (1.184) exceeds 0.25.
Chain 2: Right tail hat{xi} (0.938) exceeds 0.25.
Chain 3: Right tail hat{xi} (1.179) exceeds 0.25.
Chain 4: Right tail hat{xi} (0.899) exceeds 0.25.
theta[4]:
Chain 1: Right tail hat{xi} (1.187) exceeds 0.25.
Chain 2: Right tail hat{xi} (0.791) exceeds 0.25.
Chain 3: Right tail hat{xi} (1.105) exceeds 0.25.
Chain 4: Right tail hat{xi} (0.960) exceeds 0.25.
theta[5]:
Chain 1: Right tail hat{xi} (1.222) exceeds 0.25.
Chain 2: Right tail hat{xi} (0.861) exceeds 0.25.
Chain 3: Right tail hat{xi} (1.208) exceeds 0.25.
Chain 4: Right tail hat{xi} (0.956) exceeds 0.25.
theta[6]:
Chain 1: Right tail hat{xi} (1.358) exceeds 0.25.
Chain 2: Right tail hat{xi} (0.948) exceeds 0.25.
Chain 3: Right tail hat{xi} (1.062) exceeds 0.25.
Chain 4: Right tail hat{xi} (0.901) exceeds 0.25.
theta[7]:
Chain 1: Right tail hat{xi} (1.262) exceeds 0.25.
Chain 2: Right tail hat{xi} (0.993) exceeds 0.25.
Chain 3: Right tail hat{xi} (0.979) exceeds 0.25.
Chain 4: Right tail hat{xi} (0.991) exceeds 0.25.
theta[8]:
Chain 1: Right tail hat{xi} (1.358) exceeds 0.25.
Chain 2: Right tail hat{xi} (0.860) exceeds 0.25.
Chain 3: Right tail hat{xi} (1.083) exceeds 0.25.
Chain 4: Right tail hat{xi} (0.907) exceeds 0.25.
theta[9]:
Chain 1: Right tail hat{xi} (1.317) exceeds 0.25.
Chain 2: Right tail hat{xi} (0.896) exceeds 0.25.
Chain 3: Right tail hat{xi} (1.104) exceeds 0.25.
Chain 4: Right tail hat{xi} (1.039) exceeds 0.25.
Large tail hat{xi}s suggest that the expectand might not be
sufficiently integrable.
In both cases, the diagnostics indicate heavy-tailed behavior for the individual parameters. This is not unexpected for hierarchical models, as the convolution of the population model tends to shift probability to more extreme values.
Overlaying the marginal prior distributions of each individual parameter, it’s difficult to see any difference between the two implementations.
names <- sapply(1:K, function(k) paste0('theta[', k, ']'))
flims <- replicate(9, c(0, 25), simplify=FALSE)
par(mfrow=c(3, 3), mar = c(5, 5, 2, 1))
for (k in 1:K) {
name <- paste0('theta[', k, ']')
util$plot_expectand_pushforward(
samples_m[[name]],
30, flim=flims[[k]],
display_name=name,
col=util$c_light
)
util$plot_expectand_pushforward(
samples_j[[name]],
30, flim=flims[[k]],
col=util$c_dark,
border="#BBBBBB88",
add=TRUE
)
}Zooming in, we can see that the derived behaviors are not exactly the same, but consistent with Markov chain Monte Carlo numerical error.
par(mfrow=c(1, 1), mar = c(5, 5, 2, 1))
for (k in c(1)) {
name <- paste0('theta[', k, ']')
util$plot_expectand_pushforward(
samples_m[[name]],
30, flim=flims[[k]],
display_name=name,
col=util$c_light
)
util$plot_expectand_pushforward(
samples_j[[name]],
30, flim=flims[[k]],
col=util$c_dark,
border="#BBBBBB88",
add=TRUE
)
}3.4 Posterior Comparison
In order to compare how the two implementations of the hierarchical model influence posterior inferences, we’ll need some data. Let’s take a Poisson observational model, p( y_{1}, \ldots, y_{N} \mid \theta_{1}, \ldots, \theta_{K} ) = \prod_{n = 1}^{N} \mathrm{Poisson}( y_{n} \mid \theta_{k(n)} ), where k(n) denotes the context with which the nth observation is associated.
This assumed observational model allows us to simulate some data.
N <- 100simu.stan
data {
// Number of observations
int<lower=1> N;
// Number of individuals in hierarchy
int<lower=0> K;
}
generated quantities {
real beta = exponential_rng(2);
array[K] real theta = exponential_rng(rep_vector(beta, K));
array[N] int<lower=1, upper=K> indiv_idx;
array[N] int y;
for (n in 1:N) {
indiv_idx[n] = categorical_rng(uniform_simplex(K));
y[n] = poisson_rng(theta[indiv_idx[n]]);
}
}simu <- stan(file="stan_programs/simu.stan",
algorithm="Fixed_param", seed=3945843,
data=list('N' = N, 'K' = K),
warmup=0, iter=1, chains=1, refresh=0)
simu_fit <- extract(simu)data <- list('N' = N, 'K' = K,
'indiv_idx' = simu_fit$indiv_idx[1,],
'y' = simu_fit$y[1,])
beta_true <- simu_fit$beta[1]
theta_true <- simu_fit$theta[1,]Now, we can implement a full Bayesian model using both the marginal and joint implementations of the underlying hierarchy, and derive posterior inferences using Hamiltonian Monte Carlo.
marginal.stan
data {
int<lower=1> N; // Number of observations
int<lower=1> K; // Number of contexts
array[N] int<lower=1, upper=K> indiv_idx; // Observed context
array[N] int<lower=0> y; // Observed value
}
transformed data {
real<lower=0> gamma = 2;
}
parameters {
array[K] real<lower=0> theta;
}
model {
// Prior model
target += -(K + 1) * log(gamma + sum(theta));
// Observational model
target += poisson_lpmf(y | theta[indiv_idx]);
}fit <- stan(file="stan_programs/marginal.stan",
data=data, seed=8438338,
warmup=1000, iter=2024, refresh=0)diagnostics <- util$extract_hmc_diagnostics(fit)
util$check_all_hmc_diagnostics(diagnostics) All Hamiltonian Monte Carlo diagnostics are consistent with reliable
Markov chain Monte Carlo.
samples_m <- util$extract_expectand_vals(fit)
base_samples <- util$filter_expectands(samples_m,
c('theta'),
check_arrays=TRUE)
util$check_all_expectand_diagnostics(base_samples)All expectands checked appear to be behaving well enough for reliable
Markov chain Monte Carlo estimation.
joint.stan
data {
int<lower=1> N; // Number of observations
int<lower=1> K; // Number of contexts
array[N] int<lower=1, upper=K> indiv_idx; // Observed context
array[N] int<lower=0> y; // Observed value
}
transformed data {
real<lower=0> gamma = 2;
}
parameters {
real<lower=0> beta;
array[K] real<lower=0> theta;
}
model {
// Prior model
target += exponential_lpdf(beta | gamma);
target += exponential_lpdf(theta | beta);
// Observational model
target += poisson_lpmf(y | theta[indiv_idx]);
}fit <- stan(file="stan_programs/joint.stan",
data=data, seed=8438338,
warmup=1000, iter=2024, refresh=0)
diagnostics <- util$extract_hmc_diagnostics(fit)
util$check_all_hmc_diagnostics(diagnostics) All Hamiltonian Monte Carlo diagnostics are consistent with reliable
Markov chain Monte Carlo.
samples_j <- util$extract_expectand_vals(fit)
base_samples <- util$filter_expectands(samples_j,
c('beta', 'theta'),
check_arrays=TRUE)
util$check_all_expectand_diagnostics(base_samples)All expectands checked appear to be behaving well enough for reliable
Markov chain Monte Carlo estimation.
Hamiltonian Monte Carlo has no problems with either model implementation. In particular, we no longer see indications of heavy tails, which is consistent with the influence of an informative likelihood function.
Once again, the marginal posterior distributions for \theta_{k} fall right on top of each other. Moreover, everything is also consistent with the simulation truth.
names <- sapply(1:data$K, function(k) paste0('theta[', k, ']'))
flims <- list(c(2, 9), c(1, 6), c(0, 5),
c(3, 11), c(0, 1.5), c(1, 5),
c(4, 18), c(0, 4), c(1, 6) )
par(mfrow=c(3, 3), mar = c(5, 5, 2, 1))
for (k in 1:data$K) {
name <- paste0('theta[', k, ']')
util$plot_expectand_pushforward(
samples_m[[name]],
30, flim=flims[[k]],
display_name=name,
col=util$c_light
)
util$plot_expectand_pushforward(
samples_j[[name]],
30, flim=flims[[k]],
baseline=theta_true[k],
baseline_col=util$c_mid_teal,
col=util$c_dark,
border="#BBBBBB88",
add=TRUE
)
}If we zoom in again, then we can see the fine details as before. While there are small differences in the derived inferences, they are consistent with Markov chain Monte Carlo numerical error.
par(mfrow=c(1, 1), mar = c(5, 5, 2, 1))
for (k in c(1)) {
name <- paste0('theta[', k, ']')
util$plot_expectand_pushforward(
samples_m[[name]],
30, flim=flims[[k]],
display_name=name,
col=util$c_light
)
util$plot_expectand_pushforward(
samples_j[[name]],
30, flim=flims[[k]],
baseline=theta_true[k],
baseline_col=util$c_mid_teal,
col=util$c_dark,
border="#BBBBBB88",
add=TRUE
)
}Both with and without observed data, the two implementations of the hierarchical model yield equivalent results. This is exactly what we’d expect given our initial mathematical analysis, but it’s always nice to have a cross check.
License
The code in this case study is copyrighted by Michael Betancourt and licensed under the new BSD (3-clause) license:
https://opensource.org/licenses/BSD-3-Clause
The text and figures in this chapter are copyrighted by Michael Betancourt and licensed under the CC BY-NC 4.0 license:
Original Computing Environment
writeLines(readLines(file.path(Sys.getenv("HOME"), ".R/Makevars")))CC=clang
CXXFLAGS=-O3 -mtune=native -march=native -Wno-unused-variable -Wno-unused-function -Wno-macro-redefined -Wno-unneeded-internal-declaration
CXX=clang++ -arch x86_64 -ftemplate-depth-256
CXX14FLAGS=-O3 -mtune=native -march=native -Wno-unused-variable -Wno-unused-function -Wno-macro-redefined -Wno-unneeded-internal-declaration -Wno-unknown-pragmas
CXX14=clang++ -arch x86_64 -ftemplate-depth-256
sessionInfo()R version 4.6.2 (2026-10-29)
Platform: x86_64-apple-darwin20
Running under: macOS Sequoia 15.7.4
Matrix products: default
BLAS: /Library/Frameworks/R.framework/Versions/4.6-x86_64/Resources/lib/libRblas.0.dylib
LAPACK: /Library/Frameworks/R.framework/Versions/4.6-x86_64/Resources/lib/libRlapack.dylib; LAPACK version 3.12.1
locale:
[1] en_US.UTF-8/en_US.UTF-8/en_US.UTF-8/C/en_US.UTF-8/en_US.UTF-8
time zone: America/New_York
tzcode source: internal
attached base packages:
[1] stats graphics grDevices utils datasets methods base
other attached packages:
[1] colormap_0.1.4 rstan_2.39.0.9000 StanHeaders_2.39.1.1
loaded via a namespace (and not attached):
[1] vctrs_0.7.3 cli_3.6.6 knitr_1.52 rlang_1.3.0
[5] xfun_0.62 otel_0.3.0 S7_1.0.0 jsonlite_2.0.0
[9] RcppParallel_6.2.1 glue_1.8.1 V8_8.3.0 htmltools_0.5.9
[13] gridExtra_2.3.1 pkgbuild_1.4.8 stats4_4.6.2 scales_1.4.0
[17] rmarkdown_2.32 grid_4.6.2 evaluate_1.0.5 fastmap_1.2.0
[21] yaml_2.3.12 lifecycle_1.0.5 QuickJSR_1.11.0 inline_0.3.21
[25] compiler_4.6.2 codetools_0.2-20 RColorBrewer_1.1-3 Rcpp_1.1.2
[29] farver_2.1.2 digest_0.6.39 R6_2.6.1 curl_8.1.0
[33] parallel_4.6.2 loo_2.10.1.9000 tools_4.6.2 gtable_0.3.6
[37] matrixStats_1.5.0 ggplot2_4.0.4