Chapter 11
Linear and Generalized Linear Mixed Effects Models
Mixed effects models are the natural marriage of hierarchical shrinkage (Chapter 8), multivariate normal covariance modeling (Chapter 7), regression (Chapter 9), and Metropolis–Hastings (Chapter 10).Peter D. Hoff. A First Course in Bayesian Statistical Methods. Springer Texts in Statistics. Springer, New York, 2009. ISBN 978-0-387-92299-7. doi: 10.1007/978-0-387-92407-6; and Andrew Gelman and Jennifer Hill. Data Analysis Using Regression and Multilevel/Hierarchical Models. Cambridge University Press, New York, 2007 Instead of allowing only a scalar group mean to vary across schools or subjects, we now let an entire regression coefficient vector —both intercepts and slopes—vary across groups while borrowing strength across the population.
11.1Hierarchical Linear Regression (Linear Mixed Effects)#
Return to the public high schools from the 2002 Educational Longitudinal Study (Chapter 8), now recording both math score and within-school centered socioeconomic status for student in school . Fitting separate OLS lines suggests that both the baseline achievement (intercept ) and the SES gradient (slope ) vary from school to school—yet small schools () produce wildly noisy OLS slopes, some even negative!
A hierarchical linear regression (or **linear mixed effects (LME)** model)Dennis V. Lindley and Adrian F. M. Smith. Bayes Estimates for the Linear Model. Journal of the Royal Statistical Society, Series B, 34:1–41, 1972 stacks each school’s responses into with design matrix and models the group coefficient vectors as draws from a shared multivariate normal population:
(11.1)Writing with explains the classical “mixed effects” terminology:
- is the fixed effect (the population-average intercept and slope across all schools).
- is the random effect (school ’s specific deviation from ), governed by the between-group covariance matrix , whose off-diagonal entries capture whether high-achieving schools also have steeper or flatter SES slopes!
11.1.1Adding Group-Level Covariates#
What if some predictors (such as school size or public/private status) vary only at the group level, or have effects assumed constant across all groups? Partitioning predictors into covariates with group-specific coefficients () and covariates with common coefficients (, including every group-level covariate) yields the general LME form
(11.2)which integrates seamlessly into the exact same Gibbs framework by adding one linear-regression block for given the partial residuals .
11.2Modular Gibbs Sampling for the LME Model#
Equipping with the standard semiconjugate priors from Chapters 7 and 9,
(11.3)requires zero new derivations: every single full conditional is a direct drop-in copy of a formula we already proved!
Algorithm 11.1 (Modular Four-Block Gibbs Sampler for the LME Model). Initialize (e.g., at per-group OLS estimates), , , and . For :
Group coefficients (conditionally independent across ; Ch. 9 regression update with prior ):
(11.4)Population mean vector (Ch. 7 MVN mean update treating as data):
(11.5)Between-group covariance (Ch. 7 inverse-Wishart update with ):
(11.6)Within-group precision (Ch. 9 variance update pooling all residuals):
(11.7)
11.2.1Population Slopes vs. Predictive Slopes#
In Hoff’s 100-school ELS analysis, fitting Algorithm 11.1 shrinks the noisy negative OLS slopes of small schools cleanly toward the positive population average ( math points per unit SES), while preserving real heterogeneity among larger schools. Moreover, comparing two distinct posteriors resolves an essential scientific question:
- Posterior of the population average slope : sharply concentrated above zero (95% CI ), proving that on average across schools, higher SES is associated with higher math scores.
- Posterior predictive distribution of a new school’s slope : much wider, with —showing that individual schools can still have flat or slightly negative SES gradients despite the strong positive population average!
11.3Generalized Linear Mixed Effects Models (GLMMs)#
When the within-group responses are counts or binary outcomes rather than continuous normal measurements, we replace the normal level-1 likelihood in (11.1) with a generalized linear model (GLM, Chapter 10). In Hoff’s mouse-tumor example, researchers recorded tumor counts at spatial locations along the small intestine of mice, modeled with a Poisson GLMM using a quartic polynomial in location:
(11.8)Notice the beauty of the hierarchical DAG: only the level-1 update for loses conjugacy! Because the between-group layer is still multivariate normal, the full conditionals for and are unchanged—we simply swap Step 1 of Algorithm 11.1 for a Metropolis–Hastings update, producing a hybrid Metropolis within Gibbs sampler:
Algorithm 11.2 (Metropolis-within-Gibbs Sampler for a Poisson GLMM). Initialize and proposal scale . For :
11.3.1Three Cumulative Layers of Uncertainty#
A fitted GLMM lets us separate three conceptually distinct predictive targets at any covariate location , each adding a new source of variance (Figure 11.1):
Typical (median) group’s intensity : reflects only estimation uncertainty in the center curve (narrowest band; note that because is convex, the population-average rate across groups is strictly larger,
).
New group’s intensity with : adds between-group heterogeneity (substantially wider).
New individual count : adds within-group Poisson sampling noise (widest band—the honest interval for forecasting a new observation).
Remark 11.3 (Mixing in hierarchical mixed models). Just as in Chapter 8, when a random-effect variance component is small relative to within-group noise, the centered update can exhibit high autocorrelation between and . Writing (where and ) yields the multivariate non-centered parameterizationOmiros Papaspiliopoulos, Gareth O. Roberts, and Martin Sköld. A General Framework for the Parametrization of Hierarchical Models. Statistical Science, 22(1):59–73, 2007, which often accelerates mixing dramatically in weakly informed mixed models.
import numpy as np
from scipy import stats
# Modular 4-block Gibbs sampler for a 2-parameter LME model (random intercept & slope)
rng = np.random.default_rng(11)
m, p = 40, 2
theta_true = np.array([48.0, 2.5])
Sigma_true = np.array([[20.0, 2.0], [2.0, 1.5]])
sig2_true = 64.0
# Simulate grouped school data with centered covariate x_ij
n_j = rng.integers(5, 25, size=m)
beta_true = rng.multivariate_normal(theta_true, Sigma_true, size=m)
X_list, y_list = [], []
for j in range(m):
x = rng.normal(0.0, 1.0, size=n_j[j])
x -= x.mean()
Xj = np.column_stack([np.ones(n_j[j]), x])
yj = Xj @ beta_true[j] + rng.normal(0.0, np.sqrt(sig2_true), size=n_j[j])
X_list.append(Xj)
y_list.append(yj)
N = int(n_j.sum())
# Weakly informative priors
mu0 = np.array([50.0, 0.0])
L0_inv = np.linalg.inv(np.diag([100.0, 25.0]))
eta0, S0 = p + 2.0, np.diag([25.0, 4.0])
nu0, s20 = 1.0, 64.0
S = 2_500
theta_s, Sigma_s, beta_s = np.empty((S, p)), np.empty((S, p, p)), np.empty((S, m, p))
beta_cur = np.tile(mu0, (m, 1))
th_cur, Sig_cur, s2_cur = mu0.copy(), S0.copy(), 64.0
for s in range(S):
Sig_inv = np.linalg.inv(Sig_cur)
# 1. Update each group's regression vector beta_j
sse = 0.0
for j in range(m):
Xj, yj = X_list[j], y_list[j]
Vj = np.linalg.inv(Sig_inv + (Xj.T @ Xj) / s2_cur)
mj = Vj @ (Sig_inv @ th_cur + (Xj.T @ yj) / s2_cur)
beta_cur[j] = rng.multivariate_normal(mj, Vj)
r = yj - Xj @ beta_cur[j]
sse += float(r @ r)
# 2. Update population mean theta
Lm = np.linalg.inv(L0_inv + m * Sig_inv)
mum = Lm @ (L0_inv @ mu0 + m * Sig_inv @ beta_cur.mean(axis=0))
th_cur = rng.multivariate_normal(mum, Lm)
# 3. Update between-group covariance Sigma (scipy scale = S0 + S_theta)
diff = beta_cur - th_cur
Sig_cur = stats.invwishart.rvs(df=eta0 + m, scale=S0 + diff.T @ diff, random_state=rng)
# 4. Update residual variance sigma^2 (numpy scale = 1/rate)
s2_cur = 1.0 / rng.gamma((nu0 + N) / 2.0, 2.0 / (nu0 * s20 + sse))
theta_s[s], Sigma_s[s], beta_s[s] = th_cur, Sig_cur, beta_cur
burn = 500
print("Posterior E[theta | y]:", np.round(theta_s[burn:].mean(axis=0), 2), "(truth:", theta_true, ")")
# Predictive slope for a brand-new school
b_new = np.array([rng.multivariate_normal(th, Sg) for th, Sg in zip(theta_s[burn:], Sigma_s[burn:])])
print(f"Pr(theta_2 > 0 | y) = {np.mean(theta_s[burn:, 1] > 0):.3f}, "
f"Pr(beta_new_2 > 0 | y) = {np.mean(b_new[:, 1] > 0):.3f}")11.4Modern Developments: Augmentation, Crossed Effects, and INLA#
11.4.1Pólya–Gamma Augmentation for Logistic and Negative-Binomial GLMMs#
Replacing the Poisson in (11.8) by a logistic or negative-binomial likelihood still breaks Step 1 of Algorithm 11.1, but for those two families a latent variable repairs it exactly.Beyond Hoff (2009). This material is not in Hoff’s book; Pólya–Gamma augmentation is due to Polson, Scott, and Windle (2013) and replaces the Metropolis block for logistic and negative-binomial responses. Suppose the likelihood of is proportional to in : Bernoulli has , and negative-binomial with size and log-odds has . With and the Pólya–Gamma family,Nicholas G. Polson, James G. Scott, and Jesse Windle. Bayesian Inference for Logistic Models Using Pólya–Gamma Latent Variables. Journal of the American Statistical Association, 108(504):1339–1349, 2013. doi: 10.1080/01621459.2013.829001
(11.9)Why it holds. Write ; the Laplace transform of is, by construction, , taken at . Given the exponent is quadratic in , and the update is (11.4) with as observation-specific precisions. The draws of and are unchanged. For ordinary logistic regression with a normal prior this Gibbs chain is uniformly ergodic;Hee Min Choi and James P. Hobert. The Polya-Gamma Gibbs sampler for Bayesian logistic regression is uniformly ergodic. Electronic Journal of Statistics, 7:2054–2064, 2013. doi: 10.1214/13-EJS837 that theorem concerns fixed effects, not the full hierarchical scan. The Poisson likelihood lacks the denominator, is only an limit, and is not covered.
When to use it. Use it for logistic and negative-binomial mixed models (an unknown needs its own update): no proposal to tune. For Poisson GLMMs keep Hoff’s Algorithm 11.2 or use HMC (Section 10.5.1).
11.4.2Scalable Collapsed Gibbs for Crossed Random Effects#
Every group in (11.1) is nested, so the are conditionally independent; if instead each test score belongs to a student and an exam item, the random effects are crossed and the modular sampler slows down as the data grow.Beyond Hoff (2009). This material is not in Hoff’s book; Papaspiliopoulos, Roberts, and Zanella (2020) analyze crossed effects, and Ascolani and Zanella (2024) the nested two-level models of this chapter. Take with , , one observation per cell (), a flat prior on , and known variances . The plain scan has relaxation time , and the collapsed sampler replaces its update as follows:Omiros Papaspiliopoulos, Gareth O. Roberts, and Giacomo Zanella. Scalable inference for crossed random effects models. Biometrika, 107(1):25–40, 2020. doi: 10.1093/biomet/asz058
(11.10)followed by the same pair with and exchanged.
Why it holds. In the plain scan the averages satisfy with (and likewise), and the corresponding map for is triangular with eigenvalues ; contrasts mix at once. Since , for fixed variances is at least of order at a cost of per scan, hence at least of order in total. Integrating out removes the coupling: with flat, the conditional of given is just its prior, so in this balanced layout successive collapsed draws of are independent. For unbalanced designs the speed depends on how well connected the design is. For nested two-level models, Hoff’s own case, the mixing time of suitable Gibbs samplers stays bounded as the number of groups grows, under regularity conditions and from a good starting point.Filippo Ascolani and Giacomo Zanella. Dimension-free mixing times of Gibbs samplers for Bayesian hierarchical models. The Annals of Statistics, 52(3):869–894, 2024. doi: 10.1214/24-AOS2367
When to use it. Collapse whenever two or more factors cross. For a single grouping factor, Algorithm 11.1 already scales, subject to Remark 11.3.
11.4.3Integrated Nested Laplace Approximation (INLA)#
Given , the unknowns of the Poisson GLMM (11.8) have a Gaussian prior and a log-concave likelihood, so their posterior is often close to normal and its marginals can be computed, approximately, rather than sampled.Beyond Hoff (2009). This material is not in Hoff’s book; INLA (Rue, Martino, and Chopin, 2009) appeared in the same year as Hoff’s book and is not covered there; Van Niekerk et al. (2023) reformulate it. With hyperparameters (here the entries of ), INLA evaluatesHåvard Rue, Sara Martino, and Nicolas Chopin. Approximate Bayesian Inference for Latent Gaussian models by using Integrated Nested Laplace Approximations. Journal of the Royal Statistical Society Series B: Statistical Methodology, 71(2):319–392, 2009. doi: 10.1111/j.1467-9868.2008.00700.x
(11.11)where is the conditional mode, the Gaussian matched there, and are integration weights.
Why it holds. The identity is exact at every ; only the denominator is approximated, at the point where a Gaussian fits best. As in Proposition 10.1, log-concavity makes that mode unique (with a proper normal prior on ), and Newton’s method finds it quickly because the prior precision is sparse. The marginals are then mixtures over a small grid of . A recent reformulation removes the linear predictors from the latent field and corrects the Gaussian means variationally, which helps when data are abundant.Janet Van Niekerk, Elias Krainski, Denis Rustand, and Håvard Rue. A new avenue for Bayesian inference with INLA. Computational Statistics & Data Analysis, 181:107692, 2023. doi: 10.1016/j.csda.2023.107692
When to use it. INLA gives fast, deterministic marginals for latent Gaussian models with few hyperparameters. MCMC is still needed when there are many (an unstructured for Hoff’s quartic mouse curves has ), when random effects are not Gaussian or the predictor is nonlinear, when the conditional posterior is far from normal, as for sparse binary data, or when the full joint posterior is wanted: there, Algorithm 11.2 remains the reference.
11.4.4Computational & Symbolic Check#
At the first identity of (11.9) rests on . The script checks it by simulating the series with , and by the infinite product that the series implies.Beyond Hoff (2009). This computational check and its Wolfram symbolic counterpart below verify the modern methods in this section and are not in Hoff’s book.
import numpy as np
rng = np.random.default_rng(111)
K, S = 200, 40_000
k = np.arange(1, K + 1)
# PG(1,0) draws from the first K terms; the mean of the omitted tail is added back
w = 1.0 / (2 * np.pi ** 2 * (k - 0.5) ** 2)
omega = rng.exponential(size=(S, K)) @ w + (0.25 - w.sum())
print(f"E[omega] = {omega.mean():.4f} (exact 0.25)")
kk = np.arange(1, 100_001)
for psi in (1.0, 2.0, 4.0):
mc = np.exp(-omega * psi ** 2 / 2).mean()
prod = np.exp(-np.log1p(psi ** 2 / (np.pi * (2 * kk - 1)) ** 2).sum())
print(f"psi={psi}: Monte Carlo={mc:.4f}, product={prod:.6f}, "
f"sech(psi/2)={1 / np.cosh(psi / 2):.6f}")
# Bernoulli likelihood at y = 1: kappa = 1/2
print(" logistic:", round(0.5 * np.exp(psi / 2) * mc, 4), round(1 / (1 + np.exp(-psi)), 4))// Laplace transform of one term g_k / (2 Pi^2 (k - 1/2)^2) at t = psi^2/2, minus the product factor
await show`Assuming[k >= 1 && Element[psi, Reals],
FullSimplify[Integrate[Exp[-g]*Exp[-g*psi^2/(4*Pi^2*(k - 1/2)^2)], {g, 0, Infinity}]
- 1/(1 + psi^2/(Pi^2*(2*k - 1)^2))]]`const pgLap = await show`FullSimplify[1/Product[1 + psi^2/(Pi^2*(2*k - 1)^2), {k, 1, Infinity}]]`await show`FullSimplify[TrigToExp[Exp[a*psi]/(1 + Exp[psi]) - 1/2*Exp[(a - 1/2)*psi]*(${pgLap})]]`await show`{-2*SeriesCoefficient[${pgLap}, {psi, 0, 2}], N[Table[${pgLap}, {psi, {1, 2, 4}}]]}`11.5Symbolic Check in Wolfram Language#
Proves symbolically in wolfram-ws-bridge JavaScript mode that the Poisson GLMM population-average rate exceeds the typical-group rate by a factor of , derives both the general LME slope posterior variance and the closed-form diagonal- shrinkage vector , and instantiates the conditional slope SD for small and large schools.
// Chapter 11: Symbolic Poisson GLMM rate ratio & symbolic LME intercept/slope shrinkage
const popAvg = await show`Assuming[v > 0 && Element[m, Reals],
FullSimplify[Integrate[Exp[m + Sqrt[v]*z]*Exp[-z^2/2]/Sqrt[2*Pi], {z, -Infinity, Infinity}]]]`await show`FullSimplify[${popAvg} / Exp[m]]`// Symbolic 2x2 LME posterior covariance V_j and diagonal-Sigma shrinkage mean m_j
const Vj = await show`FullSimplify[Inverse[Inverse[{{s11, s12}, {s12, s22}}] + DiagonalMatrix[{nj, sxx}]/sig2]]`const v22Sym = await show`FullSimplify[${Vj}[[2, 2]]]`await show`FullSimplify[Inverse[DiagonalMatrix[{1/t1^2, 1/t2^2}] + DiagonalMatrix[{nj, sxx}]/sig2] . {th1/t1^2 + nj*yb/sig2, th2/t2^2 + sxx*b2ols/sig2}]`// Instantiate conditional slope SD at Sigma = [[20, 2], [2, 1.5]], sig2 = 64, E[sxx] = nj - 1 (nj in {5, 24})
await show`N[Table[Sqrt[${v22Sym} /. {s11 -> 20, s12 -> 2, s22 -> 3/2, sig2 -> 64, nj -> nVal, sxx -> nVal - 1}], {nVal, {5, 24}}]]`11.6Exercises#
Exercise 11.4. In the LME Python simulation above, compute the unpooled OLS slope for every school and compare its total MSE against the hierarchical posterior mean from Algorithm 11.1. Plot versus to verify that small schools experience the strongest slope shrinkage.
Symbolic Solution & Instantiation
Compute the shrinkage gap symbolically under diagonal .// Ex 11.1: Symbolic LME slope shrinkage difference b2ols - m_{j,2} = O(1/n_j) (diagonal Sigma)
const shrinkDiff = await show`FullSimplify[b2ols - (sxx*b2ols/sig2 + th2/tau2Sq)/(sxx/sig2 + 1/tau2Sq)]`await show`N[Table[(${shrinkDiff} / (b2ols - th2)) /. {sig2 -> 64, tau2Sq -> 3/2, sxx -> nj - 1}, {nj, {5, 24}}]]`Exercise 11.5. Why did Hoff center student SES within each school () before fitting the LME model? Show algebraically how shifting by a constant changes both the interpretation of the intercept and the off-diagonal covariance .
Symbolic Solution & Instantiation
Conjugate by the global covariate-shift matrix to track how alters .// Ex 11.2: Effect of global shift x -> x - c on LME intercept covariance Sigma_{1,2}
const T = [[1, W.c], [0, 1]]
const covShift = await show`FullSimplify[${T} . {{s11, s12}, {s12, s22}} . Transpose[${T}]]`const cDecorr = await show`c /. First[Solve[${covShift}[[1, 2]] == 0, c]]`await show`{${cDecorr}, N[${cDecorr}]} /. {s12 -> 2, s22 -> 3/2}`Exercise 11.6. Write a short Python implementation of Algorithm 11.2 for groups with Poisson counts . Tune the proposal scale so average acceptance across groups stays between and , and plot the three uncertainty bands of Figure 11.1!
Symbolic Solution & Instantiation
Combine Poisson noise and log-normal random-effect variance via the law of total variance.// Ex 11.3: Exact predictive variance across layers 2-3 (random effects + Poisson noise, conditional on theta)
const totVar = await show`FullSimplify[Exp[m + v/2] + Exp[2*m + v]*(Exp[v] - 1)]`await show`N[{Exp[m], Exp[m + v/2], ${totVar}} /. {m -> 1, v -> 1/4}]`