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:
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.
Random Intercepts and Slopes
Extend to include a group-level slope:
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$parUsing 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,
,
through a centring weight
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)
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
-
Parameterisation: Use
random_effect()with a lowcentringweight (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 tocentring = 0but loses the ability to move along the continuum. -
Priors on variance components:
half_cauchy()is a sensible default for group-level standard deviations (Gelman 2006). - Convergence: Check R-hat and ESS. Hierarchical models may need longer warmup periods.
-
Quick checks: Use
opt()orvariational()to verify the model before running full MCMC.
