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 θj\theta_j to vary across schools or subjects, we now let an entire regression coefficient vector 𝜷j∈ℝp\boldsymbol{\beta}_j \in \mathbb{R}^p—both intercepts and slopes—vary across groups while borrowing strength across the population.

11.1Hierarchical Linear Regression (Linear Mixed Effects)

Return to the m=100m = 100 public high schools from the 2002 Educational Longitudinal Study (Chapter 8), now recording both math score yi,jy_{i,j} and within-school centered socioeconomic status xi,jx_{i,j} for student i=1,…,nji = 1, \dots, n_j in school j=1,…,mj = 1, \dots, m. Fitting mm separate OLS lines suggests that both the baseline achievement (intercept βj,1\beta_{j,1}) and the SES gradient (slope βj,2\beta_{j,2}) vary from school to school—yet small schools (nj≈5n_j \approx 5) 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 𝐲j∈ℝnj\mathbf{y}_j \in \mathbb{R}^{n_j} with nj×pn_j \times p design matrix 𝐗j\mathbf{X}_j and models the group coefficient vectors as draws from a shared multivariate normal population:

Within-group model:𝐲j∣𝐗j,𝜷j,σ2∼𝒩nj(𝐗j𝜷j, σ2Inj),j=1,…,m,Between-group model:𝜷1,…,𝜷m∣𝜽,Σ∼i.i.d.𝒩p(𝜽,Σ). \begin{aligned} \text{Within-group model:} &\quad \mathbf{y}_j \mid \mathbf{X}_j, \boldsymbol{\beta}_j, \sigma^2 \sim \mathcal{N}_{n_j}(\mathbf{X}_j \boldsymbol{\beta}_j,\, \sigma^2 I_{n_j}), \qquad j = 1, \dots, m, \\ \text{Between-group model:} &\quad \boldsymbol{\beta}_1, \dots, \boldsymbol{\beta}_m \mid \boldsymbol{\theta}, \Sigma \stackrel{\text{i.i.d.}}{\sim} \mathcal{N}_p(\boldsymbol{\theta}, \Sigma). \end{aligned} (11.1)

Writing 𝜷j=𝜽+𝜸j\boldsymbol{\beta}_j = \boldsymbol{\theta} + \boldsymbol{\gamma}_j with 𝜸j∼i.i.d.𝒩p(𝟎,Σ)\boldsymbol{\gamma}_j \stackrel{\text{i.i.d.}}{\sim} \mathcal{N}_p(\mathbf{0}, \Sigma) explains the classical “mixed effects” terminology:

  • 𝜽\boldsymbol{\theta} is the fixed effect (the population-average intercept and slope across all schools).
  • 𝜸j\boldsymbol{\gamma}_j is the random effect (school jj’s specific deviation from 𝜽\boldsymbol{\theta}), governed by the p×pp \times p between-group covariance matrix Σ\Sigma, 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 (𝐱i,j\mathbf{x}_{i,j}) and covariates with common coefficients (𝐳i,j\mathbf{z}_{i,j}, including every group-level covariate) yields the general LME form

yi,j=𝜷jT𝐱i,j+𝜶T𝐳i,j+ϵi,j,ϵi,j∼i.i.d.𝒩(0,σ2), y_{i,j} = \boldsymbol{\beta}_j^T \mathbf{x}_{i,j} + \boldsymbol{\alpha}^T \mathbf{z}_{i,j} + \epsilon_{i,j}, \qquad \epsilon_{i,j} \stackrel{\text{i.i.d.}}{\sim} \mathcal{N}(0, \sigma^2), (11.2)

which integrates seamlessly into the exact same Gibbs framework by adding one linear-regression block for 𝜶\boldsymbol{\alpha} given the partial residuals yi,j−𝜷jT𝐱i,jy_{i,j} - \boldsymbol{\beta}_j^T \mathbf{x}_{i,j}.

11.2Modular Gibbs Sampling for the LME Model

Equipping (𝜽,Σ,σ2)(\boldsymbol{\theta}, \Sigma, \sigma^2) with the standard semiconjugate priors from Chapters 7 and 9,

𝜽∼𝒩p(𝝁0,Λ0),Σ∼inverse-Wishart⁡(η0,S0−1),1σ2∼gamma⁡ ⁣(ν02,ν0σ022), \boldsymbol{\theta} \sim \mathcal{N}_p(\boldsymbol{\mu}_0, \Lambda_0), \qquad \Sigma \sim \operatorname{inverse-Wishart}(\eta_0, S_0^{-1}), \qquad \frac{1}{\sigma^2} \sim \operatorname{gamma}\!\left(\frac{\nu_0}{2}, \frac{\nu_0 \sigma_0^2}{2}\right), (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 𝜷1(0),…,𝜷m(0)\boldsymbol{\beta}_1^{(0)}, \dots, \boldsymbol{\beta}_m^{(0)} (e.g., at per-group OLS estimates), 𝜽(0)\boldsymbol{\theta}^{(0)}, Σ(0)\Sigma^{(0)}, and σ2(0)\sigma^{2(0)}. For s=1,…,Ss = 1, \dots, S:

  1. Group coefficients 𝜷j(s)\boldsymbol{\beta}_j^{(s)} (conditionally independent across j=1,…,mj = 1, \dots, m; Ch. 9 regression update with prior 𝒩p(𝜽,Σ)\mathcal{N}_p(\boldsymbol{\theta}, \Sigma)):

    𝜷j∣𝐲j,𝐗j,𝜽,Σ,σ2∼𝒩p(𝐦j,Vj),Vj=(Σ−1+𝐗jT𝐗jσ2)−1,𝐦j=Vj ⁣(Σ−1𝜽+𝐗jT𝐲jσ2). \boldsymbol{\beta}_j \mid \mathbf{y}_j, \mathbf{X}_j, \boldsymbol{\theta}, \Sigma, \sigma^2 \sim \mathcal{N}_p(\mathbf{m}_j, V_j), \qquad V_j = \left(\Sigma^{-1} + \frac{\mathbf{X}_j^T \mathbf{X}_j}{\sigma^2}\right)^{-1}, \qquad \mathbf{m}_j = V_j\!\left(\Sigma^{-1}\boldsymbol{\theta} + \frac{\mathbf{X}_j^T \mathbf{y}_j}{\sigma^2}\right). (11.4)
  2. Population mean vector 𝜽(s)\boldsymbol{\theta}^{(s)} (Ch. 7 MVN mean update treating 𝜷1,…,𝜷m\boldsymbol{\beta}_1, \dots, \boldsymbol{\beta}_m as data):

    𝜽∣𝜷1:m,Σ∼𝒩p(𝝁m,Λm),Λm=(Λ0−1+mΣ−1)−1,𝝁m=Λm ⁣(Λ0−1𝝁0+mΣ−1𝜷¯). \boldsymbol{\theta} \mid \boldsymbol{\beta}_{1:m}, \Sigma \sim \mathcal{N}_p(\boldsymbol{\mu}_m, \Lambda_m), \qquad \Lambda_m = \left(\Lambda_0^{-1} + m\Sigma^{-1}\right)^{-1}, \qquad \boldsymbol{\mu}_m = \Lambda_m\!\left(\Lambda_0^{-1}\boldsymbol{\mu}_0 + m\Sigma^{-1}\bar{\boldsymbol{\beta}}\right). (11.5)
  3. Between-group covariance Σ(s)\Sigma^{(s)} (Ch. 7 inverse-Wishart update with 𝐒𝜽=∑j=1m(𝜷j−𝜽)(𝜷j−𝜽)T\mathbf{S}_{\boldsymbol{\theta}} = \sum_{j=1}^m (\boldsymbol{\beta}_j - \boldsymbol{\theta})(\boldsymbol{\beta}_j - \boldsymbol{\theta})^T):

    Σ∣𝜷1:m,𝜽∼inverse-Wishart⁡ ⁣(η0+m,  (S0+𝐒𝜽)−1). \Sigma \mid \boldsymbol{\beta}_{1:m}, \boldsymbol{\theta} \sim \operatorname{inverse-Wishart}\!\left(\eta_0 + m,\; (S_0 + \mathbf{S}_{\boldsymbol{\theta}})^{-1}\right). (11.6)
  4. Within-group precision 1/σ2(s)1/\sigma^{2(s)} (Ch. 9 variance update pooling all N=∑j=1mnjN = \sum_{j=1}^m n_j residuals):

    1σ2∣𝜷1:m,𝐲∼gamma⁡ ⁣(ν0+N2,  ν0σ02+∑j=1m∥𝐲j−𝐗j𝜷j∥22). \frac{1}{\sigma^2} \mid \boldsymbol{\beta}_{1:m}, \mathbf{y} \sim \operatorname{gamma}\!\left(\frac{\nu_0 + N}{2},\; \frac{\nu_0 \sigma_0^2 + \sum_{j=1}^m \lVert \mathbf{y}_j - \mathbf{X}_j\boldsymbol{\beta}_j \rVert^2}{2}\right). (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 (θ^2≈2.4\hat{\theta}_2 \approx 2.4 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 p(θ2∣𝐲)p(\theta_2 \mid \mathbf{y}): sharply concentrated above zero (95% CI (1.83,2.96)(1.83, 2.96)), proving that on average across schools, higher SES is associated with higher math scores.
  • Posterior predictive distribution of a new school’s slope β~2(s)∼𝒩p(𝜽(s),Σ(s))\tilde{\beta}_2^{(s)} \sim \mathcal{N}_p(\boldsymbol{\theta}^{(s)}, \Sigma^{(s)}): much wider, with Pr⁡(β~2<0∣𝐲,𝐗)≈0.07\Pr(\tilde{\beta}_2 < 0 \mid \mathbf{y}, \mathbf{X}) \approx 0.07—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 yi,jy_{i,j} at spatial locations xi,j∈(0,1)x_{i,j} \in (0, 1) along the small intestine of m=21m = 21 mice, modeled with a Poisson GLMM using a quartic polynomial in location:

yi,j∣𝐱i,j,𝜷j∼indep.Poisson⁡ ⁣(exp⁡(𝜷jT𝐱i,j)),𝜷1,…,𝜷m∣𝜽,Σ∼i.i.d.𝒩p(𝜽,Σ). y_{i,j} \mid \mathbf{x}_{i,j}, \boldsymbol{\beta}_j \stackrel{\text{indep.}}{\sim} \operatorname{Poisson}\!\bigl(\exp(\boldsymbol{\beta}_j^T \mathbf{x}_{i,j})\bigr), \qquad \boldsymbol{\beta}_1, \dots, \boldsymbol{\beta}_m \mid \boldsymbol{\theta}, \Sigma \stackrel{\text{i.i.d.}}{\sim} \mathcal{N}_p(\boldsymbol{\theta}, \Sigma). (11.8)

Notice the beauty of the hierarchical DAG: only the level-1 update for 𝜷j\boldsymbol{\beta}_j loses conjugacy! Because the between-group layer 𝜷j∣𝜽,Σ∼𝒩p(𝜽,Σ)\boldsymbol{\beta}_j \mid \boldsymbol{\theta}, \Sigma \sim \mathcal{N}_p(\boldsymbol{\theta}, \Sigma) is still multivariate normal, the full conditionals for 𝜽\boldsymbol{\theta} and Σ\Sigma 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 𝜷1:m(0),𝜽(0),Σ(0)\boldsymbol{\beta}_{1:m}^{(0)}, \boldsymbol{\theta}^{(0)}, \Sigma^{(0)} and proposal scale c>0c > 0. For s=1,…,Ss = 1, \dots, S:

  1. MH block for each 𝜷j\boldsymbol{\beta}_j (j=1,…,mj = 1, \dots, m, independently): propose 𝜷j∗∼𝒩p(𝜷j(s−1), c Σ(s−1))\boldsymbol{\beta}_j^* \sim \mathcal{N}_p(\boldsymbol{\beta}_j^{(s-1)},\, c\,\Sigma^{(s-1)}) (or a group covariance VjV_j fixed after a pilot run so the proposal stays symmetric). Compute the symmetric log-acceptance ratio

    log⁡rj=∑i=1nj[log⁡pPois(yi,j∣e𝜷j∗T𝐱i,j)−log⁡pPois(yi,j∣e𝜷j(s−1)T𝐱i,j)]+log⁡p𝒩(𝜷j∗∣𝜽(s−1),Σ(s−1))−log⁡p𝒩(𝜷j(s−1)∣𝜽(s−1),Σ(s−1)), \begin{aligned} \log r_j &= \sum_{i=1}^{n_j} \bigl[\log p_{\text{Pois}}(y_{i,j} \mid e^{\boldsymbol{\beta}_j^{*T}\mathbf{x}_{i,j}}) - \log p_{\text{Pois}}(y_{i,j} \mid e^{\boldsymbol{\beta}_j^{(s-1)T}\mathbf{x}_{i,j}})\bigr] \\ &\quad + \log p_{\mathcal{N}}(\boldsymbol{\beta}_j^* \mid \boldsymbol{\theta}^{(s-1)}, \Sigma^{(s-1)}) - \log p_{\mathcal{N}}(\boldsymbol{\beta}_j^{(s-1)} \mid \boldsymbol{\theta}^{(s-1)}, \Sigma^{(s-1)}), \end{aligned}

    and accept 𝜷j(s)=𝜷j∗\boldsymbol{\beta}_j^{(s)} = \boldsymbol{\beta}_j^* with probability min⁡(1,rj)\min(1, r_j).

  2. Exact Gibbs block for 𝜽(s)\boldsymbol{\theta}^{(s)}: draw from (11.5).

  3. Exact Gibbs block for Σ(s)\Sigma^{(s)}: draw from (11.6).

11.3.1Three Cumulative Layers of Uncertainty

A fitted GLMM lets us separate three conceptually distinct predictive targets at any covariate location 𝐱\mathbf{x}, each adding a new source of variance (Figure 11.1):

  1. Typical (median) group’s intensity exp⁡(𝜽(s)T𝐱)\exp(\boldsymbol{\theta}^{(s)T}\mathbf{x}): reflects only estimation uncertainty in the center curve 𝜽\boldsymbol{\theta} (narrowest band; note that because exp⁡\exp is convex, the population-average rate across groups is strictly larger,

    E[exp⁡(𝜷~T𝐱)∣𝜽,Σ]=exp⁡(𝜽T𝐱+12𝐱TΣ𝐱) E[\exp(\tilde{\boldsymbol{\beta}}^T\mathbf{x}) \mid \boldsymbol{\theta}, \Sigma] = \exp(\boldsymbol{\theta}^T\mathbf{x} + \frac{1}{2}\mathbf{x}^T\Sigma\mathbf{x})

    ).

  2. New group’s intensity exp⁡(𝜷~(s)T𝐱)\exp(\tilde{\boldsymbol{\beta}}^{(s)T}\mathbf{x}) with 𝜷~(s)∼𝒩p(𝜽(s),Σ(s))\tilde{\boldsymbol{\beta}}^{(s)} \sim \mathcal{N}_p(\boldsymbol{\theta}^{(s)}, \Sigma^{(s)}): adds between-group heterogeneity Σ\Sigma (substantially wider).

  3. New individual count Y~(s)∼Poisson⁡(exp⁡(𝜷~(s)T𝐱))\tilde{Y}^{(s)} \sim \operatorname{Poisson}\bigl(\exp(\tilde{\boldsymbol{\beta}}^{(s)T}\mathbf{x})\bigr): adds within-group Poisson sampling noise (widest band—the honest interval for forecasting a new observation).

Three panels comparing 95 percent intervals across location x in a Poisson GLMM: narrowest band for typical group rate exp(theta^T x), medium band for a new group rate exp(beta_tilde^T x), and widest band for a new count Y_tilde given x
Figure 11.1: Three nested layers of uncertainty in a Poisson GLMM. Left: uncertainty in the typical (median) group’s rate exp⁡(𝜽T𝐱)\exp(\boldsymbol{\theta}^T\mathbf{x}). Center: predictive rate exp⁡(𝜷~T𝐱)\exp(\tilde{\boldsymbol{\beta}}^T\mathbf{x}) for an unseen mouse, adding between-mouse variance Σ\Sigma. Right: posterior predictive count Y~∣𝐱\tilde{Y} \mid \mathbf{x}, adding Poisson sampling noise.

Remark 11.3 (Mixing in hierarchical mixed models). Just as in Chapter 8, when a random-effect variance component Σk,k\Sigma_{k,k} is small relative to within-group noise, the centered update 𝜷j∼𝒩p(𝜽,Σ)\boldsymbol{\beta}_j \sim \mathcal{N}_p(\boldsymbol{\theta}, \Sigma) can exhibit high autocorrelation between 𝜷1:m\boldsymbol{\beta}_{1:m} and Σ\Sigma. Writing 𝜷j=𝜽+L 𝜸~j\boldsymbol{\beta}_j = \boldsymbol{\theta} + L\,\tilde{\boldsymbol{\gamma}}_j (where Σ=LLT\Sigma = L L^T and 𝜸~j∼𝒩p(𝟎,Ip)\tilde{\boldsymbol{\gamma}}_j \sim \mathcal{N}_p(\mathbf{0}, I_p)) 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 yi,jy_{i,j} is proportional to eaψ/(1+eψ)be^{a\psi}/(1 + e^\psi)^b in ψ=𝜷jT𝐱i,j\psi = \boldsymbol{\beta}_j^T\mathbf{x}_{i,j}: Bernoulli has (a,b)=(y,1)(a, b) = (y, 1), and negative-binomial with size rr and log-odds ψ\psi has (a,b)=(y,y+r)(a, b) = (y, y + r). With κ=a−b/2\kappa = a - b/2 and PG⁡\operatorname{PG} 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

eaψ(1+eψ)b=2−beκψ Eω∼PG⁡(b,0)[e−ωψ2/2],ωi,j∣𝜷j∼PG⁡(bi,j, 𝜷jT𝐱i,j),𝜷j∣𝝎,𝐲j,𝜽,Σ∼𝒩p(𝐦j,Vj),Vj=(Σ−1+𝐗jTdiag⁡(𝝎j)𝐗j)−1,𝐦j=Vj(Σ−1𝜽+𝐗jT𝜿j). \begin{aligned} \frac{e^{a\psi}}{(1 + e^\psi)^b} &= 2^{-b}e^{\kappa\psi}\,E_{\omega \sim \operatorname{PG}(b, 0)}\bigl[e^{-\omega\psi^2/2}\bigr], \qquad \omega_{i,j} \mid \boldsymbol{\beta}_j \sim \operatorname{PG}(b_{i,j},\, \boldsymbol{\beta}_j^T\mathbf{x}_{i,j}), \\ \boldsymbol{\beta}_j \mid \boldsymbol{\omega}, \mathbf{y}_j, \boldsymbol{\theta}, \Sigma &\sim \mathcal{N}_p(\mathbf{m}_j, V_j), \qquad V_j = (\Sigma^{-1} + \mathbf{X}_j^T\operatorname{diag}(\boldsymbol{\omega}_j)\mathbf{X}_j)^{-1}, \quad \mathbf{m}_j = V_j(\Sigma^{-1}\boldsymbol{\theta} + \mathbf{X}_j^T\boldsymbol{\kappa}_j). \end{aligned} (11.9)

Why it holds. Write (1+eψ)−b=2−be−bψ/2cosh⁡−b(ψ/2)(1 + e^\psi)^{-b} = 2^{-b}e^{-b\psi/2}\cosh^{-b}(\psi/2); the Laplace transform of PG⁡(b,0)\operatorname{PG}(b, 0) is, by construction, E[e−ωt]=cosh⁡−b(t/2)E[e^{-\omega t}] = \cosh^{-b}(\sqrt{t/2}), taken at t=ψ2/2t = \psi^2/2. Given ω\omega the exponent is quadratic in 𝜷j\boldsymbol{\beta}_j, and the update is (11.4) with ωi,j\omega_{i,j} as observation-specific precisions. The draws of 𝜽\boldsymbol{\theta} and Σ\Sigma 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 r→∞r \to \infty limit, and is not covered.

When to use it. Use it for logistic and negative-binomial mixed models (an unknown rr 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 𝜷j\boldsymbol{\beta}_j 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 ys,k=μ+as+bk+ϵs,ky_{s,k} = \mu + a_s + b_k + \epsilon_{s,k} with s≤Is \le I, k≤Jk \le J, one observation per cell (N=IJN = IJ), a flat prior on μ\mu, and known variances σa2,σb2,σ2\sigma_a^2, \sigma_b^2, \sigma^2. The plain scan μ,𝐚,𝐛\mu, \mathbf{a}, \mathbf{b} has relaxation time TT, and the collapsed sampler replaces its μ\mu 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

T=1+max⁡{Jσa2, Iσb2}σ2,μ∣𝐛,𝐲∼normal⁡ ⁣(y¯−b¯,  σa2+σ2/JI)   then   𝐚∣μ,𝐛,𝐲, T = 1 + \frac{\max\{J\sigma_a^2,\, I\sigma_b^2\}}{\sigma^2}, \qquad \mu \mid \mathbf{b}, \mathbf{y} \sim \operatorname{normal}\!\left(\bar{y} - \bar{b},\; \frac{\sigma_a^2 + \sigma^2/J}{I}\right) \;\text{ then }\; \mathbf{a} \mid \mu, \mathbf{b}, \mathbf{y}, (11.10)

followed by the same pair with 𝐚\mathbf{a} and 𝐛\mathbf{b} exchanged.

Why it holds. In the plain scan the averages satisfy E[a¯′∣a¯]=caa¯E[\bar{a}' \mid \bar{a}] = c_a\bar{a} with ca=Jσa2/(Jσa2+σ2)c_a = J\sigma_a^2/(J\sigma_a^2 + \sigma^2) (and cb=Iσb2/(Iσb2+σ2)c_b = I\sigma_b^2/(I\sigma_b^2 + \sigma^2) likewise), and the corresponding map for (a¯,b¯)(\bar{a}, \bar{b}) is triangular with eigenvalues ca,cbc_a, c_b; contrasts mix at once. Since max⁡(I,J)≥N\max(I, J) \ge \sqrt{N}, for fixed variances TT is at least of order N\sqrt{N} at a cost of O(N)O(N) per scan, hence at least of order N3/2N^{3/2} in total. Integrating 𝐚\mathbf{a} out removes the coupling: with μ\mu flat, the conditional of b¯\bar{b} given 𝐚\mathbf{a} is just its prior, so in this balanced layout successive collapsed draws of 𝐛\mathbf{b} 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 Σ\Sigma, the unknowns 𝝃=(𝜷1:m,𝜽)\boldsymbol{\xi} = (\boldsymbol{\beta}_{1:m}, \boldsymbol{\theta}) 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 𝝍\boldsymbol{\psi} (here the entries of Σ\Sigma), 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

p~(𝝍∣𝐲)∝p(𝝃,𝝍,𝐲)p~G(𝝃∣𝝍,𝐲)∣𝝃=𝝃∗(𝝍),p~(ξi∣𝐲)=∑kp~(ξi∣𝝍k,𝐲) p~(𝝍k∣𝐲) Δk, \tilde{p}(\boldsymbol{\psi} \mid \mathbf{y}) \propto \left.\frac{p(\boldsymbol{\xi}, \boldsymbol{\psi}, \mathbf{y})}{\tilde{p}_G(\boldsymbol{\xi} \mid \boldsymbol{\psi}, \mathbf{y})}\right|_{\boldsymbol{\xi} = \boldsymbol{\xi}^*(\boldsymbol{\psi})}, \qquad \tilde{p}(\xi_i \mid \mathbf{y}) = \sum_k \tilde{p}(\xi_i \mid \boldsymbol{\psi}_k, \mathbf{y})\,\tilde{p}(\boldsymbol{\psi}_k \mid \mathbf{y})\,\Delta_k, (11.11)

where 𝝃∗(𝝍)\boldsymbol{\xi}^*(\boldsymbol{\psi}) is the conditional mode, p~G\tilde{p}_G the Gaussian matched there, and Δk\Delta_k are integration weights.

Why it holds. The identity p(𝝍∣𝐲)=p(𝝃,𝝍∣𝐲)/p(𝝃∣𝝍,𝐲)p(\boldsymbol{\psi} \mid \mathbf{y}) = p(\boldsymbol{\xi}, \boldsymbol{\psi} \mid \mathbf{y})/p(\boldsymbol{\xi} \mid \boldsymbol{\psi}, \mathbf{y}) is exact at every 𝝃\boldsymbol{\xi}; 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 𝜽\boldsymbol{\theta}), and Newton’s method finds it quickly because the prior precision is sparse. The marginals are then mixtures over a small grid of 𝝍\boldsymbol{\psi}. 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 5×55 \times 5 Σ\Sigma for Hoff’s quartic mouse curves has 1515), 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 b=1b = 1 the first identity of (11.9) rests on Eω∼PG⁡(1,0)[e−ωψ2/2]=sech⁡(ψ/2)E_{\omega \sim \operatorname{PG}(1,0)}[e^{-\omega\psi^2/2}] = \operatorname{sech}(\psi/2). The script checks it by simulating the series ω=d12π2∑k=1∞gk/(k−12)2\omega \stackrel{d}{=} \frac{1}{2\pi^2}\sum_{k=1}^\infty g_k/(k - \frac{1}{2})^2 with gk∼exponential⁡(1)g_k \sim \operatorname{exponential}(1), 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))
Integrate out one exponential gkg_k: each term of the series contributes the factor (1+ψ2/(π2(2k−1)2))−1\bigl(1 + \psi^2/(\pi^2(2k-1)^2)\bigr)^{-1}.
// 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))]]`
∫0∞e−g e−gψ2/{4π2(k−12)2} dg−(1+ψ2π2(2k−1)2)−1=0 \int_0^\infty e^{-g}\,e^{-g\psi^2/\{4\pi^2(k-\frac{1}{2})^2\}}\,dg - \left(1 + \frac{\psi^2}{\pi^2(2k-1)^2}\right)^{-1} = 0 Multiply the independent factors over all kk: Euler’s product for cosh⁡\cosh closes the Pólya–Gamma transform.
const pgLap = await show`FullSimplify[1/Product[1 + psi^2/(Pi^2*(2*k - 1)^2), {k, 1, Infinity}]]`
𝔼ω∼PG⁡(1,0)[e−ωψ2/2]=∏k=1∞(1+ψ2π2(2k−1)2)−1=sech⁡(ψ2) \begin{aligned} &\mathbb{E}_{\omega\sim\operatorname{PG}(1,0)}\bigl[e^{-\omega\psi^2/2}\bigr] = \prod_{k=1}^\infty \left(1 + \frac{\psi^2}{\pi^2(2k-1)^2}\right)^{-1} \\ &= \operatorname{sech}\left(\frac{\psi}{2}\right) \end{aligned} Substitute the transform into the fundamental identity at b=1b = 1, for a symbolic exponent aa.
await show`FullSimplify[TrigToExp[Exp[a*psi]/(1 + Exp[psi]) - 1/2*Exp[(a - 1/2)*psi]*(${pgLap})]]`
eaψ1+eψ−12 e(a−12)ψ 𝔼ω∼PG⁡(1,0)[e−ωψ2/2]=0 \frac{e^{a\psi}}{1+e^\psi} - \frac{1}{2}\,e^{(a-\frac{1}{2})\psi}\,\mathbb{E}_{\omega\sim\operatorname{PG}(1,0)}\bigl[e^{-\omega\psi^2/2}\bigr] = 0 Read 𝔼[ω]\mathbb{E}[\omega] off the ψ2\psi^2 coefficient and instantiate sech⁡(ψ/2)\operatorname{sech}(\psi/2) at the script’s ψ∈{1,2,4}\psi \in \{1, 2, 4\}.
await show`{-2*SeriesCoefficient[${pgLap}, {psi, 0, 2}], N[Table[${pgLap}, {psi, {1, 2, 4}}]]}`
(𝔼[ω],  sech⁡(ψ/2)ψ∈{1, 2, 4})={14,{0.886819,0.648054,0.265802}} \begin{aligned} &\bigl(\mathbb{E}[\omega],\; \operatorname{sech}(\psi/2)_{\psi \in \{1,\, 2,\, 4\}}\bigr) \\ &= \left\{\frac{1}{4},\{0.886819,0.648054,0.265802\}\right\} \end{aligned}

11.5Symbolic Check in Wolfram Language

Proves symbolically in wolfram-ws-bridge JavaScript mode that the Poisson GLMM population-average rate E[exp⁡(𝜷~T𝐱)]E[\exp(\tilde{\boldsymbol{\beta}}^T\mathbf{x})] exceeds the typical-group rate exp⁡(𝜽T𝐱)\exp(\boldsymbol{\theta}^T\mathbf{x}) by a factor of exp⁡(12𝐱TΣ𝐱)\exp(\tfrac12 \mathbf{x}^T\Sigma\mathbf{x}), derives both the general 2×22 \times 2 LME slope posterior variance (Vj)2,2(V_j)_{2,2} and the closed-form diagonal-Σ\Sigma shrinkage vector 𝐦j\mathbf{m}_j, and instantiates the conditional slope SD for small and large schools.

Integrate em+vze^{m + \sqrt{v}z} against the standard normal to compute the population-averaged Poisson GLMM rate.
// 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}]]]`
𝔼[eη]=∫−∞∞em+v zϕ(z) dz=em+v2 \mathbb{E}[e^{\eta}] = \int_{-\infty}^\infty e^{m+\sqrt{v}\,z}\phi(z)\,dz = e^{m+\frac{v}{2}} Divide by the typical-group rate eme^m to isolate the exact Jensen inflation factor ev/2e^{v/2}.
await show`FullSimplify[${popAvg} / Exp[m]]`
𝔼[eη]em=ev/2 \frac{\mathbb{E}[e^\eta]}{e^m} = e^{v/2} Invert the 2×22 \times 2 LME posterior precision matrix to get the conditional covariance VjV_j; write D=Σ11Σ22−Σ122=det⁡ΣD = \Sigma_{11}\Sigma_{22} - \Sigma_{12}^2 = \det\Sigma.
// 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]]`
Vj=(Σ−1+1σ2diag⁡(nj,Sxx))−1=σ2σ4+σ2(njΣ11+SxxΣ22)+njSxxD×(σ2Σ11+SxxDσ2Σ12σ2Σ12σ2Σ22+njD) \begin{aligned} &V_j = \left(\Sigma^{-1} + \frac{1}{\sigma^2}\operatorname{diag}(n_j, S_{xx})\right)^{-1} \\ &= \frac{\sigma^2}{\sigma^4 + \sigma^2 (n_j \Sigma_{11} + S_{xx} \Sigma_{22}) + n_j S_{xx} D} \\ &\quad \times \left( \begin{array}{cc} \sigma^2 \Sigma_{11} + S_{xx} D & \sigma^2 \Sigma_{12} \\ \sigma^2 \Sigma_{12} & \sigma^2 \Sigma_{22} + n_j D \\ \end{array} \right) \end{aligned} Extract its (2,2)(2,2) entry, the conditional slope variance [Vj]2,2[V_j]_{2,2}.
const v22Sym = await show`FullSimplify[${Vj}[[2, 2]]]`
[(Σ−1+1σ2diag⁡(nj,Sxx))−1]2,2=σ2(−njΣ122+njΣ11Σ22+Σ22σ2)−njΣ122Sxx+njΣ11(σ2+Σ22Sxx)+σ2(σ2+Σ22Sxx) \begin{aligned} &\left[\left(\Sigma^{-1} + \frac{1}{\sigma^2}\operatorname{diag}(n_j, S_{xx})\right)^{-1}\right]_{2,2} \\ &= \frac{\sigma^2 \left(-n_j \Sigma_{12}^2+n_j \Sigma_{11} \Sigma_{22} +\Sigma_{22} \sigma^2 \right)}{-n_j \Sigma_{12}^2 S_{xx} +n_j \Sigma_{11} (\sigma^2 +\Sigma_{22} S_{xx})+\sigma^2 (\sigma^2 +\Sigma_{22} S_{xx})} \end{aligned} Solve the diagonal-Σ\Sigma posterior mean system to display explicit intercept and slope shrinkage formulas.
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}]`
𝐦jdiag={σ2θ1+njτ12y¯σ2+njτ12,β^j,2OLSSxxτ22+σ2θ2σ2+Sxxτ22} \begin{aligned} &\mathbf{m}_j^{\text{diag}} \\ &= \left\{\frac{\sigma^2 \theta_1 +n_j \tau_1^2 \bar{y}}{\sigma^2 +n_j \tau_1^2},\frac{\hat{\beta}_{j,2}^{\text{OLS}} S_{xx} \tau_2^2+\sigma^2 \theta_2}{\sigma^2 +S_{xx} \tau_2^2}\right\} \end{aligned} Instantiate the conditional slope SD for small (nj=5n_j = 5) versus large (nj=24n_j = 24) schools.
// 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}}]]`
(SD⁡(βj,2∣yj,θ,Σ,σ2))nj∈{5, 24}={1.1264,0.947057} \begin{aligned} &\bigl(\operatorname{SD}(\beta_{j,2} \mid y_j, \theta, \Sigma, \sigma^2)\bigr)_{n_j \in \{5,\, 24\}} \\ &= \{1.1264,0.947057\} \end{aligned}

11.6Exercises

Exercise 11.4. In the LME Python simulation above, compute the unpooled OLS slope β^j,2ols\hat{\beta}_{j,2}^{\text{ols}} for every school j=1,…,mj = 1, \dots, m and compare its total MSE against the hierarchical posterior mean β^j,2\hat{\beta}_{j,2} from Algorithm 11.1. Plot β^j,2ols−β^j,2\hat{\beta}_{j,2}^{\text{ols}} - \hat{\beta}_{j,2} versus njn_j to verify that small schools experience the strongest slope shrinkage.

Symbolic Solution & InstantiationCompute the shrinkage gap β^j,2OLS−mj,2\hat{\beta}_{j,2}^{\text{OLS}} - m_{j,2} symbolically under diagonal Σ\Sigma.
// 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)]`
β^j,2OLS−mj,2=σ2(β^j,2OLS−θ2)σ2+Sxxτ22 \begin{aligned} &\hat{\beta}_{j,2}^{\text{OLS}} - m_{j,2} \\ &= \frac{\sigma^2 (\hat{\beta}_{j,2}^{\text{OLS}} -\theta_2)}{\sigma^2 +S_{xx} \tau_2^2} \end{aligned} Evaluate the fraction of (β^j,2OLS−θ2)(\hat{\beta}_{j,2}^{\text{OLS}} - \theta_2) shrunk away at nj=5n_j = 5 (91.4%91.4\%) and nj=24n_j = 24 (65.0%65.0\%).
await show`N[Table[(${shrinkDiff} / (b2ols - th2)) /. {sig2 -> 64, tau2Sq -> 3/2, sxx -> nj - 1}, {nj, {5, 24}}]]`
(β^j,2OLS−mj,2β^j,2OLS−θ2)nj∈{5, 24}={0.914286,0.649746} \begin{aligned} &\left(\frac{\hat{\beta}_{j,2}^{\text{OLS}} - m_{j,2}}{\hat{\beta}_{j,2}^{\text{OLS}} - \theta_2}\right)_{n_j \in \{5,\, 24\}} \\ &= \{0.914286,0.649746\} \end{aligned}

Exercise 11.5. Why did Hoff center student SES within each school (x¯j=0\bar{x}_j = 0) before fitting the LME model? Show algebraically how shifting xi,jx_{i,j} by a constant changes both the interpretation of the intercept βj,1\beta_{j,1} and the off-diagonal covariance Σ1,2=Cov⁡(βj,1,βj,2)\Sigma_{1,2} = \operatorname{Cov}(\beta_{j,1}, \beta_{j,2}).

Symbolic Solution & InstantiationConjugate Σ\Sigma by the global covariate-shift matrix TT to track how x↦x−cx \mapsto x - c alters Σ1,2\Sigma_{1,2}.
// 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}]]`
TΣT⊤=(Σ11+c(2Σ12+cΣ22)Σ12+cΣ22Σ12+cΣ22Σ22) \begin{aligned} &T \Sigma T^\top \\ &= \left( \begin{array}{cc} \Sigma_{11} +c (2 \Sigma_{12} +c \Sigma_{22}) & \Sigma_{12} +c \Sigma_{22} \\ \Sigma_{12} +c \Sigma_{22} & \Sigma_{22} \\ \end{array} \right) \end{aligned} Solve (TΣTT)1,2=0(T\Sigma T^T)_{1,2} = 0 for the exact decorrelating shift c∗=−Σ12/Σ22c^* = -\Sigma_{12}/\Sigma_{22}.
const cDecorr = await show`c /. First[Solve[${covShift}[[1, 2]] == 0, c]]`
c∗=−Σ12Σ22 c^* = -\frac{\Sigma_{12}}{\Sigma_{22}} Instantiate c∗c^* as an exact fraction and decimal at Σ12=2,Σ22=3/2\Sigma_{12} = 2, \Sigma_{22} = 3/2.
await show`{${cDecorr}, N[${cDecorr}]} /. {s12 -> 2, s22 -> 3/2}`
(cexact∗,  cdecimal∗)Σ12=2,  Σ22=3/2={−43,−1.33333} \begin{aligned} &\bigl(c^*_{\text{exact}},\; c^*_{\text{decimal}}\bigr)_{\Sigma_{12}=2,\; \Sigma_{22}=3/2} \\ &= \left\{-\frac{4}{3},-1.33333\right\} \end{aligned}

Exercise 11.6. Write a short Python implementation of Algorithm 11.2 for m=15m = 15 groups with nj=12n_j = 12 Poisson counts yi,j∼Poisson⁡(exp⁡(βj,1+βj,2xi,j))y_{i,j} \sim \operatorname{Poisson}(\exp(\beta_{j,1} + \beta_{j,2} x_{i,j})). Tune the proposal scale cc so average acceptance across groups stays between 25%25\% and 45%45\%, and plot the three uncertainty bands of Figure 11.1!

Symbolic Solution & InstantiationCombine 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)]`
Var⁡(Y~∣θ)=em+v2+e2m+v(−1+ev) \operatorname{Var}(\tilde{Y} \mid \theta) = e^{m+\frac{v}{2}}+e^{2 m+v} \left(-1+e^v\right) Instantiate median rate, population-average rate, and total predictive variance at m=1,v=0.25m = 1, v = 0.25.
await show`N[{Exp[m], Exp[m + v/2], ${totVar}} /. {m -> 1, v -> 1/4}]`
(em,  em+v/2,  Var⁡(Y~∣θ))m=1,  v=0.25={2.71828,3.08022,5.77497} \begin{aligned} &\bigl(e^m,\; e^{m+v/2},\; \operatorname{Var}(\tilde{Y} \mid \theta)\bigr)_{m=1,\; v=0.25} \\ &= \{2.71828,3.08022,5.77497\} \end{aligned}