Skip to contents

Overview

Hierarchical (multi-level) models are a key strength of Bayesian inference. gretaR supports hierarchical models through the [ indexing operator, which lets you define group-level parameters and index them by observation.

Random Intercepts Model

Consider data from J groups, each with n_j observations:

yij=αj+ϵij,ϵij∼N(0,σ2)y_{ij} = \alpha_j + \epsilon_{ij}, \quad \epsilon_{ij} \sim N(0, \sigma^2)

αj∼N(μ,τ2)\alpha_j \sim N(\mu, \tau^2)

library(gretaR)

# Simulate grouped data
set.seed(42)
n_groups <- 5
n_per_group <- 20
n <- n_groups * n_per_group
group_id <- rep(1:n_groups, each = n_per_group)

true_mu <- 5
true_tau <- 2
true_sigma <- 1
true_alpha <- rnorm(n_groups, true_mu, true_tau)
y_obs <- rnorm(n, true_alpha[group_id], true_sigma)

# Define gretaR model
mu <- normal(0, 10)
tau <- half_cauchy(5)
alpha <- normal(mu, tau, dim = c(n_groups, 1))
sigma <- half_cauchy(5)

y <- as_data(y_obs)
fitted_vals <- alpha[group_id]  # Index into group-level parameters
distribution(y) <- normal(fitted_vals, sigma)

m <- model(mu, tau, sigma, alpha)
print(m)

The alpha[group_id] syntax creates an operation node in the DAG that selects the appropriate group-level parameter for each observation. This is equivalent to the indexing notation used in Stan and JAGS.

# Fit with NUTS
draws <- mcmc(m, n_samples = 1000, warmup = 1000, chains = 4)
summary(draws)

Random Intercepts and Slopes

Extend to include a group-level slope:

yij=αj+βjxij+ϵijy_{ij} = \alpha_j + \beta_j x_{ij} + \epsilon_{ij}

αj∼N(μα,τα2),βj∼N(μβ,τβ2)\alpha_j \sim N(\mu_\alpha, \tau_\alpha^2), \quad \beta_j \sim N(\mu_\beta, \tau_\beta^2)

reset_gretaR_env()
set.seed(123)

n_groups <- 8
n_per_group <- 15
n <- n_groups * n_per_group
group_id <- rep(1:n_groups, each = n_per_group)
x_obs <- rnorm(n)

true_mu_a <- 3; true_tau_a <- 1.5
true_mu_b <- 2; true_tau_b <- 0.5
true_sigma <- 0.8

true_a <- rnorm(n_groups, true_mu_a, true_tau_a)
true_b <- rnorm(n_groups, true_mu_b, true_tau_b)
y_obs <- true_a[group_id] + true_b[group_id] * x_obs + rnorm(n, 0, true_sigma)

# Model
mu_a <- normal(0, 10)
mu_b <- normal(0, 10)
tau_a <- half_cauchy(5)
tau_b <- half_cauchy(5)
alpha <- normal(mu_a, tau_a, dim = c(n_groups, 1))
beta <- normal(mu_b, tau_b, dim = c(n_groups, 1))
sigma <- half_cauchy(5)

x <- as_data(x_obs)
y <- as_data(y_obs)

mu_y <- alpha[group_id] + beta[group_id] * x
distribution(y) <- normal(mu_y, sigma)

m <- model(mu_a, mu_b, tau_a, tau_b, sigma, alpha, beta)
print(m)

Using MAP for Quick Estimates

For quick model checking, use opt() to find the MAP estimate:

fit <- opt(m, verbose = TRUE)
fit$par

Using Variational Inference

For faster approximate inference:

fit <- variational(m, method = "meanfield", max_iter = 3000)
fit$mean
fit$sd
summary(fit$draws)

Partially-Centred Random Effects with random_effect()

The centred and non-centred parameterisations above are the two ends of a continuum: random_effect() builds the same group-level prior, uj∼N(mean,sd2)u_j \sim N(\mathrm{mean}, \mathrm{sd}^2), through a centring weight w∈[0,1]w \in [0, 1] that interpolates the sampling geometry (0 non-centred, 1 centred, anything between is a partial reparameterisation) without changing what is being estimated. It returns a $latent block, which must be passed to model(), and a $effect, the per-observation value that enters the linear predictor.

reset_gretaR_env()
set.seed(42)

n_groups <- 5
n_per_group <- 20
n <- n_groups * n_per_group
group_id <- rep(1:n_groups, each = n_per_group)

true_mu <- 5
true_tau <- 2
true_sigma <- 1
true_alpha <- rnorm(n_groups, true_mu, true_tau)
y_obs <- rnorm(n, true_alpha[group_id], true_sigma)

mu <- normal(0, 10)
tau <- half_cauchy(5)
sigma <- half_cauchy(5)

# A centring weight of 0.5 is a reasonable starting point when groups have
# a moderate amount of data each, as here (n_per_group = 20).
re <- random_effect(group_id, n_groups, sd = tau, centring = 0.5, mean = mu)

y <- as_data(y_obs)
distribution(y) <- normal(re$effect, sigma)

m <- model(mu, tau, sigma, re$latent)
print(m)
fit_re <- mcmc(m, n_samples = 300, warmup = 300, chains = 2)
summary(fit_re)
plot(fit_re, type = "trace")

The hyper-parameters mu and tau and all five latent group terms mix without the funnel-shaped stickiness a badly-matched centring weight produces; centring is a construction-time choice here, not something random_effect() tunes automatically – a group with very few observations relative to tau mixes better closer to w = 0, and a richly-informed group closer to w = 1.

Formula Interface for Simple Models

For standard GLMs, use the formula interface:

# Simple linear regression via formula
dat <- data.frame(y = y_obs, x = x_obs, group = factor(group_id))
fit <- gretaR_glm(y ~ x, data = dat, family = "gaussian", sampler = "map")
print(fit)

Tips for Hierarchical Models

  1. Parameterisation: Use random_effect() with a low centring weight (closer to non-centred) for better sampling when data are sparse within groups, and a higher weight (closer to centred) when groups are richly informed; hand-rolling the non-centred form directly is equivalent to centring = 0 but loses the ability to move along the continuum.
  2. Priors on variance components: half_cauchy() is a sensible default for group-level standard deviations (Gelman 2006).
  3. Convergence: Check R-hat and ESS. Hierarchical models may need longer warmup periods.
  4. Quick checks: Use opt() or variational() to verify the model before running full MCMC.

References

Gelman, A. (2006). Prior distributions for variance parameters in hierarchical models (comment on article by Browne and Draper). Bayesian Analysis, 1(3), 515–534. doi:10.1214/06-BA117A