Post

Bayesian estimation

An estimate of a person’s value on a latent variable depends on the population parameters that relate the latent variable to the observed responses. Conditioning on estimated population parameters treats those parameters as known, leaving their uncertainty out of the conditional distribution of the person’s latent variable. Bayesian estimation combines prior distributions with the observed data to obtain the joint posterior distribution of the population parameters and the latent variables. Integrating over the population parameters then carries their uncertainty into the posterior distribution of each person’s latent variable. The chapter follows a one-factor model for the simulated sample BAYES4 from priors and posterior approximations through several samplers to diagnostics, predictive checks and verification of the samplers.

16.1 Joint posterior distributions, priors, identification, and empirical Bayes estimates

Consider one response from one person. Let $y_{ij}$ be person $i$’s observed value on item $j$, let $z_i$ be the person’s common factor, and write $\theta$ for the population parameters. A prior density $p(\theta)$ expresses uncertainty about these parameters before observing the responses. At a given $\theta$, the population distribution supplies a density $p(z_i\mid\theta)$ for the factor. The measurement density $p(y_{ij}\mid z_i,\theta)$ completes the product $p(\theta)p(z_i\mid\theta)p(y_{ij}\mid z_i,\theta)$. At the observed response, divide this product by its integral over both unknowns to obtain their joint posterior density. This normalization requires the marginal density of the observed responses to be finite and strictly positive. For $n$ people independent given $\theta$, each with four conditionally independent responses given their factor and the parameters, collect the observations into the matrix $Y$ and the factors into the vector $z$. The posterior has the form

\[p(\theta,z\mid Y)\ \propto\ p(\theta) \prod_{i=1}^{n}\left\{p(z_i\mid\theta) \prod_{j=1}^{4}p(y_{ij}\mid z_i,\theta)\right\}.\]

The prior for the shared parameters occurs once. Integrate over all the factors for the marginal posterior of the parameters, or over the parameters and all but the first factor for the posterior of the first person’s factor. The other people’s responses inform this prediction through the shared parameters.

What changes in a person’s prediction when the population parameter is uncertain? Take one observation $y=1$. In this scalar example, the population mean has prior $\theta\sim N(0,1)$, the person’s latent variable $Z$ satisfies $Z\mid\theta\sim N(\theta,1)$, and the measurement satisfies $Y\mid Z\sim N(Z,1)$. Integrating out $Z$ gives $Y\mid\theta\sim N(\theta,2)$, so the marginal likelihood is largest at $\hat\theta=1$. Completing the square in $(z-\theta)^2+(1-z)^2$ gives a conditional mean of $(1+\theta)/2$ and variance $1/2$ for $Z$. Using the fitted mean treats it as known, as in a factor score calculated at estimated loadings. To integrate over $\theta$ instead, add the prior precision of one to the measurement’s marginal precision of one half. These reciprocal variances give the posterior for the population mean.

1
2
3
4
5
6
y_example <- 1
theta_variance <- 1 / (1 + 1/2)
theta_mean <- theta_variance * y_example / 2
print(data.frame(prior_precision = 1, data_precision = 1/2,
  posterior_precision = 1/theta_variance,
  posterior_mean_theta = theta_mean, posterior_variance_theta = theta_variance))
1
2
3
4
  prior_precision data_precision posterior_precision posterior_mean_theta
1               1            0.5                 1.5            0.3333333
  posterior_variance_theta
1                0.6666667

The posterior for $\theta$ has mean $1/3$ and variance $2/3$. Averaging $(1+\theta)/2$ over this distribution gives the person’s posterior mean. The variance has two components, the average conditional variance and the variance of the conditional mean.

1
2
3
4
5
print(data.frame(treatment = c("theta at marginal MLE", "theta integrated given y"),
  mean_z = c(y_example, (theta_mean + y_example)/2),
  expected_conditional_variance = 1/2,
  variance_of_conditional_mean = c(0, theta_variance/4),
  variance_z = c(1/2, 1/2 + theta_variance/4)))
1
2
3
4
5
6
                 treatment    mean_z expected_conditional_variance
1    theta at marginal MLE 1.0000000                           0.5
2 theta integrated given y 0.6666667                           0.5
  variance_of_conditional_mean variance_z
1                    0.0000000  0.5000000
2                    0.1666667  0.6666667

The empirical Bayes distribution for $Z$ is $N(1,1/2)$. After integration, it is $N(2/3,2/3)$. The mean moves toward the population prior mean of zero, and uncertainty in $\theta$ adds $(2/3)/4=1/6$ to the variance. The divisor four comes from squaring the coefficient of $\theta$ in the conditional mean. Here the conditional variance is the same at every $\theta$. In a model where it varies, its posterior average may be larger or smaller than its value at the fitted parameters, even though the variance of the conditional mean is always nonnegative.

A one-factor model and priors for the BAYES4 responses

BAYES4 contains four continuous responses from each of 150 simulated people. In its one-factor model, $\theta$ contains four loadings $\lambda_j$ and four unique variances $\psi_j$. Each person’s factor is standard normal, so one factor unit is one population standard deviation. At $z_i$, response $j$ is normal with mean $\lambda_j z_i$ and variance $\psi_j$, with all response intercepts fixed at zero. A one-unit increase in the factor changes the conditional mean of response $j$ by $\lambda_j$ response units. The unique variance $\psi_j$ is the variance of $y_{ij}-\lambda_jz_i$ at a given factor value, in squared units of that response. It describes variation left after conditioning on the common factor. Require $\lambda_1>0$ so that larger factor values increase the expected first response.

Give each loading an independent normal prior with mean zero and variance four, and restrict the first loading to $\lambda_1>0$. Truncating the $N(0,4)$ density to positive values removes half its probability, so on $\lambda_1>0$ the normalized prior density is twice the $N(0,4)$ density. Zero and four are the mean and variance before truncation. The truncated prior of $\lambda_1$ has mean $2\sqrt{2/\pi}\approx1.596$ and variance $4(1-2/\pi)\approx1.454$. Independently give each $\psi_j$ an inverse gamma prior, so its reciprocal has a gamma distribution with shape two and rate one.

These priors and the simulated responses are set up in R as follows. From the book directory, load the functions, set these prior values with bayes4_prior() and reproduce the simulated response matrix with bayes4_generate(), both in code/lib/bayes_factor.R.

1
2
3
4
5
bayes4_generate <- function(n,loading,variance) {
  z <- rnorm(n)
  Y <- outer(z,loading)+sweep(matrix(rnorm(n*length(loading)),n),2,sqrt(variance),"*")
  list(Y=Y,truth=list(z=z,loading=loading,variance=variance))
}

In the code, z contains the factors $z_i$, and sweep() multiplies column $j$ of the standard normal errors by $\sqrt{\psi_j}$, so column $j$ of Y is $\lambda_jz_i$ plus an error with variance $\psi_j$.

1
2
3
4
5
6
7
8
9
10
11
12
source("code/lib/bayes_factor.R")

bayes4_prior <- function(loading_sd=2,shape=2,rate=1) {
  stopifnot(loading_sd>0,shape>0,rate>0)
  list(loading_sd=loading_sd,shape=shape,rate=rate)
}

RNGkind("Mersenne-Twister","Inversion","Rejection")
prior <- bayes4_prior()
set.seed(1601)
generated <- bayes4_generate(150,c(.8,.7,.9,.6),c(.36,.51,.19,.64))
Y <- generated$Y

The prior constructor stores loading_sd, the normal loading prior’s standard deviation before truncation, and shape and rate, the gamma parameters for each reciprocal variance. The four loadings and four unique variances in the generation call are the values used to generate this particular sample. At these fixed parameters, bayes4_generate() draws one standard normal factor per person and independent normal response errors. It returns the person-by-item response matrix in Y and the generating factors and parameters in truth.

The matrix Y matches data/source/ch16/BAYES4.rds. Only the four responses per person enter the likelihood. In the imported log_prior_bayes4() function, log(2) supplies the normalization for the first loading. For each variance, the function evaluates the log gamma density at $1/\psi_j$ and adds the log absolute derivative $-2\log\psi_j$ to express that density per unit of variance.

1
2
3
4
5
log_prior_bayes4 <- function(loading,variance,prior) {
  if(any(!is.finite(c(loading,variance))) || loading[1]<=0 || any(variance<=0)) return(-Inf)
  log(2)+sum(dnorm(loading,sd=prior$loading_sd,log=TRUE))+
    sum(dgamma(1/variance,shape=prior$shape,rate=prior$rate,log=TRUE)-2*log(variance))
}

A nonpositive first loading or variance, or a nonfinite value, gives $-\infty$.

Prior families for coefficients, variances and covariance matrices

The loading and variance priors above belong to standard families. For a linear regression coefficient, a normal prior describes plausible changes in mean response per unit of the covariate. For a loading, the factor plays the role of the covariate. A variance $v$ must be positive. In the convention used here, $v\sim IG(\alpha,\beta)$ means that its reciprocal has a gamma distribution with shape $\alpha>0$ and rate $\beta>0$. Changing variables gives a density proportional to $v^{-(\alpha+1)}\exp(-\beta/v)$ for $v>0$. For the variance prior $IG(2,1)$, the mean is one but the variance is infinite. A proper prior need not have finite moments, and its numerical parameters must be interpreted on the stated response scale.

For a random intercept and slope, their two variances describe the dispersion in starting levels and rates of change. Their covariance describes whether people who start higher also tend to have larger slopes. Let $G$ be a positive definite covariance matrix for $q$ random effects. An inverse Wishart prior with degrees of freedom $\nu>q-1$ and positive definite scale matrix $S$ has density proportional to

\[|G|^{-(\nu+q+1)/2} \exp\!\left\{-\tfrac12\operatorname{tr}(SG^{-1})\right\}.\]

Here $\vert G\vert $ is the determinant and the trace sums the diagonal entries of $SG^{-1}$. This prior assigns probability jointly to the variances and covariances, respecting the bounds that the variances place on each covariance.

An intercept measured in response units and a slope measured in response units per year can warrant different prior scales. Write $G=D\Omega D$, with the standard deviations on the diagonal of $D$ and the correlations in $\Omega$. One choice assigns independent half-$t$ priors to the standard deviations and independently gives $\Omega$ a Lewandowski-Kurowicka-Joe (LKJ) correlation prior with density proportional to $\vert \Omega\vert ^{\eta-1}$ on positive definite correlation matrices, for $\eta>0$. At $\eta=1$ the density is uniform over correlation matrices; in dimensions above two this does not give uniform marginal distributions for individual correlations. Independent priors on these scales and correlations generally yield a different distribution for $G$ from an inverse Wishart prior. With two random effects and correlation $\rho$, the determinant is $1-\rho^2$. Set $u=(1+\rho)/2$. Then $1-\rho^2=4u(1-u)$ and the absolute derivative of $\rho$ with respect to $u$ is two. The resulting density is proportional to $u^{\eta-1}(1-u)^{\eta-1}$ on the unit interval, a beta density with both shapes equal to $\eta$.

A half-$t$ standard deviation has the distribution of $A$ times the absolute value of a standard Student $t$ variable with $\nu$ degrees of freedom. Here $A$ sets its scale; it is not the standard deviation of that prior. One construction draws an auxiliary $a\sim IG(1/2,1/A^2)$ and then $v\mid a\sim IG(\nu/2,\nu/a)$, setting $\sigma=\sqrt v$. The variables df, A, aux and sigma below give these quantities.

Simulating from the priors

What responses do the factor-model priors predict before anyone is measured? Each call to prior_predictive_bayes4() draws four loadings, taking the absolute value of the first, and four unique variances. All 150 people in that dataset share those values. Each person receives a new standard normal factor and four independent normal errors with the drawn variances.

1
2
3
4
5
6
7
prior_predictive_bayes4 <- function(n,prior) {
  loading <- rnorm(4,sd=prior$loading_sd)
  # A half-normal prior draw is the absolute value of a draw from a zero-mean normal distribution.
  loading[1] <- abs(loading[1])
  variance <- 1/rgamma(4,shape=prior$shape,rate=prior$rate)
  bayes4_generate(n,loading,variance)
}

Sample variances and covariances therefore vary both because the parameters differ across datasets and because responses vary among samples at given parameters. Generate the draws once in the following order. The 500 datasets summarized in prior_draws use the factor-model priors. The subsequent draws of standard deviations and correlations illustrate the separate covariance prior.

1
2
3
4
5
6
7
8
9
10
set.seed(1611)
prior_draws <- replicate(500L,{
  data <- prior_predictive_bayes4(150,prior)
  c(first_loading=data$truth$loading[1],var1=var(data$Y[,1]),
    cov12=cov(data$Y[,1],data$Y[,2]))
})
df <- 4; A <- 1.5
aux <- 1/rgamma(2000,.5,rate=1/A^2)
sigma <- sqrt(1/rgamma(length(aux),df/2,rate=df/aux))
rho <- 2*rbeta(2000,2,2)-1

Read each row of prior_draws across datasets for the first loading, the first response’s sample variance and the covariance of the first two responses.

1
print(t(apply(prior_draws,1,quantile,c(.05,.5,.95))))
1
2
3
4
                      5%          50%       95%
first_loading  0.1045225  1.187472907  3.747664
var1           0.4628933  2.328713154 15.483481
cov12         -4.9643927 -0.002610708  5.621079

The central 90 percent of first loadings ran from about 0.105 to 3.748, with median 1.187. The corresponding percentiles for the sample variance were 0.463, 2.329 and 15.48. Figure 16.1 shows the long right tail allowed for this variance. Although the first loading is positive, the second can have either sign. Their product is the population covariance at a given draw. The sample covariance spanned both signs, with percentiles of about $-4.96$, $-0.003$ and 5.62. These ranges let a researcher judge whether the proposed priors put appreciable probability on implausible response scales before using the observed responses.

The first response's sample variance has a long right tail. Sample covariances for the first two responses cluster near zero and extend to both signs.

Figure 16.1. Each bar counts datasets in the indicated interval among 500 samples of 150 people. The horizontal scale on the left is in squared units of response one. On the right it is in the product of the two response units.

The remaining draws illustrate the separate priors for covariance scales and correlations. For $\eta=2$, the beta distribution has mean $1/2$ and variance $1/20$. Transforming back gives mean zero and mean square $4/20$ for $\rho$.

1
2
print(c(LKJ_shape=2,mean_rho=mean(rho),mean_squared_rho=mean(rho^2),
  theoretical_second=1/5))
1
2
         LKJ_shape           mean_rho   mean_squared_rho theoretical_second 
        2.00000000        -0.02324319         0.19888558         0.20000000 

The mean of the 2,000 simulated correlations was about $-0.0232$. Their mean square, 0.1989, measures spread about zero and is close to the theoretical 0.2.

To verify the half-$t$ construction for $\nu>0$ and $A>0$, integrate out the auxiliary variable $a$. In this integral, the normalizing term $(\nu/a)^{\nu/2}$ of the conditional density matters because it varies with $a$. Multiplying the two densities gives the following marginal density up to a constant independent of $v$:

\[p(v)\ \propto\ v^{-\nu/2-1} \int_0^\infty a^{-(\nu+3)/2} \exp\!\left[-\{\nu/v+1/A^2\}/a\right]\,da \ \propto\ v^{-\nu/2-1}(\nu/v+1/A^2)^{-(\nu+1)/2}.\]

Substituting $t=(\nu/v+1/A^2)/a$ gives the final power of $\nu/v+1/A^2$ times a gamma integral independent of $v$. Setting $v=\sigma^2$ multiplies the density by $2\sigma$ and gives $p(\sigma)\propto[1+\sigma^2/(\nu A^2)]^{-(\nu+1)/2}$ for $\sigma>0$. This is the half-$t$ density specified above. In the code, aux contains the first reciprocal gamma draws. For each $a$, the next gamma draw uses rate $\nu/a$. Its reciprocal square root gives $\sigma$. By symmetry, the half-$t$ quantile at cumulative probability $p$ is $A$ times the ordinary $t$ quantile at $(1+p)/2$.

1
2
print(data.frame(p=c(.25,.5,.75),empirical=quantile(sigma,c(.25,.5,.75)),
  half_t=A*qt((1+c(.25,.5,.75))/2,df)))
1
2
3
4
       p empirical    half_t
25% 0.25 0.4764716 0.5120634
50% 0.50 1.0862543 1.1110456
75% 0.75 1.9987824 2.0165963

At four degrees of freedom and scale 1.5, the simulated lower quartile, median and upper quartile were 0.4765, 1.0863 and 1.9988. Their theoretical values are 0.5121, 1.1110 and 2.0166. Introducing $a$ is one way to draw from this prior. The four unique variances in the factor model still have their specified inverse gamma priors. The stats package supplies the probability distributions used in these calculations.

Identification and orientation

A proper prior integrates to one. That property alone cannot distinguish parameter values that imply identical response distributions. In the one-factor model, reversing the signs of every loading and every person’s factor leaves each conditional response mean unchanged. After the factor is integrated out, the observable covariance between any two distinct responses still depends on the product of their loadings. No number of observations can choose between these two orientations. With symmetric priors on unrestricted loadings, averaging over both orientations gives a posterior mean loading of zero even for an item strongly associated with the factor.

Fixing the factor variance and requiring a positive first loading give its unit and direction a consistent meaning across fits. These conventions remove the scale and sign ambiguities; identification of the remaining parameters also depends on the response structure and nonzero loadings. A latent class analysis likewise needs a consistent way to attach a class label to a response profile before summarizing its class-specific parameters. Predictions of observable responses are invariant to a consistent change of signs or a permutation of class labels. Interpreting one person’s factor therefore requires the same unit and orientation for every draw.

16.2 Maximum a posteriori estimation, Laplace approximation, and mean-field variational Bayes

How large is the first loading in the one-factor model for BAYES4? One possible answer uses the combination of four loadings and four unique variances at which their joint posterior density is highest. This is a maximum a posteriori (MAP) estimate. To find a mode for the first loading alone, one would have to integrate out the other seven parameters before maximizing. For the joint MAP, integrate out only the people’s factors. Write $\theta=(\lambda,\psi)$ for the eight population parameters and $\pi_\theta(\theta\mid Y)$ for their density per unit of volume on the loading and variance scales. An optimization routine can search for its maximum without ever proposing an inadmissible variance. Let $u$ contain the log of the positive first loading, the three unrestricted loadings, and the logs of the four positive variances. The inverse transformation $g$ exponentiates the five logged entries. Because $g$ is one-to-one onto the allowed parameter space, searching over $u$ for the largest value of $\log\pi_\theta(g(u)\mid Y)$ visits the same density values as searching directly over $\theta$. Working in the book directory, load the observed BAYES4 responses and use the loading and variance priors already specified. The starting loadings are all 0.6 and the starting unique variances are all 0.5. The function bayes4_coordinates() stores these values in the order below, and bayes4_unpack() reverses the transformation.

Entries of uModel quantities
u[1]$\log\lambda_1$
u[2:4]$\lambda_2,\lambda_3,\lambda_4$
u[5:8]$\log\psi_1,\ldots,\log\psi_4$
Remaining entries, when factors are retained$z_1,\ldots,z_n$

The function bayes4_target() returns two functions: value(u) evaluates the log density up to its posterior normalizing constant, and gradient(u) differentiates it in these coordinates. Its marginal argument selects whether to integrate out the person factors; its transformed argument selects whether to include the log absolute determinant of the change-of-variables Jacobian. The coordinates are converted by bayes4_coordinates() and bayes4_unpack().

1
bayes4_coordinates <- function(loading,variance,z=numeric()) c(log(loading[1]),loading[-1],log(variance),z)
1
2
3
bayes4_unpack <- function(u,p=4L) {
  list(loading=c(exp(u[1]),u[2:p]),variance=exp(u[p+seq_len(p)]),z=tail(u,-(2L*p)))
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
bayes4_target <- function(Y,prior,transformed=TRUE,marginal=FALSE) {
  n <- nrow(Y); p <- ncol(Y)
  scatter <- crossprod(Y)
  invalid <- function(u) list(value=-Inf,gradient=rep(NaN,length(u)))
  evaluate <- function(u) {
    b <- bayes4_unpack(u,p)
    L <- b$loading; v <- b$variance
    lp <- log_prior_bayes4(L,v,prior)
    if(!is.finite(lp) || any(!is.finite(b$z))) return(invalid(u))
    if(marginal) {
      R <- tryCatch(chol(tcrossprod(L)+diag(v,p)),error=function(e) NULL)
      if(is.null(R)) return(invalid(u))
      inv <- chol2inv(R)
      # The joint quadratic for all observed people depends on their scatter matrix.
      value <- lp-.5*(n*(p*log(2*pi)+2*sum(log(diag(R))))+sum(inv*scatter))
      A <- inv%*%scatter%*%inv-n*inv
      gL <- drop(A%*%L)
      gv <- diag(A)*v/2
      gz <- numeric()
    } else {
      z <- b$z
      zz <- sum(z*z)
      yz <- drop(crossprod(Y,z))
      rss <- diag(scatter)-2*L*yz+L^2*zz
      # Direct residual sums protect nearly exact fits from subtractive cancellation.
      if(any(!is.finite(rss))) return(invalid(u))
      uncertain <- rss<=sqrt(.Machine$double.eps)*(diag(scatter)+L^2*zz)
      if(any(uncertain)) rss[uncertain] <- colSums((Y[,uncertain,drop=FALSE]-outer(z,L[uncertain]))^2)
      value <- lp-.5*(n*((p+1)*log(2*pi)+sum(log(v)))+zz+sum(rss/v))
      gL <- (yz-L*zz)/v
      gv <- -.5*n+.5*rss/v
      gz <- drop(Y%*%(L/v))-(1+sum(L^2/v))*z
    }
    if(transformed) value <- value+u[1]+sum(u[p+seq_len(p)])
    gL <- gL-L/prior$loading_sd^2
    gL[1] <- gL[1]*L[1]+as.integer(transformed)
    gv <- gv-(prior$shape+1)+prior$rate/v+as.integer(transformed)
    list(value=value,gradient=c(gL,gv,gz))
  }
  # The value and gradient of the log posterior density at one point share the same calculations.
  previous <- result <- NULL
  at <- function(u) {
    if(!identical(u,previous)) {
      result <<- evaluate(u)
      previous <<- u
    }
    result
  }
  list(value=function(u) at(u)$value,gradient=function(u) at(u)$gradient)
}

In evaluate(), the marginal branch forms $\Sigma=\lambda\lambda^\top+\operatorname{diag}(\psi)$ through its Cholesky factor R and evaluates $-\tfrac12\lbrace n(p\log2\pi+\log\vert \Sigma\vert )+\operatorname{tr}(\Sigma^{-1}S)\rbrace $ with $S=Y^\top Y$ in scatter; with $A=\Sigma^{-1}S\Sigma^{-1}-n\Sigma^{-1}$, the derivatives are $A\lambda$ for the loadings and $A_{jj}\psi_j/2$ for the log variances. The joint branch uses the residual sums of squares rss, $\sum_i(y_{ij}-\lambda_jz_i)^2$, computed from scatter, $Y^\top z$ and $z^\top z$ unless they are too small to trust, and adds the standard normal factor density. Both branches then add the prior derivatives, $-\lambda/\sigma_\lambda^2$ for the loadings and $-(a+1)+b/\psi_j$ for each log variance, and, with transformed = TRUE, the Jacobian terms $u_1+\sum_ju_{4+j}$ and their derivatives of one. Because the first loading is stored as a logarithm, its derivative is multiplied by $\lambda_1$. The function at() evaluates both quantities once for each new u.

1
2
3
4
5
6
7
8
9
10
.libPaths(c(".R-library", .libPaths()))
source("code/lib/result.R")
source("code/lib/differentiation.R")
source("code/lib/quasi_newton.R")
source("code/lib/bayes_factor.R")
RNGkind("Mersenne-Twister","Inversion","Rejection")
Y <- readRDS("data/source/ch16/BAYES4.rds")
prior <- bayes4_prior()
initial <- bayes4_coordinates(rep(.6,4),rep(.5,4))
map_target <- bayes4_target(Y,prior,FALSE,TRUE)

In the call to bayes4_target(), the last argument requests the likelihood with the factors integrated out. The preceding FALSE selects the original-scale log density evaluated at the parameters represented by $u$. Its gradient still needs the chain rule because the optimizer works in $u$. No density Jacobian enters a search for this original-scale peak.

Where is the peak if intervals are measured in log variance? Consider one variance $v$ with the inverse gamma prior used for each unique variance. Write $\alpha=2$ for the shape and $\beta=1$ for the rate on the reciprocal. The derivative of its log density per unit of $v$ is $-(\alpha+1)/v+\beta/v^2$, which changes from positive to negative at $v=\beta/(\alpha+1)=1/3$. Now take $w=\log v$. An interval of small width $dw$ at $w$ covers an interval of width approximately $e^w dw$ in $v$. To assign these corresponding intervals the same probability, the density per unit of $w$ must include the absolute derivative $e^w$. Writing $C$ for a constant independent of $w$, its log density and derivative are

\[\log p_W(w)=-\alpha w-\beta e^{-w}+C, \qquad \frac{d}{dw}\log p_W(w)=-\alpha+\beta e^{-w}.\]

The maximum occurs at $w=\log(\beta/\alpha)=\log(1/2)$, corresponding to a variance of $1/2$. The two modes describe the same distribution measured against two different interval widths. For the factor model, TRUE in the third argument below requests the analogous density per unit of $u$. Before locating either mode, check the original-scale log density at the common starting point and the derivative of the transformed log density there. The function bayes4_pointwise() takes the observed response matrix, loadings and unique variances and returns one marginal log likelihood contribution per person, with the factor integrated out; Section 16.9 shows it. Summing these contributions and adding log_prior_bayes4() gives the original-scale log posterior up to its normalizing constant.

1
2
3
4
5
6
7
8
9
10
log_target <- bayes4_target(Y,prior,TRUE,TRUE)
at_mode <- function(target) bfgs(function(u)-target$value(u),
  function(u)-target$gradient(u),initial)
test_point <- bayes4_unpack(initial)
rowwise_target <- log_prior_bayes4(test_point$loading,test_point$variance,prior)+
  sum(bayes4_pointwise(Y,test_point$loading,test_point$variance))
stopifnot(abs(map_target$value(initial)-rowwise_target)<1e-8)
print(c(marginal_log_density_difference=map_target$value(initial)-rowwise_target,
  log_coordinate_gradient_difference=max(abs(log_target$gradient(initial)-
    num_grad(log_target$value,initial)$gradient))))
1
2
   marginal_log_density_difference log_coordinate_gradient_difference 
                      0.000000e+00                       1.803496e-08 

The first difference checks the log density against the sum of the 150 individual log likelihoods and the log prior density. The second compares the transformed log-density gradient to numerical derivatives of that same transformed function. The two checks use the same parameter values and test different functions.

A normal approximation at the mode

A mode also gives a local approximation to a whole distribution if the log density curves downward in every direction. To use a minimization routine, give it the negative log density and the negative of its gradient. The Broyden-Fletcher-Goldfarb-Shanno (BFGS) method uses changes in these gradients to update its search direction. Apply it once to each function from the same initial point. For a Laplace approximation, let $\hat u$ denote the returned mode of the transformed density and $K$ the negative Hessian of its log density there. A second-order Taylor expansion about a stationary point gives

\[\log\pi_u(u\mid Y)\ \approx\ \log\pi_u(\hat u\mid Y)-\tfrac12(u-\hat u)^\top K(u-\hat u).\]

If $K$ is positive definite, normalizing the exponential gives a normal density with mean $\hat u$ and covariance $K^{-1}$. The same quadratic used by laplace_approx() to integrate over a person’s factor now gives a covariance for the population parameters. Recalculate the Hessian from central differences of the transformed gradient at lapfit$par. This evaluates curvature at the reported point independently of the inverse-Hessian estimate accumulated during the search.

1
2
3
4
5
6
7
8
mapfit <- at_mode(map_target)
lapfit <- at_mode(log_target)
K <- -num_hess(log_target$value,lapfit$par,gr=log_target$gradient)$hessian
V <- chol2inv(chol(K))
print(list(original_scale_MAP=bayes4_unpack(mapfit$par),
  transformed_density_mode=lapfit$par,
  inverse_gamma_original_mode=prior$rate/(prior$shape+1),
  variance_at_log_variance_mode=prior$rate/prior$shape))
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
$original_scale_MAP
$original_scale_MAP$loading
[1] 0.7648938 0.5788471 0.9338263 0.6296112

$original_scale_MAP$variance
[1] 0.3682616 0.5287309 0.1871877 0.5397470

$original_scale_MAP$z
numeric(0)


$transformed_density_mode
[1] -0.2589847  0.5810583  0.9329605  0.6314045 -0.9907980 -0.6249912 -1.6255124
[8] -0.6030898

$inverse_gamma_original_mode
[1] 0.3333333

$variance_at_log_variance_mode
[1] 0.5

Both fits recorded converged after 14 iterations. The gradient and negative log-density Hessian provide the local assessment of these endpoints. The reason and iterations entries in each fit report the stopping decision.

The empty z in the unpacked MAP reflects the integration over the factors. The eight entries in transformed_density_mode follow the order of $u$. The final two named list elements reproduce the scalar example’s two modes, both expressed on the variance scale. To obtain means on the reporting scales, draw entire parameter vectors before undoing the logarithms.

1
2
3
4
set.seed(1602)
laplace_u <- sweep(matrix(rnorm(4000*8),4000)%*%chol(V),2,lapfit$par,"+")
original <- function(u) {b <- bayes4_unpack(u); c(b$loading,b$variance)}
laplace_draws <- t(apply(laplace_u,1,original))

The upper triangular matrix chol(V) is a Cholesky factor $U$ satisfying $U^\top U=V$. Right multiplication by $U$ turns each of the 4,000 independent standard normal row vectors into a draw with the required covariance. The columnwise addition centers those draws at lapfit$par. Applying original() to each row converts the logged entries back to a loading and four variances. Averaging these transformed draws allows the right tail of a loading or variance to contribute to its mean.

A variational lower bound

The Laplace fit uses the location of the peak and the curvature there. How could a distribution be fitted using information away from that peak? A variational approximation evaluates a criterion averaged over draws from a trial density. Let $q(u)$ be a normalized trial density and $p(Y,u)$ the joint density of the responses and transformed parameters, with the factors already integrated out. Its integral over $u$ is the marginal density $p(Y)$ of the observed sample under the prior. With finite expectations and positive densities on the support of $q$, substitute $p(Y,u)=p(Y)\pi_u(u\mid Y)$ into the expected log ratio. The resulting lower bound on the log marginal density of the observed sample satisfies

\[\mathcal L(q)=E_q[\log p(Y,u)-\log q(u)],\qquad \log p(Y)-\mathcal L(q) =E_q\!\left[\log\frac{q(u)}{\pi_u(u\mid Y)}\right]\geq 0.\]

The expectation on the right is the Kullback-Leibler divergence from $q$ to the posterior. Jensen’s inequality gives the bound since $E_q[\log(\pi_u/q)]\leq\log E_q[\pi_u/q]$. The normal trial densities used here are positive at every $u$, so $E_q[\pi_u/q]=\int\pi_u(u\mid Y)\,du=1$ and the logarithm on the right side of Jensen’s inequality is zero. Maximizing the bound over a chosen family minimizes that divergence because the data and $\log p(Y)$ are fixed. Unlike the observed log likelihood bound used when the population parameters are fixed, this bound includes their prior and integrates over them. In a variational fit for individual factor scores, a separate distribution can describe each person’s factors while the loadings are estimated as fixed numbers. Here the trial distribution describes the shared loadings and unique variances themselves. All 150 response vectors inform one distribution over eight parameters. Its spread gives an approximation to population-parameter uncertainty after observing these respondents.

To determine which density enters the bound, write $y_i$ for one person’s four responses and $\Sigma=\lambda\lambda^\top+\operatorname{diag}(\psi)$ for their covariance after integrating over a standard normal factor. At fixed loadings and unique variances, $y_i$ has a four-dimensional normal distribution with mean zero and covariance $\Sigma$. Summing its log density over the people gives the marginal log likelihood. Add the log prior density on the original scales, then account for the five positive parameters. In $g(u)$ the derivative of each exponentiated parameter is the parameter itself. The other three diagonal derivatives are one. Taking the log determinant therefore adds the logs of precisely the five positive parameters. If $\ell_\theta$ is the original-scale log likelihood plus log prior density, the log joint density required on the unconstrained scale is

\[\log p(Y,u)=\ell_\theta(g(u))+u_1+\sum_{j=1}^{4}u_{4+j}.\]

The function bayes4_target(Y,prior,TRUE,TRUE) gave log_target, whose value() and gradient() return this log joint density and its gradient; the variational fit below uses only these two functions. As a separate check of the formula and the coordinate order, the same density is also written as a program in Stan, a modeling language whose R interface rstan evaluates a program’s log density and gradient at a given point. The program is code/model_programs/bayes4_marginal.stan, and it serves only for this comparison. Compile it and create an object with zero sampling chains so that the program can be evaluated at exactly the point used for the Laplace expansion.

1
2
3
4
5
6
7
8
9
10
11
12
13
compile_program <- function(name) rstan::stan_model(file.path("code/model_programs",
  paste0(name,".stan")),
  model_name=name)
sampler_shell <- function(model,data) suppressMessages(rstan::sampling(model,data=data,
  chains=0L))
bayes4_data <- list(N=nrow(Y),J=ncol(Y),Y=Y,loading_sd=prior$loading_sd,shape=prior$shape,
  rate=prior$rate)
marginal_model <- compile_program("bayes4_marginal")
marginal_shell <- sampler_shell(marginal_model,bayes4_data)
print(c(Stan_minus_book=rstan::log_prob(marginal_shell,lapfit$par)-
  log_target$value(lapfit$par),
  gradient_gap=max(abs(rstan::grad_log_prob(marginal_shell,lapfit$par)-
    log_target$gradient(lapfit$par)))))
1
2
Stan_minus_book    gradient_gap
   3.410605e-13    1.140060e-13

At that point, the two log densities differ by about $3.4\times10^{-13}$ and the largest absolute difference between corresponding gradient components is about $1.1\times10^{-13}$. Agreement of values and slopes tests the model formula and coordinate order at this point. The choice of an approximating family is a separate step.

Mean-field variational Bayes approximates a joint posterior by a product of separate densities. Here each transformed parameter $u_k$ receives an independent normal density; this restriction belongs to the approximation, not to the posterior implied by the response model. For $k=1,\ldots,8$, write $m_k$ for its mean, $a_k$ for its log standard deviation, and $\epsilon_k$ for an independent standard normal draw. Then $u_k=m_k+\exp(a_k)\epsilon_k$. With the drawn $\epsilon$ fixed, differentiation makes the sampled vector a differentiable function of all sixteen variational parameters. Write $d_k(u)$ for the derivative of $\log p(Y,u)$ with respect to $u_k$. For one draw, the estimates of the two partial derivatives of the bound are

\[\widehat{\frac{\partial\mathcal L}{\partial m_k}}=d_k(u),\qquad \widehat{\frac{\partial\mathcal L}{\partial a_k}} =d_k(u)\exp(a_k)\epsilon_k+1.\]

The added one comes from differentiating the differential entropy $-E_q[\log q]$ of the normal trial density, which contains $a_k$. The function meanfield_gradient() in code/lib/variational.R computes both estimates from a standard normal vector e, with $d(u)$ from target$gradient(); with draws greater than one it averages the estimates over several vectors.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
meanfield_gradient <- function(target, mean, log_sd, draws = 1L) {
  d <- length(mean); for_mean <- numeric(d); for_log_sd <- numeric(d); kept <- 0L; failed <- 0L
  while (kept < draws) {
    e <- rnorm(d)
    u <- mean + exp(log_sd) * e
    g <- tryCatch(target$gradient(u), error = function(err) rep(NaN, d))
    if (all(is.finite(g))) {
      for_mean <- for_mean + g; for_log_sd <- for_log_sd + g * e; kept <- kept + 1L
    } else {
      failed <- failed + 1L
      if (failed >= 10L * draws) stop("the gradient of the lower bound could not be estimated")
    }
  }
  list(mean = for_mean / draws, log_sd = for_log_sd / draws * exp(log_sd) + 1)
}

A draw at which the gradient is not finite is replaced by a new draw. Monte Carlo estimates of the derivatives then update the sixteen means and log standard deviations to increase the bound.

Local optima and curvature in posterior approximations

A positive first loading assigns the factor a direction, but it imposes no requirement that the log posterior density or the variational bound have a single maximum. A local maximum can satisfy an optimization rule even when another region has more posterior probability. If the negative Hessian is not positive definite, the quadratic does not define the proposed normal approximation; a zero eigenvalue gives no finite variance in that direction. The Cholesky calculation then cannot give the specified covariance.

For a variational fit, do two runs on the same data give similar estimates of the bound? Run the same mean-field fit twice, with seeds 1602 and 1612 and random starting values. The function normal_variational_fit() runs meanfield_fit() from code/lib/variational.R and collects its progress and draws for comparison.

1
2
3
4
5
6
7
8
9
10
11
source("code/lib/stability.R")
source("code/lib/nuts.R")
source("code/lib/posterior_checks.R")
source("code/lib/variational.R")
normal_variational_fit <- function(seed) {
  RNGkind("Mersenne-Twister","Inversion","Rejection")
  set.seed(seed)
  fit <- meanfield_fit(log_target,8L,bayes4_report)
  list(seed=seed,eta=fit$eta,table=fit$table,draws=fit$draws[,1:8],converged=fit$converged,
    pareto_shape=fit$pareto_shape)
}

In normal_variational_fit(), meanfield_fit() starts from values drawn uniformly on $(-2,2)$ in each transformed coordinate, chooses the step-size scale, runs the updates and draws 1,000 vectors from the final approximation.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
meanfield_fit <- function(target, dimension, report, adapt_iterations = 50L, gradient_draws = 1L, bound_draws = 100L,
                          bound_every = 100L, tolerance = .01, max_iterations = 10000L, output_draws = 1000L) {
  start <- random_start(target, dimension)$u
  scale <- meanfield_step_scale(target, start, adapt_iterations, gradient_draws, bound_draws)
  state <- meanfield_state(start)
  window <- as.integer(max(.1 * max_iterations / bound_every, 2))
  changes <- numeric(); bound <- 0; best <- -.Machine$double.xmax
  table <- NULL; converged <- FALSE; iteration <- 0L
  repeat {
    iteration <- iteration + 1L
    g <- meanfield_gradient(target, state$mean, state$log_sd, gradient_draws)
    state <- meanfield_ascend(state, g, iteration, scale$eta)
    stop_now <- FALSE
    if (iteration %% bound_every == 0L) {
      previous <- bound
      bound <- meanfield_bound(target, state$mean, state$log_sd, bound_draws)
      best <- max(best, bound)
      changes <- tail(c(changes, abs((previous - bound) / bound)), window)
      mean_change <- mean(changes); median_change <- sort(changes)[length(changes) %/% 2L + 1L]
      table <- rbind(table, c(iteration = iteration, lower_bound = bound, relative_change_mean = mean_change,
        relative_change_median = median_change))
      if (mean_change < tolerance || median_change < tolerance) { converged <- TRUE; stop_now <- TRUE }
    }
    if (iteration == max_iterations) stop_now <- TRUE
    if (stop_now) break
  }
  e <- matrix(rnorm(output_draws * dimension), output_draws, dimension, byrow = TRUE)
  u <- sweep(sweep(e, 2, exp(state$log_sd), "*"), 2, state$mean, "+")
  log_density <- apply(u, 1, function(v) tryCatch(target$value(v), error = function(err) -Inf))
  log_approximation <- -rowSums(e^2) / 2 - sum(state$log_sd) - dimension * log(2 * pi) / 2
  ratio <- log_density - log_approximation
  ratio[ratio == -Inf] <- -800
  draws <- t(apply(u, 1, report))
  list(eta = scale$eta, step_scale_search = scale$tried, start = start, table = table, converged = converged,
    iterations = iteration, best_bound = best, mean = state$mean, log_sd = state$log_sd,
    draws = cbind(draws, log_density = log_density), log_approximation = log_approximation,
    pareto_shape = psis_weights(ratio, 1)$shape)
}

Here random_start() draws the start, meanfield_step_scale() chooses $\eta$ as described below, meanfield_state() sets the log standard deviations and the running averages to zero, and meanfield_bound() estimates the bound from bound_draws draws. Every bound_every iterations the relative change of the bound is added to changes, of which the last window, here ten, are used. After the loop, log_approximation is the log density of each output draw under the fitted normal distribution, and the Pareto shape is estimated from the log ratios ratio, with $-800$ in place of $-\infty$. The function bayes4_report() returns the loadings and variances of each draw on their reporting scales. The column names in table distinguish the bound from the mean and median relative changes that govern stopping.

The fit also diagnoses importance ratios, which compare posterior density to the fitted variational density at a draw. If the approximation assigns too little density to a region, a few draws there can receive large ratios and dominate a weighted estimate. The entry pareto_shape estimates the shape of the upper tail of these ratios with psis_weights(), described in Section 16.9; a value above 0.7 warns that importance resampling may be unreliable. The returned draws are not resampled, so each contributes equally to the variational mean.

1
2
3
4
5
vbfits <- lapply(c(1602L,1612L),normal_variational_fit)
print(do.call(rbind,lapply(vbfits,function(f) data.frame(seed=f$seed,eta=f$eta,
  iterations=max(f$table[,"iteration"]),initial_lower_bound=f$table[1,"lower_bound"],
  final_lower_bound=tail(f$table[,"lower_bound"],1L),converged=f$converged,
  pareto_shape=f$pareto_shape))))
1
2
3
4
5
6
             seed eta iterations initial_lower_bound final_lower_bound
lower_bound  1602   1        300           -741.3405         -740.8575
lower_bound1 1612   1        300           -804.1894         -801.5547
             converged pareto_shape
lower_bound       TRUE    0.8350917
lower_bound1      TRUE    0.3532403

In these variational fits, each iteration uses one independent standard normal vector for its gradient estimate. An initial adaptation selects a step-size scale $\eta$: from the same starting values, 50 iterations are run with each of 100, 10, 1, 0.1 and 0.01 in turn, and the search stops once a smaller scale gives a lower estimated bound than the best so far. At iteration $t$, meanfield_ascend() scales the gradient by $\eta/\sqrt t$ and divides each component by one plus the square root of a running average of its squared gradients.

1
2
3
4
5
6
7
8
9
10
11
12
13
meanfield_ascend <- function(state, g, iteration, scale) {
  if (iteration == 1L) {
    state$squares_mean <- state$squares_mean + g$mean^2
    state$squares_log_sd <- state$squares_log_sd + g$log_sd^2
  } else {
    state$squares_mean <- .9 * state$squares_mean + .1 * g$mean^2
    state$squares_log_sd <- .9 * state$squares_log_sd + .1 * g$log_sd^2
  }
  step <- scale / sqrt(iteration)
  state$mean <- state$mean + step * g$mean / (1 + sqrt(state$squares_mean))
  state$log_sd <- state$log_sd + step * g$log_sd / (1 + sqrt(state$squares_log_sd))
  state
}

Every 100 iterations, meanfield_bound() estimates the lower bound with 100 draws. The fit stops when the mean or median of the last ten relative changes, using the available changes when there are fewer than ten, falls below 0.01, or when it reaches 10,000 iterations. Each assessment uses fresh simulated values, so the estimated bound can fall between assessments even with little change in the fitted distribution.

Both runs selected $\eta=1$ and stopped at iteration 300. The first run’s estimated bound went from $-741.341$ at iteration 100 to $-741.724$ at iteration 200 and $-740.858$ at iteration 300. In the second run, it rose from $-804.189$ to $-799.820$ and then fell to $-801.555$. At iteration 300, the final relative_change_median entries of the two tables were 0.0012 and 0.0055, respectively. Both meet the stopping rule, although the final estimated bounds differ by about 61, so the two runs did not reach the same approximation. The Pareto shape estimate of 0.84 for the first run exceeds the warning threshold of 0.7 for importance resampling; the estimate for the second run is 0.35. Selecting the larger of the two final estimated bounds favors seed 1602 here. The comparison uses simulated estimates of the bound.

The first loading under each approximation

For the first response, a one-unit increase in the factor changes the conditional mean by the value of its loading. How do the approximations summarize that change? The output label MAP gives the loading at the original-scale joint mode located by the optimizer. The transformed-density mode instead has first coordinate $-0.2589847$, the log of a loading. Exponentiating gives $0.771835$ on the loading scale. For a normal approximation on the log scale, exponentiating its center gives the median of the implied lognormal distribution. Its mean is $\exp(\hat u_1+V_{11}/2)$, which also depends on the log-scale variance. The column VA_SD measures spread within the fitted variational distribution on the loading scale. It approximates posterior uncertainty about the change in response per factor unit and can be compared with a posterior standard deviation (SD) obtained by another method. Select the indicated variational fit, then read the first loading in each column of the comparison.

1
2
3
4
vb <- vbfits[[which.max(vapply(vbfits,function(r)tail(r$table[,"lower_bound"],1L),0.0))]]
print(data.frame(parameter=paste0("loading",1:4),MAP=bayes4_unpack(mapfit$par)$loading,
  Laplace_mean=colMeans(laplace_draws)[1:4],VA_mean=colMeans(vb$draws)[1:4],
  VA_SD=apply(vb$draws[,1:4],2,sd)))
1
2
3
4
5
           parameter       MAP Laplace_mean   VA_mean      VA_SD
loading[1]  loading1 0.7648938    0.7768110 0.7699470 0.05788676
loading[2]  loading2 0.5788471    0.5821511 0.5688070 0.05936653
loading[3]  loading3 0.9338263    0.9328082 0.9329200 0.05082698
loading[4]  loading4 0.6296112    0.6316890 0.6892892 0.07201829

The original-scale MAP estimate is 0.76489. The mean from 4,000 back-transformed Laplace draws is 0.77681, and the selected variational draws give mean 0.76995 and standard deviation 0.05789. A numerical gradient check does not establish whether that spread is realistic. At the starting point, the zero difference for map_target$value(initial) compares the original-scale log density with a separate sum over people. The discrepancy of $1.803496\times10^{-8}$ compares log_target$gradient(initial) with numerical derivatives of the transformed log density, whose Jacobian adds one to the gradient entries for the five logged parameters. Both checks concern evaluation of the chosen density. Assessing uncertainty calls for a comparison in which the posterior spread is known.

Mean-field variances for correlated parameters

A mean-field approximation treats the parameters as independent. Consider a bivariate normal posterior with mean vector $\mu$, unit marginal variances and correlation 0.8. Its covariance matrix is $R$ and its precision matrix is $P=R^{-1}$. Approximate it by independent normals with means $m$ and diagonal covariance $D=\operatorname{diag}(v_1,v_2)$. Under these normals, the expected quadratic term in the log posterior density equals $(m-\mu)^\top P(m-\mu)+\operatorname{tr}(PD)$. The differential entropy of the normal trial density contributes $\tfrac12\log\vert D\vert $ plus a constant. Up to a constant, twice the divergence to be minimized is

\[(m-\mu)^\top P(m-\mu)+P_{11}v_1+P_{22}v_2-\log v_1-\log v_2+C.\]

Positive definiteness puts the minimum in $m$ at $\mu$. Differentiating in each $v_j$ gives $P_{jj}-1/v_j=0$, so that $v_j=1/P_{jj}$. For two unit variances and correlation $\rho$, each diagonal of $P$ is $1/(1-\rho^2)$. The calculation compares these reciprocal precision entries with the actual marginal variances.

1
2
3
Rho <- matrix(c(1,.8,.8,1),2)
print(data.frame(coordinate=1:2,exact_variance=diag(Rho),
  mean_field_variance=1/diag(solve(Rho))))
1
2
3
  coordinate exact_variance mean_field_variance
1          1              1                0.36
2          2              1                0.36

At $\rho=0.8$, both approximate means are exact and each approximate variance is $1-0.8^2=0.36$. In this normal example, $1/P_{jj}$ is the variance of coordinate $j$ conditional on the other coordinate. Its marginal variance of one also includes variation in the conditional mean as the other coordinate changes. The independence restriction explains the shortfall here. For a nonnormal loading posterior, neither the exact mean nor the size of a variance discrepancy follows from this calculation. For the factor model, compare the printed Laplace and variational summaries with posterior draws on the same loading scale. The file data/derived/ch16/analysis.rds can be opened with readRDS(). Its MAP and laplace entries contain the two optimizer records. Each variational entry contains its seed, step-size scale, table of estimated lower bounds and relative changes, the 1,000 draws of the loadings and variances, and the Pareto shape estimate. The supplied meanfield_fit() is translated from the mean-field variational algorithm of Stan (code/NOTICE.md); in R, the rstan package provides this fit.

16.3 Gibbs sampling for linear factor models and linear mixed models

The first person in BAYES4 gave four responses, approximately $-0.91$, $-1.19$, $-1.94$ and $-1.85$. At given loadings and unique variances, these responses determine the conditional normal distribution of the person’s factor. Its mean and variance can be calculated again whenever the item parameters change. Write $y_{ij}=\lambda_j z_i+e_{ij}$ for response $j$ from person $i$, with $z_i\sim N(0,1)$ and independent errors $e_{ij}\sim N(0,\psi_j)$ independent of the factor. Each $\psi_j$ is the item’s unique variance. There are 150 independent people, four responses per person and no item intercepts.

A full conditional is the distribution of one unknown, or a block of unknowns, given the observations and all remaining unknowns. A Gibbs sampler replaces each block by a draw from this distribution, using the latest values of the other blocks. Here one sweep updates the person factors, the item loadings and the unique variances in that order. For one person’s factor, collect the terms of twice the negative log density that involve $z_i$ and complete the square.

\[z_i^2+\sum_{j=1}^4\frac{(y_{ij}-\lambda_jz_i)^2}{\psi_j} =\frac{(z_i-m_i)^2}{v}+\text{constant},\qquad v=\left(1+\sum_{j=1}^4\frac{\lambda_j^2}{\psi_j}\right)^{-1}, \qquad m_i=v\sum_{j=1}^4\frac{\lambda_j y_{ij}}{\psi_j}.\]

The standard normal factor distribution contributes one unit of precision. An item contributes more precision when its loading is large in magnitude and its unique variance is small. Because everyone answered the same items, all 150 factors have the same conditional variance $v$ at these parameter values. Each person’s four responses determine a separate mean $m_i$.

Why do these conditional draws yield a sampler for the joint posterior? If the joint state has the posterior distribution, leaving the other blocks unchanged and drawing $z_i$ conditionally reproduces that same joint distribution. A complete sequence of such updates also preserves it. Consecutive states share information through the quantities used in the updates, so retained draws can be correlated. Preservation of the posterior is distinct from convergence to it from the chosen initial state. A proper posterior, a transition rule that can reach its relevant regions, and adequate run length must be considered separately.

Given the newly drawn factors, the update for each loading is a regression of one item’s 150 responses on the 150 factor values. Its prior is the $N(0,4)$ distribution, truncated to positive values for the first loading. For item $j$, the terms in twice the negative log density on its allowed range are $\lambda_j^2/4+\sum_i(y_{ij}-z_i\lambda_j)^2/\psi_j$. The coefficient of $\lambda_j^2$ gives the conditional precision, and the cross product of factors and responses gives the numerator of the conditional mean. Before imposing the sign constraint, the normal variance and mean are

\[V_j=\left(\frac14+\frac{\sum_i z_i^2}{\psi_j}\right)^{-1}, \qquad a_j=V_j\frac{\sum_i z_i y_{ij}}{\psi_j}.\]

For items two through four, draw directly from $N(a_j,V_j)$. Reversing every loading and every factor together leaves each fitted response unchanged. Requiring $\lambda_1>0$ fixes the direction in which a person’s score is reported. For the first item, draw from the normal repeatedly until the draw is positive. Conditional on acceptance, the draw has exactly the $N(a_1,V_1)$ distribution truncated to positive values, whose mean and variance differ from $a_1$ and $V_1$. Its probability of acceptance on each attempt is $p=\Phi(a_1/\sqrt{V_1})$, where $\Phi$ is the standard normal distribution function. The expected number of attempts is $1/p$. When $a_1$ lies several multiples of $\sqrt{V_1}$ below zero, most attempts fail the sign constraint.

Each unique variance can now be updated from discrepancies on the scale of its own item. Form $e_{ij}=y_{ij}-\lambda_j z_i$ with the current factors and loadings. For $\psi_j>0$ and $n=150$ people, the normal likelihood is proportional to $\psi_j^{-n/2}\exp[-\sum_i e_{ij}^2/(2\psi_j)]$ as a function of $\psi_j$. Under the prior, the precision $1/\psi_j$ has a gamma density with shape two and unit rate. Expressed on the variance scale, this prior density is proportional to $\psi_j^{-3}\exp(-1/\psi_j)$. Collecting the power and the exponential gives

\[\psi_j\mid Y,z,\lambda,\psi_{-j}\sim IG\left(2+\frac n2,\;1+\frac12\sum_i e_{ij}^2\right).\]

Draw a gamma precision with shape $77$ and rate $1+\sum_i e_{ij}^2/2$, then take its reciprocal. A larger residual sum of squares increases the rate for the precision and thus favors a larger unique variance. The sum uses one column of 150 measurements. By comparison, the uncertainty $v$ about one person’s score uses all four items in one row. Feeding the four updated unique variances back into $v$ lets the next set of person draws reflect how much information each item supplies.

Implementing the factor-model sampler

The three parts of factor_gibbs() below form a single function in code/lib/factor_gibbs.R. The first part initializes the chain and draws the factors at the current loadings and unique variances.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
factor_gibbs <- function(X,Lambda,Psi,load_sign,load_prior_mean,
  load_prior_prec,
  a0,b0,burnin=1000L,n_draws=20000L,thin=1L,seed=12345L,score_rows=integer(),
  max_redraws=Inf) {
  K <- ncol(X); N <- nrow(X); D <- ncol(Lambda)
  rng <- mt_generator(seed)
  psi <- diag(Psi)
  phi <- matrix(0,N,D)
  kept <- 0L
  stopifnot(length(thin) == 1L, is.finite(thin), thin >= 1, thin == floor(thin),
    length(n_draws) == 1L, is.finite(n_draws), n_draws >= thin,
    n_draws == floor(n_draws), n_draws %% thin == 0)
  n_keep <- n_draws%/%thin
  out <- matrix(NA_real_,n_keep,K*D+K)
  scores <- matrix(NA_real_,n_keep,length(score_rows)*D)
  for(iter in 0:(burnin+n_draws-1L)) {
    # Draw one factor for each person at the current item parameters.
    A <- Lambda/sqrt(psi)
    phi_var <- chol2inv(chol(diag(D)+crossprod(A)))
    phi_C <- t(chol(phi_var))
    phi_mean <- X%*%(Lambda/psi)%*%phi_var
    z <- matrix(mt_normal(rng,N*D),N,D,byrow=TRUE)
    phi <- z%*%t(phi_C)+phi_mean

The matrix X contains the observed responses, Lambda contains the loadings and psi contains the diagonal of the residual covariance. Here the number of factors D is one. In the factor update, phi_var is $v$, and row $i$ of phi_mean is $m_i$. The array named z in the function supplies fresh standard normal noise. The resulting factor draws $z_i$ are in phi. The call mt_generator(seed) creates the local random-number state rng for this chain. The function mt_normal(rng, n) returns n standard normal draws and advances that state; the inverse gamma draws use the same state.

The next part draws the item loadings conditional on these new factors.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
    # Draw each loading using the new factors.
    for(i in seq_len(K)) {
      prec <- load_prior_prec[i,]
      V <- chol2inv(chol(diag(prec,D)+crossprod(phi)/psi[i]))
      C <- t(chol(V))
      m <- V%*%(prec*load_prior_mean[i,]+crossprod(phi,X[,i])/psi[i])
      redraws <- 0
      repeat {
        draw <- drop(C%*%mt_normal(rng,D)+m)
        if(min(0,load_sign[i,]*draw)>=0) break
        redraws <- redraws+1
        if(redraws>=max_redraws) stop(sprintf(
          "loading row %d not drawn within %g redraws at iteration %d",
          i,max_redraws,iter+1L))
      }
      Lambda[i,] <- draw
    }

In this loading update, the index i runs over items. The scalar entries of V and m give $V_j$ and $a_j$. Only the first row of load_sign imposes a sign, so the other three normals are accepted on the first attempt. The variable redraws counts unsuccessful attempts. The argument max_redraws can limit them for one update. Its default is Inf; the calibration fits in Section 16.10 set it to one million. Reaching that limit stops the fit without producing a draw from the truncated distribution.

Finally, mt_inverse_gamma() draws a reciprocal gamma with the shape and rate just derived. The function stores the new loadings and variances in one matrix and the selected person’s factor in the corresponding row of a second matrix.

1
2
3
4
5
6
7
8
9
10
11
12
13
    # Draw each unique variance and keep the requested coordinates.
    for(i in seq_len(K)) {
      e <- X[,i]-phi%*%Lambda[i,]
      psi[i] <- mt_inverse_gamma(rng,(a0[i]+N)*.5,(b0[i]+sum(e*e))*.5)
    }
    if(iter>=burnin && iter%%thin==0L) {
      kept <- kept+1L
      out[kept,] <- c(t(Lambda),psi)
      if(length(score_rows)) scores[kept,] <- c(t(phi[score_rows,,drop=FALSE]))
    }
  }
  list(draws=out,scores=scores,Lambda=Lambda,psi=psi,phi=phi,uniforms=rng$draws)
}

The wrapper bayes4_gibbs() supplies the starting values and priors for the BAYES4 fit and names the retained population parameters.

1
2
3
4
5
6
7
8
9
10
bayes4_gibbs <- function(Y,prior,seed,burnin=1000L,n_draws=20000L,score_rows=integer(),
  max_redraws=Inf) {
  J <- ncol(Y)
  fit <- factor_gibbs(Y,matrix(c(.5,rep(0,J-1L)),J),.5*diag(diag(var(Y))),
    matrix(c(1,rep(0,J-1L)),J),matrix(0,J,1L),matrix(1/prior$loading_sd^2,J,1L),
    rep(2*prior$shape,J),rep(2*prior$rate,J),burnin,n_draws,seed=seed,score_rows=score_rows,
    max_redraws=max_redraws)
  colnames(fit$draws) <- c(paste0("loading",seq_len(J)),paste0("variance",seq_len(J)))
  fit
}

For the specified prior, bayes4_gibbs() sets the loading prior precision to $1/4$. It supplies twice the inverse gamma shape and rate because factor_gibbs() halves these arguments in its variance update. The eight columns of draws contain the four loadings followed by the four unique variances.

Chains for the BAYES4 responses

To fit one chain, run the following from the book directory. Use the observed matrix as stored, without centering its columns. The four starting loadings are $(0.5,0,0,0)$ and each starting unique variance is half the corresponding sample variance.

1
2
3
4
5
6
7
8
9
10
11
12
.libPaths(c(".R-library", .libPaths()))
source("code/lib/stability.R")
source("code/lib/factor_gibbs.R")
source("code/lib/bayes_factor.R")
RNGkind("Mersenne-Twister", "Inversion", "Rejection")

Y <- readRDS("data/source/ch16/BAYES4.rds")
prior <- bayes4_prior()
fit <- bayes4_gibbs(Y, prior, 1016031L, score_rows=1L)
print(colMeans(fit$draws))
print(apply(fit$draws, 2L, sd))
print(c(mean=mean(fit$scores[, 1]), variance=var(fit$scores[, 1])))
1
2
3
4
5
6
7
8
 loading1  loading2  loading3  loading4 variance1 variance2 variance3 variance4 
0.7816719 0.5895678 0.9472565 0.6411124 0.3798134 0.5460532 0.2041480 0.5580023 
  loading1   loading2   loading3   loading4  variance1  variance2  variance3 
0.07332722 0.07462664 0.07050915 0.07686992 0.05809694 0.06983063 0.04928680 
 variance4 
0.07168354 
      mean   variance 
-1.7061408  0.1267296 

With seed 1016031, the first loading averages 0.7816719 and the first person’s factor averages $-1.7061408$. At a draw with four positive loadings, each of this person’s responses contributes a negative term to the conditional mean. Both summaries use 20,000 draws after 1,000 burn-in sweeps. For four chains, repeat the call with seeds 1016031 through 1016034. The starts and lengths remain the same, and each seed initializes a separate random number sequence. Different seeds do not disperse these identical initial parameter values. Agreement among these chains cannot rule out a region missed by all four.

1
2
3
4
factor_chains <- lapply(1016030L + 1:4, function(seed) {
  fit <- bayes4_gibbs(Y, prior, seed, score_rows=1L)
  cbind(fit$draws, z1=fit$scores[,1])
})

Column nine adds the first person’s factor to the eight named parameters. Storing each chain in a separate matrix preserves the order of its draws. The number of sweeps is fixed in advance.

The file data/derived/ch16/factor-gibbs-chains.rds contains the four matrices from these fits. They make it possible to estimate the posterior spread of the first person’s factor and then examine how uncertainty in the item parameters contributes to that spread. First, retain the chain index when summarizing any column. In the summary, sd estimates posterior spread, while the Monte Carlo standard error (MCSE) estimates simulation uncertainty in the reported mean.

The other columns assess agreement between chains and the precision of their draws. Split Rhat compares variation within and between half-chains, using both pooled ranks transformed to normal scores and ranked distances from the pooled median. Values appreciably above one signal disagreement in location or spread. Bulk effective sample size (ESS_bulk) assesses the precision of averages of the normal rank scores. Tail ESS is the smaller effective size for indicators at the pooled 5th and 95th percentiles. Neither replaces the effective size on the original scale used for a mean’s MCSE; 16.8 develops these calculations.

The following calculation from code/practice/16.3-four-chains.R puts the 20,000 successive draws down the rows and the four chains across the columns for each quantity. The function chain_summary() takes this matrix and returns the six named summaries just described; Section 16.8 shows it and the diagnostics it uses.

1
2
3
4
5
6
7
8
9
source("code/lib/posterior_checks.R", local=TRUE)
gibbs <- readRDS("data/derived/ch16/factor-gibbs-chains.rds")
parameters <- colnames(gibbs[[1]])
# For one parameter, each column is a chain and each row a retained iteration.
summary_table <- t(vapply(parameters, function(parameter) {
  chains <- do.call(cbind, lapply(gibbs, function(chain) chain[,parameter]))
  chain_summary(chains)
}, c(mean=0,sd=0,Rhat=0,ESS_bulk=0,ESS_tail=0,MCSE=0)))
print(summary_table)
1
2
3
4
5
6
7
8
9
10
                mean         sd     Rhat  ESS_bulk ESS_tail         MCSE
loading1   0.7800641 0.07334142 1.000428 14637.636 28287.57 0.0006080674
loading2   0.5894020 0.07488087 1.000066 23192.911 41123.71 0.0004929218
loading3   0.9465505 0.07159855 1.000450  9152.984 16918.37 0.0007505739
loading4   0.6400516 0.07732123 1.000128 20753.035 36747.83 0.0005382885
variance1  0.3796726 0.05767032 1.000077 22305.477 35944.20 0.0003816231
variance2  0.5463631 0.06937791 1.000093 50900.383 64624.80 0.0003050165
variance3  0.2032209 0.04934914 1.000430  8765.964 15827.93 0.0005166813
variance4  0.5590971 0.07174963 1.000048 48593.220 64839.93 0.0003227993
z1        -1.7063825 0.35676106 1.000007 47256.950 65058.24 0.0016425424

Over all four chains the mean and standard deviation of the first loading are 0.78006 and 0.07334. For the first person’s factor they are $-1.7064$ and 0.3568. The latter SD describes uncertainty about the person’s factor given the measurements. The Monte Carlo standard error (MCSE) of 0.00164 describes the simulation precision of the estimated mean score. The Rhat value of 1.000007 shows close agreement for this score by the split-chain comparison.

To separate the sources of the person’s posterior uncertainty, let $\theta=(\lambda,\psi)$. Conditional on $Y$ and a draw of $\theta$, the score has known mean $m_1(\theta)$ and variance $v(\theta)$. The law of total variance gives

\[\operatorname{Var}(z_1\mid Y) =E_{\theta\mid Y}[v(\theta)]+\operatorname{Var}_{\theta\mid Y}[m_1(\theta)].\]

Pool the 80,000 rows for these two moments. In each row conditional_variance uses the eight population parameters, and conditional_mean combines the same parameters with the first person’s observed responses.

1
2
3
4
5
6
7
8
9
Y <- readRDS("data/source/ch16/BAYES4.rds")
pooled <- do.call(rbind,gibbs)
loading <- pooled[,1:4]
variance <- pooled[,5:8]
conditional_variance <- 1/(1+rowSums(loading^2/variance))
conditional_mean <- conditional_variance * drop((loading/variance) %*% Y[1,])
variance_terms <- c(mean_conditional_variance=mean(conditional_variance),
                    variance_of_conditional_mean=var(conditional_mean))
print(c(variance_terms, total=sum(variance_terms), sampled=var(pooled[,"z1"])))
1
2
3
4
   mean_conditional_variance variance_of_conditional_mean 
                  0.11704148                   0.01001653 
                       total                      sampled 
                  0.12705801                   0.12727845 

Averaging the conditional variances gives 0.11704. As the loadings and unique variances change, the conditional mean also moves, contributing 0.01002. Together they give 0.12706, close to the empirical variance 0.12728 of the sampled scores. The identity is exact for the posterior moments. Its two sides use different Monte Carlo estimates and can differ at finite run length. Reporting only the first term would discard nearly eight percent of the variance in this calculation.

For the first loading in the one-factor model for BAYES4, the approximations in Section 16.2 and the Gibbs draws refer to the same observed responses, sign convention and reporting scale. The Laplace approximation gave 0.77681 for the mean after transforming individual draws back to the loading scale. The independent normal variational approximation gave a mean of 0.76995 and an SD of 0.05789. The four Gibbs chains gave 0.78006 and 0.07334. Thus the variational fit places its center lower and gives a narrower spread for this loading. The Laplace mean is closer to the sampled mean, although agreement of means alone provides no check on the tails. The Gibbs comparison also depends on how well the chains explore the posterior, a question the chain-specific diagnostics address.

The supplied factor_gibbs() is translated from MCMCfactanal of MCMCpack, including its random number generator (code/NOTICE.md). The mixed-model sampler used next for the growth data, random_coefficient_gibbs(), is translated in the same way from the Gaussian-response sampler of MCMCglmm. Each package serves only as a comparison: Section 16.10 runs it with the same seed or random number stream. The one-factor model for BAYES4 fixes the response intercepts at zero and leaves the observed columns uncentered. An external factor-analysis call that centers them would use different data for this likelihood comparison.

Growth trajectories with random intercepts and slopes

Normal full conditionals also support Gibbs sampling for person-specific growth trajectories. In the simulated GROWTH4 data, each participant has a random intercept and a random slope. Each of 200 independent participants has measurements at times zero through three. Write $y_i$ for the four responses in time order and $Z$ for the four-row design with row $(1,t)$ at time $t$. Both the population coefficients $\beta$ and the person’s deviations $b_i$ use this design. The Bayesian linear mixed model specifies

\[y_i=Z\beta+Zb_i+\epsilon_i,\qquad b_i\sim N_2(0,G),\qquad \epsilon_i\sim N_4(0,\sigma^2I_4).\]

The deviations are independent of the measurement errors. The first coefficient of $\beta$ is the population mean at time zero and the second is the mean change per occasion. The two entries of $b_i$ are that person’s deviations from these population coefficients. Thus $G_{11}$ is the between-person variance of initial levels, in squared response units, and $G_{22}$ is the variance of rates of change, in squared response units per squared occasion unit. The covariance $G_{21}$ has units of squared response per occasion; a positive value associates higher initial levels with larger slopes. The residual variance $\sigma^2$ describes variation around each person’s trajectory at a given occasion, in squared response units, and is shared by all four occasions.

Use independent priors $\beta\sim N_2(0,100I_2)$, $G\sim IW(q+2,I_q)$ for $q=2$ random coefficients, and $\sigma^2\sim IG(2,1)$. Transposing the wide response matrix before taking its entries puts one participant’s four measurements together in the long data.

1
2
3
4
5
6
Gdata <- readRDS("data/source/ch07/GROWTH4.rds")
Z <- cbind(1,0:3)
growth_long <- data.frame(y=as.vector(t(Gdata$wide)),time=rep(0:3,nrow(Gdata$wide)),
  id=factor(rep(seq_len(nrow(Gdata$wide)),each=4L)))
growth_prior <- list(B=list(mu=c(0,0),V=diag(100,2)),G=list(G1=list(V=diag(2)/4,nu=4)),
  R=list(V=.5,nu=4))

In B, mu and V are the prior mean and covariance of the fixed effects. For G1, the inverse Wishart degrees of freedom are nu and its scale matrix equals nu*V, here $4(I_2/4)=I_2$. The univariate residual prior in R has gamma precision shape $\nu/2=2$ and rate $\nu V/2=1$. These choices specify a posterior for the growth trajectories and their population distribution. In this parameterization V is a scaled prior matrix, not the prior mean of $G$. The mapping $S=\nu V$ is the one documented by MCMCglmm::rIW(); random_coefficient_gibbs() takes its priors in the same form.

Given the variance components, the normal likelihood and normal priors make the fixed and random coefficients jointly normal conditional on the responses. To see the information for one person at given $\beta$, subtract $Z\beta$ from $y_i$. Combining the resulting regression with the prior for $b_i$ gives precision $Q_b=G^{-1}+Z^\top Z/\sigma^2$ and mean $Q_b^{-1}Z^\top(y_i-Z\beta)/\sigma^2$. For $\beta$ at given person effects, subtract $Zb_i$ instead and collect the contributions from all $N=200$ participants. Its precision is $Q_\beta=0.01I_2+NZ^\top Z/\sigma^2$ and its mean is $Q_\beta^{-1}Z^\top\sum_i(y_i-Zb_i)/\sigma^2$. These conditional expressions show the contributions from the data and priors; the sampler used here draws the fixed and random effects together from their joint normal update.

The variance conditionals use the current coefficients. For $G$, each person’s normal density supplies a power of $\vert G\vert $ and an outer product $b_i b_i^\top$. For $\sigma^2$, each of the 800 scalar measurements contributes a squared residual. Write $b$ for all person effects and $r_i=y_i-Z(\beta+b_i)$ for each person’s residual vector. The two full conditionals reduce to

\[G\mid b\sim IW\left(204,\;I_2+\sum_i b_ib_i^\top\right),\qquad \sigma^2\mid\beta,b,Y\sim IG\left(402,\;1+\tfrac12\sum_i r_i^\top r_i\right).\]

To sample $G$, generate a Wishart matrix with $q+2+N=204$ degrees of freedom and scale equal to the inverse of the updated scale matrix, then invert the draw; inverse_wishart_draw() does this. The residual variance has shape $2+800/2=402$ because it is shared by all four occasions. The function random_coefficient_gibbs() in code/lib/mixed_gibbs.R takes the response, the fixed-effects design, the design of the random coefficients and the participant factor. Here both designs have rows $(1,t)$, and $G$ is an unrestricted covariance matrix of each participant’s intercept and slope deviations. Each iteration draws the fixed and random coefficients jointly, then $G$, then $\sigma^2$, and the person coefficients are retained. The three parts below form the function.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
random_coefficient_gibbs <- function(y, X, U, group, prior, start_G = prior$G[[1L]]$V, start_R = prior$R$V,
                                     iterations = 13000L, burnin = 3000L, thin = 10L, store_random = TRUE,
                                     group_name = "group") {
  U <- as.matrix(U); n <- length(y); p <- ncol(X); q <- ncol(U)
  group <- as.factor(group); levels_ <- levels(group); m <- length(levels_); level <- as.integer(group)
  stopifnot(nrow(X) == n, nrow(U) == n, !anyNA(level))
  G_prior <- prior$G[[1L]]
  start_G <- as.matrix(start_G); start_R <- as.matrix(start_R)
  # The translated function draws starting liabilities before sampling. A Gaussian response does not use them;
  # drawing them aligns the random stream with the translated program.
  rnorm(n)
  spread <- sort(rnorm(n, mean(y), sqrt(var(y))))
  spread <- spread[rank(y, ties.method = "random")]
  rnorm(n, mean(y) + .8 * (spread - mean(y)), sqrt(var(y) * (1 - .8^2)))
  B_precision <- solve(prior$B$V)
  stopifnot(all(B_precision[row(B_precision) != col(B_precision)] == 0))
  B_root <- sqrt(diag(B_precision))
  G_scale <- as.matrix(G_prior$V * G_prior$nu)
  R_scale <- as.matrix(prior$R$V * prior$R$nu)
  # Cross-products within each level: entries (k, l) of U_i'U_i and (a, k) of X_i'U_i, one row per level.
  UtU <- array(0, c(m, q, q)); XtU <- array(0, c(m, p, q))
  for (k in seq_len(q)) {
    for (l in seq_len(q)) UtU[, k, l] <- rowsum(U[, k] * U[, l], level, reorder = TRUE)[, 1L]
    for (a in seq_len(p)) XtU[, a, k] <- rowsum(X[, a] * U[, k], level, reorder = TRUE)[, 1L]
  }
  XtX <- crossprod(X)
  G <- start_G; R <- start_R
  G_inverse <- spd_inverse(G); G_root <- row_cholesky(G_inverse)
  R_inverse <- spd_inverse(R); R_root <- row_cholesky(R_inverse)
  stored_draws <- (iterations - burnin) %/% thin
  random_names <- paste0(rep(colnames(U), each = m), ".", group_name, ".", rep(levels_, q))
  location_draws <- matrix(NA_real_, stored_draws, p + if (store_random) q * m else 0L,
    dimnames = list(NULL, c(colnames(X), if (store_random) random_names)))
  variance_draws <- matrix(NA_real_, stored_draws, q * q + 1L)
  stored <- 0L
  for (iteration in 0:(iterations - 1L)) {

The first part prepares the run. Before sampling, MCMCglmm draws starting values for latent responses that a normal response does not use; the three calls of rnorm() after the comment use the same random numbers, so the later draws follow the translated program’s stream. The prior covariance of the fixed effects must be diagonal, and B_root contains the square roots of its precisions. The scale matrices of the two inverse Wishart priors are nu*V, as described above. The cross-products $U_i^\top U_i$ and $X_i^\top U_i$ of each participant are computed once, in UtU and XtU. The chain starts with $G$ and $\sigma^2$ equal to the prior matrices V. Here spd_inverse() inverts a positive definite matrix through its Cholesky factor, and row_cholesky() returns the lower Cholesky factor, so G_root and R_root are lower factors of $G^{-1}$ and $1/\sigma^2$.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
    # A draw of (beta, b, e) from their priors.
    beta_prior <- rnorm(p) / B_root + prior$B$mu
    b_prior <- matrix(rnorm(m * q), m, q, byrow = TRUE)
    for (j in q:1) {
      for (l in seq_len(q - j) + j) b_prior[, j] <- b_prior[, j] - G_root[l, j] * b_prior[, l]
      b_prior[, j] <- b_prior[, j] / G_root[j, j]
    }
    e_prior <- rnorm(n) / R_root[1L, 1L]
    pseudo <- y - (e_prior + drop(X %*% beta_prior) + rowSums(U * b_prior[level, , drop = FALSE]))
    # Mixed model equations for the pseudo-observation, solved by eliminating each level's block.
    r <- R_inverse[1L, 1L]
    rhs_beta <- r * drop(crossprod(X, pseudo))
    rhs_b <- r * rowsum(U * pseudo, level, reorder = TRUE)
    block <- r * UtU
    for (k in seq_len(q)) for (l in seq_len(q)) block[, k, l] <- block[, k, l] + G_inverse[k, l]
    root <- level_cholesky(block)
    solved_rhs <- level_solve(root, rhs_b)
    solved_X <- array(0, c(m, q, p))
    for (a in seq_len(p)) solved_X[, , a] <- level_solve(root, r * matrix(XtU[, a, ], m, q))
    schur <- r * XtX + B_precision
    schur_rhs <- rhs_beta
    for (a in seq_len(p)) {
      schur_rhs[a] <- schur_rhs[a] - sum(r * XtU[, a, ] * solved_rhs)
      for (a2 in seq_len(p)) schur[a, a2] <- schur[a, a2] - sum(r * XtU[, a, ] * solved_X[, , a2])
    }
    beta <- solve(schur, schur_rhs)
    b <- solved_rhs
    for (a in seq_len(p)) b <- b - solved_X[, , a] * beta[a]
    beta <- beta + beta_prior
    b <- b + b_prior

The second part draws $\beta$ and every $b_i$ together. Write $\theta$ for these coefficients, $W$ for their combined design and $C$ for the precision of their joint full conditional, $W^\top W/\sigma^2$ plus the prior precisions. The code first draws $\theta^\ast$ from the prior and $e^\ast$ from $N(0,\sigma^2I)$. The rows of b_prior start as standard normal draws, and solving with the transpose of G_root gives them covariance $G$. It then forms pseudo, the response minus $W\theta^\ast+e^\ast$. Solving the mixed model equations $C\tilde\theta=W^\top(y-W\theta^\ast-e^\ast)/\sigma^2$ and adding $\theta^\ast$ gives a vector with mean $C^{-1}W^\top y/\sigma^2$ and covariance $C^{-1}$. These are the moments of the joint full conditional when the prior mean of $\beta$ is zero, as here. The equations are solved participant by participant: level_cholesky() factors each $2\times2$ block $U_i^\top U_i/\sigma^2+G^{-1}$ and level_solve() eliminates it, which leaves a $2\times2$ system for $\beta$ in schur. Each $b_i$ then follows from $\beta$.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
    # G from the random coefficients of all levels, then the residual variance.
    G <- inverse_wishart_draw(spd_inverse(crossprod(b) + G_scale), m + G_prior$nu)
    G_inverse <- spd_inverse(G); G_root <- row_cholesky(G_inverse)
    deviation <- y - (drop(X %*% beta) + rowSums(U * b[level, , drop = FALSE]))
    R <- inverse_wishart_draw(spd_inverse(crossprod(deviation) + R_scale), n + prior$R$nu)
    R_inverse <- spd_inverse(R); R_root <- row_cholesky(R_inverse)
    if (iteration >= burnin && (iteration - burnin) %% thin == 0L) {
      stored <- stored + 1L
      location_draws[stored, ] <- if (store_random) c(beta, b) else beta
      variance_draws[stored, ] <- c(G, R)
    }
  }
  list(location = location_draws, G = variance_draws[, seq_len(q * q), drop = FALSE],
    residual_variance = variance_draws[, q * q + 1L])
}

The third part draws $G$ from $IW(N+\nu,\sum_ib_ib_i^\top+\nu V)$ and then $\sigma^2$ from the one-dimensional inverse Wishart distribution with $n+\nu$ degrees of freedom and scale $\sum_ir_i^\top r_i+\nu V$, which is the $IG(402,1+\tfrac12\sum_ir_i^\top r_i)$ distribution above. Both variance draws use inverse_wishart_draw().

1
2
3
4
5
6
7
8
9
10
11
inverse_wishart_draw <- function(A, df) {
  m <- nrow(A)
  T <- matrix(0, m, m)
  for (i in seq_len(m)) {
    T[i, i] <- sqrt(rchisq(1, df))
    for (j in seq_len(m - i) + i) T[j, i] <- rnorm(1)
    df <- df - 1
  }
  C <- row_cholesky(A) %*% T
  spd_inverse(C %*% t(C))
}

Its matrix T is lower triangular, with the square roots of chi-square draws with df, df minus one and so on down the diagonal and standard normal draws below it. With $LL^\top=A$, the product $LTT^\top L^\top$ is a Wishart draw with scale matrix $A$ (Bartlett’s construction), and the function returns its inverse. Four random number streams start from the common root seed 101613.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
source("code/lib/boundary_test.R")
source("code/lib/mixed_gibbs.R")
RNGkind("L'Ecuyer-CMRG","Inversion","Rejection")
set.seed(101613)
streams <- replicate_streams(4L,.Random.seed)
growth_design <- cbind("(Intercept)"=1,time=growth_long$time)
lmm_gibbs <- lapply(seq_along(streams),function(id) {
  assign(".Random.seed",streams[[id]],envir=.GlobalEnv)
  fit <- random_coefficient_gibbs(growth_long$y,growth_design,growth_design,growth_long$id,
    growth_prior,group_name="id")
  list(draws=cbind(intercept=fit$location[,"(Intercept)"],slope=fit$location[,"time"],
    G11=fit$G[,1],G21=fit$G[,2],G22=fit$G[,4],residual_variance=fit$residual_variance,
    b11=fit$location[,"(Intercept).id.1"]))
})

The default run has 13,000 iterations per chain. It discards the first 3,000 and retains every tenth subsequent draw, giving 1,000 per chain. Each row of fit$G contains one retained $G$ in column order, so its first, second and fourth entries are $G_{11}$, $G_{21}$ and $G_{22}$. The seven columns contain the population intercept and slope, the three distinct entries of $G$, the residual variance and the first person’s intercept deviation. The function four_matrix() selects column j from each chain’s draws matrix and places those vectors side by side, with iterations in rows and chains in columns. The function report_chains() applies chain_summary() to each such matrix, returning one row per quantity in that order.

1
2
3
4
5
6
four_matrix <- function(chains,j) vapply(chains,
  function(r)r$draws[,j],numeric(nrow(chains[[1]]$draws)))
report_chains <- function(chains) do.call(rbind,lapply(
  seq_len(ncol(chains[[1]]$draws)),function(j)
  chain_summary(four_matrix(chains,j))))
print(report_chains(lmm_gibbs))
1
2
3
4
5
6
7
8
          mean         sd      Rhat ESS_bulk ESS_tail         MCSE
[1,] 2.0737708 0.08536420 0.9998285 4017.250 3645.927 0.0013474055
[2,] 0.4003248 0.04334907 1.0002163 4033.548 3861.366 0.0006823986
[3,] 1.1284932 0.14722161 0.9997722 3845.737 3970.566 0.0023704468
[4,] 0.1272585 0.05439482 0.9996188 3916.716 3908.694 0.0008684385
[5,] 0.2847392 0.03918534 0.9996861 3795.511 3892.754 0.0006372328
[6,] 0.4864607 0.03521195 0.9994693 3987.046 3630.636 0.0005594651
[7,] 0.1485008 0.46620635 1.0004515 3894.437 3933.340 0.0074637713

For example, the first row gives a mean of 2.0738 and a posterior SD of 0.0854 for the population intercept. The last row gives a much smaller mean, 0.1485, with a larger SD, 0.4662. It describes how far one person’s intercept lies from the population intercept.

The same four time points and covariance structure also admit a maximum likelihood fit. Place its parameter estimates and information-based standard errors beside the posterior means, SDs and central 95% posterior credible intervals from the 4,000 pooled draws. Each credible interval uses the lower and upper posterior quantiles that leave equal probability in the two tails. It describes uncertainty about that parameter conditional on these data and priors.

1
2
3
4
5
6
7
8
9
10
11
12
13
growth_ml <- readRDS("data/derived/ch07/growth-fit.rds")
lmm_table <- report_chains(lmm_gibbs)
rownames(lmm_table) <- colnames(lmm_gibbs[[1]]$draws)
lmm_bounds <- t(vapply(seq_len(ncol(lmm_gibbs[[1]]$draws)),function(j)
  quantile(four_matrix(lmm_gibbs,j),c(.025,.975),names=FALSE),numeric(2)))
# The four residual variances share one ML estimate.
ml_names <- c(intercept="mean_intercept",slope="mean_slope",G11="G11",G21="G21",G22="G22",
  residual_variance="residual1",b11=NA)
ml_at <- match(ml_names,names(growth_ml$theta))
print(data.frame(mean=lmm_table[,"mean"],sd=lmm_table[,"sd"],lower=lmm_bounds[,1],
  upper=lmm_bounds[,2],ML=unname(growth_ml$theta[ml_at]),
  SE=growth_ml$information$se[ml_at],
  row.names=rownames(lmm_table))[names(ml_names),])
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
                       mean         sd       lower     upper        ML
intercept         2.0737708 0.08536420  1.90752873 2.2480904 2.0745469
slope             0.4003248 0.04334907  0.31531270 0.4877080 0.4014797
G11               1.1284932 0.14722161  0.86106681 1.4430858 1.1451694
G21               0.1272585 0.05439482  0.01959045 0.2335186 0.1201136
G22               0.2847392 0.03918534  0.21643105 0.3686646 0.2810106
residual_variance 0.4864607 0.03521195  0.42170032 0.5605918 0.4790511
b11               0.1485008 0.46620635 -0.75073232 1.0440161        NA
                          SE
intercept         0.08603793
slope             0.04340627
G11               0.14993734
G21               0.05380968
G22               0.03828625
residual_variance 0.03387403
b11                       NA

For the population intercept and slope, the intervals are $(1.908,2.248)$ and $(0.315,0.488)$, respectively. The posterior means of 2.0738 and 0.4003 differ from the maximum likelihood (ML) estimates of 2.0745 and 0.4015 by less than twice their respective Monte Carlo standard errors, 0.00135 and 0.00068. The variance components give a different comparison. For $G_{11}$ the gap between 1.1285 and 1.1452 is about seven MCSEs. For $\sigma^2$ the gap between 0.4865 and 0.4791 is about thirteen. These ratios measure differences relative to the precision of the simulated means. The posterior SD of 0.1472 for $G_{11}$ is close to the ML standard error of 0.1499. The former measures posterior spread, while the latter estimates the sampling variability of the ML estimator. ML selects the parameters that maximize the observed-data likelihood. A posterior mean averages parameter values with weights determined by both the likelihood and the prior. Their numerical differences alone cannot establish how much the prior contributed.

The first person’s deviations permit a comparison with empirical Bayes prediction. Fix the population parameters at their ML estimates. With $V=ZGZ^\top+\sigma^2I_4$, the empirical Bayes mean is $GZ^\top V^{-1}(y_1-Z\beta)$ and its conditional covariance is $G-GZ^\top V^{-1}ZG$.

1
2
3
4
5
6
G_ml <- matrix(growth_ml$theta[c("G11","G21","G21","G22")],2)
V_ml <- Z%*%G_ml%*%t(Z)+growth_ml$theta[["residual1"]]*diag(4)
beta_ml <- growth_ml$theta[c("mean_intercept","mean_slope")]
eb_mean <- drop(G_ml%*%t(Z)%*%solve(V_ml,Gdata$wide[1,]-drop(Z%*%beta_ml)))
eb_covariance <- G_ml-G_ml%*%t(Z)%*%solve(V_ml,Z%*%G_ml)
print(rbind(empirical_Bayes=eb_mean,conditional_SD=sqrt(diag(eb_covariance))))
1
2
3
                     [,1]       [,2]
empirical_Bayes 0.1602684 -0.8125887
conditional_SD  0.4566416  0.2421297

The predicted intercept deviation is 0.160 and the slope deviation is $-0.813$, with conditional SDs 0.457 and 0.242. The posterior intercept deviation in the last row of the comparison averages over the population parameters, giving mean 0.149 and SD 0.466.

The population-coefficient summaries can also be checked by averaging known conditional normal moments in place of the sampled coefficients. This is Rao-Blackwellization. To obtain those moments, integrate out the person effects at each sampled pair $(G,\sigma^2)$. Given this pair and $\beta$, each $y_i$ then has mean $Z\beta$ and covariance $V$. Combining this likelihood with the fixed-effect prior gives precision $P=0.01I_2+NZ^\top V^{-1}Z$ and mean $m=P^{-1}Z^\top V^{-1}\sum_i y_i$. The following calculation averages these conditional means over the variance draws. It adds the mean of $P^{-1}$ to the covariance of $m$ before taking the square roots of the diagonal entries.

1
2
3
4
5
6
7
8
9
10
11
12
13
print(local({
  draws <- do.call(rbind,lapply(lmm_gibbs,function(r)r$draws))
  total <- colSums(Gdata$wide); N <- nrow(Gdata$wide)
  moments <- lapply(seq_len(nrow(draws)),function(s) {
    G <- matrix(draws[s,c("G11","G21","G21","G22")],2)
    Vinv <- solve(Z%*%G%*%t(Z)+draws[s,"residual_variance"]*diag(4))
    P <- .01*diag(2)+N*t(Z)%*%Vinv%*%Z
    list(mean=drop(solve(P,t(Z)%*%Vinv%*%total)),covariance=solve(P))
  })
  means <- t(vapply(moments,`[[`,numeric(2),"mean"))
  rbind(Rao_Blackwell_mean=colMeans(means),Rao_Blackwell_sd=sqrt(diag(
    Reduce(`+`,lapply(moments,`[[`,"covariance"))/length(moments)+cov(means))))
}))
1
2
3
                         [,1]       [,2]
Rao_Blackwell_mean 2.07439489 0.40147399
Rao_Blackwell_sd   0.08570025 0.04370491

These Rao-Blackwellized means, 2.07439 and 0.40147, and SDs, 0.08570 and 0.04370, closely match the directly sampled fixed-effect summaries. This agreement checks the direct simulation against an average that uses a whole conditional normal distribution at each variance draw. Using only its mean would omit the uncertainty about $\beta$ still present at that draw.

Observed growth trajectories and uncertainty about diet contrasts

The simulated growth data have a known generating model. The ChickWeight experiment provides an observed longitudinal application of Bayesian estimation. The R dataset documentation describes 578 measurements of body weight under four diets, with repeated observations from birth through day 21. The measurements are nested within chicks. Reuse the mean and random-intercept structure of the Chapter 8 application: diet-specific intercepts and linear trends, a common quadratic time term, and one random intercept per chick.

Let $y_{it}$ denote chick $i$’s weight in units of 100 grams, and let $t$ denote age in units of ten days. With diet 1 as the reference, write $D_{ik}=1$ for diet $k$ and zero otherwise, for $k=2,3,4$. The model is

\[y_{it}=\beta_0+\beta_t t+\beta_{tt}t^2+ \sum_{k=2}^4\{\beta_{Dk}D_{ik}+\beta_{tDk}tD_{ik}\}+b_i+\epsilon_{it}, \qquad b_i\sim N(0,\tau^2),\quad \epsilon_{it}\sim N(0,\sigma^2).\]

Chicks are independent given the population parameters. Within a chick, the errors are independent given its random intercept. The nine fixed coefficients determine the population mean trajectory. In particular, $\beta_{Dk}$ is a diet difference at birth, while $\beta_{tDk}$ is a difference in the linear time coefficient. The common quadratic term makes the instantaneous mean rate of growth depend on age. The random intercept $b_i$ shifts one chick’s entire trajectory. The variance $\tau^2$ describes between-chick intercept variation, and $\sigma^2$ describes variation around those trajectories; both use squared 100-gram units.

Retain the observed measurement schedule, including its unequal numbers of observations across chicks. The following design uses explicit treatment contrasts so that its coefficient names have the stated reference-diet interpretation. From the book directory, source("code/examples/ch16-application.R") runs this application. Its setup loads the chapter functions and saves inputs and fitted objects under data/source/ch16 and data/derived/ch16.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
# start_application() loads the functions, sets the random-number methods and creates the folders.
# record_check() and record_review() save checks and review flags; neither changes an estimate.
source("code/lib/application_run.R", local = TRUE)
application <- start_application(16L)
record_check <- application$record_check
record_review <- application$record_review

chick <- as.data.frame(datasets::ChickWeight)
chick$day10 <- chick$Time / 10
chick$weight100 <- chick$weight / 100
chick$Diet <- factor(chick$Diet, levels = as.character(1:4))
chick$Chick <- factor(chick$Chick)
contrasts(chick$Diet) <- contr.treatment(4L)
chick_formula <- weight100 ~ day10 * Diet + I(day10^2)
chick_X <- model.matrix(chick_formula, chick)
chick_group <- as.integer(chick$Chick)
chick_groups <- nlevels(chick$Chick)
stopifnot(!anyNA(chick), qr(chick_X)$rank == ncol(chick_X))
print(c(measurements = nrow(chick), chicks = chick_groups, coefficients = ncol(chick_X)))
print(with(chick, table(Diet, Time)))
saveRDS(list(data = chick, X = chick_X, formula = chick_formula),
        file.path("data/source/ch16", "ch16-chickweight.rds"))
1
2
3
4
5
6
7
8
measurements       chicks coefficients 
         578           50            9 
    Time
Diet  0  2  4  6  8 10 12 14 16 18 20 21
   1 20 20 19 19 19 19 19 18 17 17 17 16
   2 10 10 10 10 10 10 10 10 10 10 10 10
   3 10 10 10 10 10 10 10 10 10 10 10 10
   4 10 10 10 10 10 10 10 10 10 10  9  9

chick_X contains the nine fixed-effect columns in the formula’s order. chick_group maps each measurement to its chick. The diet-by-time table shows how many observations contribute to each mean. Conditioning on this observed schedule does not model why some later measurements are absent.

Use independent priors

\[\beta\sim N_9(0,25I_9),\qquad \tau^2\sim IG(2,0.04),\qquad \sigma^2\sim IG(2,0.04),\]

where $IG(a,b)$ has density proportional to $v^{-a-1}\exp(-b/v)$ for $v>0$. The normal prior is broad on these scaled coefficients. The variance priors each have mean 0.04, whose square root corresponds to 20 grams on the original response scale. This is not the prior mean of a standard deviation. For a focused sensitivity analysis, change both inverse-gamma rates to 0.16 while leaving their shapes, the fixed-effect prior and the likelihood unchanged. This increases each prior mean variance fourfold; it is a change in prior scale, rather than an unspecified “weaker prior.”

1
2
3
4
5
6
7
8
9
10
11
12
13
chick_prior <- list(B = list(mu = rep(0, ncol(chick_X)), V = diag(25, ncol(chick_X))),
  G = list(G1 = list(V = .02, nu = 4)), R = list(V = .02, nu = 4))
chick_alternative_prior <- chick_prior
chick_alternative_prior$G$G1$V <- .08
chick_alternative_prior$R$V <- .08
chick_priors <- list(main = chick_prior, larger_variances = chick_alternative_prior)
chick_prior_summary <- do.call(rbind, lapply(names(chick_priors), function(name) {
  prior <- chick_priors[[name]]
  data.frame(prior = name, coefficient_SD = sqrt(prior$B$V[1, 1]),
    variance_shape = prior$R$nu / 2, variance_rate = prior$R$nu * prior$R$V / 2,
    prior_mean_variance = prior$R$nu * prior$R$V / (prior$R$nu - 2))
}))
print(chick_prior_summary, row.names = FALSE)
1
2
3
            prior coefficient_SD variance_shape variance_rate prior_mean_variance
             main              5              2          0.04                0.04
 larger_variances              5              2          0.16                0.16

For a scalar variance, the parameterization of random_coefficient_gibbs(), the same as that of MCMCglmm, has inverse-gamma shape nu/2 and rate nu*V/2. Thus nu=4 and V=.02 specify the first pair of variance priors. Setting V=.08 gives the second pair. The list B specifies the normal prior for the fixed coefficients. These prior settings are modeling choices, not values estimated from the fitted variances.

The conditional updates show where the observed schedule enters. Let $n_i$ be chick $i$’s number of measurements, let $N=\sum_i n_i$, let $m$ be the number of chicks, and let $x_{it}^\top$ be a row of the fixed design. For a random intercept, the conditional precision and mean are

\[Q_i=\tau^{-2}+n_i\sigma^{-2},\qquad m_i=Q_i^{-1}\sigma^{-2}\sum_t(y_{it}-x_{it}^\top\beta).\]

For the fixed coefficients, the conditional precision is $Q_\beta=I_9/25+X^\top X/\sigma^2$, and the mean is $Q_\beta^{-1}X^\top(y-Zb)/\sigma^2$, where $Z$ is the chick-incidence matrix. Under the main prior, the variance conditionals are

\[\tau^2\mid b\sim IG\left(2+\frac m2,\;0.04+\frac12\sum_i b_i^2\right),\qquad \sigma^2\mid\beta,b,y\sim IG\left(2+\frac N2,\;0.04+\frac12\sum_{i,t}(y_{it}-x_{it}^\top\beta-b_i)^2\right).\]

Under the alternative prior, replace 0.04 by 0.16 in both rates. As in the earlier growth example, random_coefficient_gibbs() samples fixed and random coefficients jointly, which targets the same joint normal conditional distribution. Here the random-coefficient design is a single column of ones. Run four chains per prior with dispersed starting variances. Each chain discards 3,000 iterations and retains every fifth iteration from the next 40,000, giving 8,000 retained draws. Thinning controls storage here; it does not establish independence of the retained draws.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
chick_chains <- list()
for (chick_prior_name in names(chick_priors)) {
  chick_current_chains <- vector("list", 4L)
  for (chick_chain_id in 1:4) {
    message("Sampling ChickWeight: ", chick_prior_name, ", chain ", chick_chain_id)
    chick_seed <- 160400L + 100L * match(chick_prior_name, names(chick_priors)) + chick_chain_id
    set.seed(chick_seed)
    # Random intercepts by chick (code/lib/mixed_gibbs.R): 3,000 burn-in, then every fifth of 40,000 iterations.
    chick_chain_fit <- random_coefficient_gibbs(chick$weight100, chick_X,
      matrix(1, nrow(chick), 1L, dimnames = list(NULL, "(Intercept)")), chick$Chick,
      chick_priors[[chick_prior_name]], start_G = .02 * 4^(chick_chain_id - 1L),
      start_R = .01 * 4^(chick_chain_id - 1L), iterations = 43000L, burnin = 3000L, thin = 5L,
      store_random = FALSE, group_name = "Chick")
    stopifnot(identical(colnames(chick_chain_fit$location), colnames(chick_X)))
    chick_chain_draws <- cbind(chick_chain_fit$location, between_chick_variance = chick_chain_fit$G[, 1],
      residual_variance = chick_chain_fit$residual_variance)
    chick_current_chains[[chick_chain_id]] <- list(seed = chick_seed, draws = chick_chain_draws)
    saveRDS(list(seed = chick_seed, fit = chick_chain_fit, draws = chick_chain_draws), file.path("data/derived/ch16",
      paste0("ch16-", chick_prior_name, "-chain", chick_chain_id, ".rds")))
  }
  chick_chains[[chick_prior_name]] <- chick_current_chains
}

location supplies the fixed-effect draws, and G and residual_variance supply the two variance components. The check confirms that the fixed-effect columns follow the design’s column names. The chains use distinct seeds under each prior, and their full fits are saved separately. Summaries must reflect dependence within these chains.

An interpretable contrast is the difference between the population mean weights under diets 4 and 1 at day 21. In the scaled model it is $\beta_{D4}+2.1\beta_{tD4}$; multiplying by 100 expresses it in grams. Calculate this contrast in every posterior draw, then summarize its joint uncertainty rather than adding the two coefficients’ standard deviations.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
chick_new <- data.frame(day10 = rep(2.1, 4L), Diet = factor(1:4, levels = 1:4))
contrasts(chick_new$Diet) <- contrasts(chick$Diet)
chick_new_X <- model.matrix(delete.response(terms(chick_formula)), chick_new)
chick_contrast <- chick_new_X[4, ] - chick_new_X[1, ]
chick_summaries <- do.call(rbind, lapply(names(chick_chains), function(prior_name) {
  chains <- lapply(chick_chains[[prior_name]], function(chain) {
    draws <- chain$draws
    cbind(draws, diet4_minus_diet1_day21_grams =
      100 * drop(draws[, colnames(chick_X), drop = FALSE] %*% chick_contrast))
  })
  do.call(rbind, lapply(seq_len(ncol(chains[[1]])), function(j) {
    values <- vapply(chains, function(draws) draws[, j], numeric(nrow(chains[[1]])))
    summary <- chain_summary(values)
    interval <- quantile(values, c(.025, .975), names = FALSE)
    data.frame(prior = prior_name, parameter = colnames(chains[[1]])[j],
      mean = summary["mean"], sd = summary["sd"], lower = interval[1], upper = interval[2],
      Rhat = summary["Rhat"], ESS_bulk = summary["ESS_bulk"], ESS_tail = summary["ESS_tail"],
      MCSE = summary["MCSE"], row.names = NULL)
  }))
}))
print(chick_summaries, row.names = FALSE)
saveRDS(list(priors = chick_priors, chains = chick_chains, summaries = chick_summaries),
        file.path("data/derived/ch16", "ch16-chickweight.rds"))
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
            prior                     parameter          mean           sd       lower       upper      Rhat
             main                   (Intercept)  0.4101259119  0.062891847  0.28640408  0.53309610 1.0000422
             main                         day10  0.3634247017  0.060970938  0.24375434  0.48276188 0.9999390
             main                         Diet2 -0.0231117916  0.103847801 -0.22673797  0.18048013 1.0000859
             main                         Diet3 -0.1266555694  0.103964089 -0.33212309  0.07573130 0.9999453
             main                         Diet4 -0.0008830581  0.103574927 -0.20357803  0.20496810 0.9999081
             main                    I(day10^2)  0.1455944340  0.026198953  0.09393161  0.19699816 0.9999670
             main                   day10:Diet2  0.1849515643  0.041676410  0.10291981  0.26740643 1.0003479
             main                   day10:Diet3  0.4660819982  0.041840982  0.38408143  0.54766378 1.0000744
             main                   day10:Diet4  0.2934074183  0.042026440  0.21056087  0.37571794 0.9999883
             main        between_chick_variance  0.0534126406  0.012183222  0.03430052  0.08180459 1.0000190
             main             residual_variance  0.0608516207  0.003785773  0.05388893  0.06873522 1.0000510
             main diet4_minus_diet1_day21_grams 61.5272520396 10.362327822 41.29099570 82.13125232 1.0000341
 larger_variances                   (Intercept)  0.4108972157  0.065119215  0.28342083  0.53919723 0.9999623
 larger_variances                         day10  0.3629024034  0.060900344  0.24337122  0.48233162 1.0000202
 larger_variances                         Diet2 -0.0233063805  0.109021012 -0.23530630  0.19193291 0.9999884
 larger_variances                         Diet3 -0.1272430759  0.108371922 -0.33966624  0.08736093 1.0000832
 larger_variances                         Diet4 -0.0002239070  0.108401856 -0.21457515  0.21236116 1.0000533
 larger_variances                    I(day10^2)  0.1456899486  0.026149438  0.09467503  0.19683254 0.9999350
 larger_variances                   day10:Diet2  0.1850248776  0.041626296  0.10322695  0.26691660 1.0001549
 larger_variances                   day10:Diet3  0.4663604912  0.042130762  0.38355576  0.54900625 0.9999856
 larger_variances                   day10:Diet4  0.2933991872  0.042414258  0.20974513  0.37634515 1.0001598
 larger_variances        between_chick_variance  0.0593328580  0.013203688  0.03834787  0.09019542 1.0000813
 larger_variances             residual_variance  0.0612636671  0.003779875  0.05428821  0.06913008 1.0000303
 larger_variances diet4_minus_diet1_day21_grams 61.5914386141 10.827976679 40.24107789 82.78012590 1.0001200
 ESS_bulk ESS_tail         MCSE
 31377.05 30671.52 3.550259e-04
 30873.03 30245.96 3.467191e-04
 31521.44 32014.43 5.849722e-04
 32235.82 31504.82 5.791558e-04
 31567.67 31750.44 5.829542e-04
 31452.27 31681.10 1.477254e-04
 30263.55 31318.55 2.395421e-04
 31881.56 31312.11 2.343764e-04
 31751.98 31917.26 2.358453e-04
 32064.71 31513.87 6.799385e-05
 31245.01 29754.66 2.144943e-05
 31839.12 30452.63 5.805872e-02
 32135.37 32063.90 3.632792e-04
 32969.91 30304.36 3.353948e-04
 32162.02 31309.68 6.078974e-04
 32610.54 31575.57 6.001841e-04
 31182.22 32233.07 6.138418e-04
 32493.61 31332.92 1.450688e-04
 32620.41 32159.29 2.304799e-04
 31850.10 30305.49 2.360797e-04
 31146.54 31007.23 2.403667e-04
 31290.82 31355.33 7.439575e-05
 32565.56 31527.09 2.096856e-05
 30627.73 31223.54 6.188208e-02

The table contains posterior means, standard deviations, central 95% credible intervals, rank-normalized split $\widehat R$, bulk and tail effective sample sizes, and Monte Carlo standard errors. The final contrast is in grams; the coefficient and variance rows retain the scaled model’s units. The credible interval describes uncertainty about the population mean contrast given the data, model and prior. A predictive interval for the weight difference between two individual chicks would also include their random effects and measurement variation.

Under the main prior, the day-21 population mean contrast between diets 4 and 1 is 61.53 grams, with a central 95% credible interval of 41.29 to 82.13 grams. Its posterior SD is 10.36 grams and its mean MCSE is 0.058 gram. Across the reported quantities, the largest rank-normalized split $\widehat R$ is about 1.00035 under the main prior and 1.00016 under the alternative prior; the minimum bulk or tail effective sample sizes are approximately 29,755 and 30,304. These diagnostics support the precision of the sampled summaries, while model adequacy requires predictive checks.

Examine agreement across chains and effective sample sizes before comparing priors. The observed data do not provide known parameter values against which to declare one posterior estimate correct.

16.4 Probit, ordinal, and Pólya-Gamma data augmentation

At the lowest covariate value in LOGIT3, two of ten trials were successes. A probit model treats each success as evidence that a continuous response crossed a threshold. For trial $i$, write $u_i=x_i^\top\beta+\epsilon_i$, where $x_i^\top$ is its design row and the errors are independent standard normals. The observed response is $y_i=1$ if $u_i>0$ and $y_i=0$ otherwise. The threshold fixes the origin of the latent response. Its residual variance is fixed at one because multiplying both $u_i$ and its coefficients by any positive constant leaves every observed sign unchanged. Let $\eta_i=x_i^\top\beta$, and let $\phi$ and $\Phi$ denote the standard normal density and distribution function. Integrating the density of $u_i$ over the values $u_i>0$ compatible with a success gives

\[\Pr(y_i=1\mid x_i,\beta)=\int_0^\infty\phi(u-\eta_i)\,du =1-\Phi(-\eta_i)=\Phi(\eta_i).\]

A failure has probability $\Phi(-\eta_i)$. In this model $\eta_i=\beta_0+\beta_1x_i$: the intercept is the mean latent response at $x_i=0$, and the slope is its change per unit of $x_i$, measured in latent-response residual standard deviations. The success probability at zero is $\Phi(\beta_0)$; a covariate increase changes probability through the normal distribution function, so the probability change also depends on the starting covariate value. Each of the two successes therefore contributes $\Phi(\beta_0-\beta_1)$ to the likelihood at $x=-1$, and each of the eight failures contributes its complement. The count fixes how many latent responses fall on either side of zero. Their values within those ranges, $u_i>0$ for a success and $u_i\leq0$ for a failure, are unknown. In data augmentation, each trial supplies a draw from the part of its latent response distribution compatible with its observed outcome.

For a success, divide $\phi(u_i-\eta_i)$ on $u_i>0$ by $\Phi(\eta_i)$ to obtain the full conditional density. For a failure, use the density on $u_i\leq0$ and divide by $\Phi(-\eta_i)$. For instance, to draw a latent response for a success, draw a uniform probability between $\Phi(-\eta_i)$ and one, take its standard normal quantile and add $\eta_i$. In exact arithmetic its value exceeds zero even if the current linear predictor is negative. In extreme tails, rounded probabilities can equal zero or one, so an implementation needs a truncated-normal calculation that remains accurate there. At fixed coefficients the latent trial responses are conditionally independent given their observed outcomes.

Once the latent vector $u$ is available, it gives an ordinary normal regression with unit error variance. The prior $\beta\sim N_2(0,4I_2)$ contributes precision $I_2/4$. Completing the square in $(u-X\beta)^\top(u-X\beta)+\beta^\top\beta/4$ gives a normal update with precision $P=X^\top X+I_2/4$ and mean $P^{-1}X^\top u$.

The function probit_gibbs() in code/lib/probit_gibbs.R alternates the two updates above.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
probit_gibbs <- function(X, y, seed, prior_mean = 0, prior_precision = 0, burnin = 1000L, retained = 10000L,
                         start = probit_irls(X, y)) {
  k <- ncol(X)
  b0 <- matrix(prior_mean, k, 1L)
  B0 <- if (is.matrix(prior_precision)) prior_precision else prior_precision * diag(k)
  rng <- mt_generator(seed)
  XpX <- crossprod(X)
  beta <- matrix(start, k, 1L)
  latent <- numeric(nrow(X))
  draws <- matrix(NA_real_, retained, k, dimnames = list(NULL, colnames(X)))
  for (iteration in seq_len(burnin + retained)) {
    mean <- ordered_product(X, beta)
    for (i in seq_along(y))
      latent[i] <- if (y[i] == 1) mt_normal_above(rng, mean[i], 1, 0) else mt_normal_below(rng, mean[i], 1, 0)
    variance <- positive_definite_inverse(B0 + XpX)
    X_latent <- matrix(vapply(seq_len(k), function(i) ordered_sum(X[, i] * latent), 0), k, 1L)
    center <- ordered_product(variance, accumulate_product(B0, b0, X_latent))
    beta <- center + ordered_product(cholesky_factor(variance), mt_normal(rng, k))
    if (iteration > burnin) draws[iteration - burnin, ] <- beta
  }
  list(draws = draws, start = start)
}

The arguments X and y are the design matrix and the vector of zeros and ones. Each coefficient has prior mean prior_mean and prior precision prior_precision; a matrix argument supplies the whole precision matrix B0. In each iteration mean contains the linear predictors $\eta_i$. For a success, mt_normal_above(rng, mean[i], 1, 0) draws $u_i$ from the unit-variance normal distribution with mean $\eta_i$ restricted to values above zero; for a failure, mt_normal_below() restricts it to values below zero. Then variance is $P^{-1}=(B_0+X^\top X)^{-1}$, X_latent is $X^\top u$ and center is $P^{-1}(B_0b_0+X^\top u)$, which equals $P^{-1}X^\top u$ when the prior mean $b_0$ is zero. Adding the lower Cholesky factor of $P^{-1}$ times a vector of standard normal draws to center gives a draw from $N(P^{-1}X^\top u,P^{-1})$. Draws after the first burnin iterations are stored.

The truncated draws choose a method by the distance from the mean to the bound in standard deviations. When the mean lies above the bound, or less than half a standard deviation below it, mt_normal_above() repeats ordinary normal draws until one falls above the bound. Between half and five standard deviations below, it uses the inverse distribution function. Farther out the probability above the bound is less than $2.9\times10^{-7}$, and the function instead takes ten slice-sampling steps that start just above the bound. The function mt_normal_below() is its mirror image. The remaining helpers repeat the arithmetic of MCMCprobit in a fixed order: ordered_product(A, x) returns $Ax$ by adding the columns of A weighted by the elements of x in increasing order, ordered_sum() adds the elements of a vector in order, accumulate_product(A, b, c) returns $Ab+c$ in the same way, cholesky_factor() returns the lower Cholesky factor and positive_definite_inverse() inverts a positive definite matrix by solving two triangular systems for each column of the identity. Apart from rounding they give the values of %*%, sum(), chol() and solve(). With the order fixed, the draws do not depend on the matrix library that R uses, and Section 16.10 compares them with those of MCMCprobit for the same seed. The random numbers come from mt_generator() and mt_normal(), introduced with factor_gibbs() in Section 16.3.

Expand the three counts in data/source/LOGIT3.csv into 30 trials. Each design row has an intercept and the covariate $-1$, 0 or 1. Run the fit from the book directory. The function’s default prior mean is zero, and prior_precision=.25 sets the prior precision of each coefficient to one quarter. The default start is the probit maximum likelihood estimate, computed by probit_irls() with the iteratively reweighted least squares that glm() uses and that irls() follows in Section 2.6. Each seed from 1016041 through 1016044 gives 10,000 retained draws after 1,000 burn-in iterations. The seed starts the Mersenne twister of code/lib/factor_gibbs.R, as in MCMCprobit of MCMCpack, from which the sampler is translated (code/NOTICE.md); Section 16.10 compares their draws for the same seeds.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
.libPaths(c(".R-library", .libPaths()))
for (file in c("posterior_checks","factor_gibbs","probit_gibbs")) source(paste0("code/lib/",file,".R"))
logit3 <- read.csv("data/source/LOGIT3.csv")
trials <- logit3$trials
success <- logit3$successes
expanded <- rep(logit3$x, trials)
observed <- unlist(Map(function(k) c(rep(1,k),rep(0,10-k)),success))
X <- cbind(1,expanded)
probit_glm <- lapply(1016040L + 1:4, function(seed) {
  list(draws=probit_gibbs(X,observed,seed,prior_precision=.25)$draws)
})
four_matrix <- function(chains,j) vapply(chains,
  function(r)r$draws[,j],numeric(nrow(chains[[1]]$draws)))
report_chains <- function(chains) do.call(rbind,lapply(
  seq_len(ncol(chains[[1]]$draws)),function(j)
  chain_summary(four_matrix(chains,j))))

The intercept offers an exact check. The two successes at $x=-1$ match the two failures at $x=1$, and the eight failures on the left match the eight successes on the right. Changing the intercept’s sign with the slope fixed exchanges the corresponding probabilities. The middle group has five outcomes of each kind and the intercept prior is symmetric, so its posterior mean is zero. For the slope, evaluate the observed-data likelihood on a grid with spacing 0.005 in both coefficients. The grid spans intercepts from $-1.6$ to 1.6 and slopes from $-0.8$ to 2.6. Multiply the likelihood terms of the three covariate groups by the normal prior densities. After normalization the grid weights yield both first and second moments.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
probit_grid <- local({
  b0 <- seq(-1.6,1.6,by=.005); b1 <- seq(-.8,2.6,by=.005)
  log_post <- outer(b0,b1,function(u,v) {
    value <- dnorm(u,sd=2,log=TRUE)+dnorm(v,sd=2,log=TRUE)
    for(i in seq_along(success)) {
      eta <- u+v*(i-2)
      value <- value+success[i]*pnorm(eta,log.p=TRUE)+
        (trials[i]-success[i])*pnorm(-eta,log.p=TRUE)
    }
    value
  })
  w <- exp(log_post-max(log_post)); w <- w/sum(w)
  B0 <- matrix(b0,length(b0),length(b1))
  B1 <- matrix(b1,length(b0),length(b1),byrow=TRUE)
  m <- c(sum(w*B0),sum(w*B1))
  cbind(grid_mean=m,grid_sd=sqrt(c(sum(w*B0^2),sum(w*B1^2))-m^2))
})
print(cbind(probit_grid,chain_mean=report_chains(probit_glm)[,"mean"],
  chain_sd=report_chains(probit_glm)[,"sd"],
  chain_MCSE=report_chains(probit_glm)[,"MCSE"]))
1
2
3
        grid_mean   grid_sd   chain_mean  chain_sd  chain_MCSE
[1,] 2.474443e-18 0.2486610 0.0004886429 0.2496075 0.002108267
[2,] 8.536853e-01 0.3189672 0.8539019178 0.3195271 0.002834946

In intercept and slope order the simulated means are 0.00049 and 0.85390, with posterior SDs 0.24961 and 0.31953. The grid gives zero to numerical precision and 0.85369, with SDs 0.24866 and 0.31897. The Monte Carlo standard errors (MCSEs) of the two chain means are 0.00211 and 0.00283. The slope discrepancy is about 0.08 of its MCSE. Thus the augmented response calculation recovers the slope mean to the precision available in these chains. The finite grid is a numerical reference. Its range and spacing must also be varied before its approximation error can be treated as negligible relative to the reported MCSE.

Normal-ogive item responses

For an item response, the linear predictor can itself contain an unknown trait. In the two-parameter normal-ogive model, examinee $i$ has $z_i\sim N(0,1)$ and item $j$ has a latent response $u_{ij}=-\alpha_j+\beta_jz_i+\epsilon_{ij}$ with independent standard normal errors. An observed one then has probability $\Phi(-\alpha_j+\beta_jz_i)$. The standard normal trait sets the origin and unit for comparing examinees. Positive slopes orient larger trait values toward a greater probability of success on every item. The intercept in this equation is $d_j=-\alpha_j$, the mean latent response for an examinee at $z_i=0$, whose success probability is $\Phi(d_j)$. The discrimination $\beta_j$ changes the mean latent response by $\beta_j$ residual standard deviations per population SD of the trait. Its effect on success probability depends on the trait value. The trait value at which success has probability one half is $\alpha_j/\beta_j$, since the linear predictor is zero there.

Give the item parameters independent $N(0,4)$ priors and restrict each slope to $\beta_j>0$, so that each slope has the $N(0,4)$ prior truncated to positive values. Zero and four are the mean and variance before truncation. Generate a probit companion to IRT8 using the same eight generating slopes and the same eight difficulty parameters, evenly spaced from $-1.5$ to $1.5$. Equal numerical slopes do not make probit and logistic response curves identical. Seed 1604 generates 800 traits and then the uniforms for all 6,400 responses.

1
2
3
4
RNGkind("Mersenne-Twister","Inversion","Rejection")
set.seed(1604); trait <- rnorm(800)
a <- c(.7,.9,1,1.1,1.2,.8,1.3,1); d <- -a*seq(-1.5,1.5,length.out=8)
probit_Y <- matrix(as.integer(runif(6400)<pnorm(sweep(outer(trait,a),2,d,"+"))),800)

Each row of probit_Y belongs to one examinee. The vector d supplies the item intercepts in the linear predictor of the normal-ogive model. The generating traits specify the sample used here. Only the observed item responses enter the fit, so each examinee’s trait must also be drawn.

Given the item parameters and traits, draw each $u_{ij}$ on the side of zero selected by the response. Completing the square for one trait gives precision $P_z=1+\sum_j\beta_j^2$ and mean $P_z^{-1}\sum_j\beta_j(u_{ij}+\alpha_j)$. For item $j$, regress its latent responses $u_j$ on the design $D$ with rows $(1,z_i)$. Before imposing the sign constraint, the normal distribution for $(d_j,\beta_j)$ has precision $P_D=D^\top D+I_2/4$ and mean $P_D^{-1}D^\top u_j$. The full conditional is this bivariate normal conditioned on $\beta_j>0$. Truncation raises the slope mean and can shift the intercept mean when the two coefficients are correlated. The function run_items() below calls the normal-ogive sampler when ordinal=FALSE. Its other branch is used for the ordered-response example later in this section.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
for (file in c("result","stability","logit","glm","line_search","quasi_newton","factor_gibbs",
  "probit_gibbs")) source(paste0("code/lib/",file,".R"))
run_items <- function(ordinal,Y,seed,mcmc) {
  J <- ncol(Y)
  if(!ordinal) {
    fit <- ordinal_factor_gibbs(Y+1L,seed,prior_precision=c(.25,.25),retained=mcmc)
    draws <- cbind(fit$slope,fit$intercept)
    colnames(draws) <- c(paste0("a",1:J),paste0("d",1:J))
    return(list(draws=draws))
  }
  # Ordinal responses use unit residual variance and a positive slope.
  fit <- ordinal_factor_gibbs(Y+1L,seed,prior_precision=c(0,.25),retained=mcmc)
  cuts <- do.call(cbind,lapply(1:J,function(j)fit$cuts[,2:4,j]-fit$intercept[,j]))
  draws <- cbind(fit$slope,cuts)
  colnames(draws) <- c(paste0("a",1:J),paste0("cut",rep(1:J,each=3),".",1:3))
  list(draws=draws,acceptance=fit$acceptance)
}

The function ordinal_factor_gibbs() in code/lib/probit_gibbs.R numbers the categories from one, hence Y+1L, and treats an item with two categories as a normal-ogive item. It restricts every slope to positive values. The argument prior_precision gives the prior precisions of the intercept and the slope; for the normal-ogive items both are one quarter. The dichotomous branch of run_items() returns the slopes and the intercepts $d_j=-\alpha_j$. The first eight columns contain the slopes and the next eight contain the intercepts. Traits are updated but are omitted from the returned matrix. The sampler is translated from MCMCirtKd and MCMCordfactanal of MCMCpack, with their starting values and random number generator (code/NOTICE.md); Section 16.10 compares the draws for the same seeds.

The function appears in five parts, which together form it. The first three, below, prepare the chain and draw the latent responses, the traits and the item coefficients. The last two, which move the cutpoints and return the draws, follow with the ordered categories later in this section.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
ordinal_factor_gibbs <- function(Y, seed, prior_mean = c(0, 0), prior_precision = c(0, 0), positive_slope = TRUE,
                                 burnin = 1000L, retained = 20000L, start = ordinal_factor_start(Y),
                                 tune = .05 / categories, state = NULL) {
  N <- nrow(Y); K <- ncol(Y)
  stopifnot(!anyNA(Y), all(Y >= 1L))
  categories <- apply(Y, 2, max)
  if (is.null(state)) {
    rng <- mt_generator(seed)
    intercept <- start$intercept
    slope <- rep(if (positive_slope) 1 else 0, K)
    # cut[c + 1, j] is the upper limit of category c of item j; -300 and 300 stand for the unbounded ends.
    cut <- start$cuts
    factor <- numeric(N)
    accepted <- numeric(K)
    sweeps <- 0
  } else {
    rng <- list2env(state$rng)
    intercept <- state$intercept; slope <- state$slope; cut <- state$cut; factor <- state$factor
    accepted <- state$accepted; sweeps <- state$sweeps
  }
  prior_precision_matrix <- diag(prior_precision, 2L)
  draws <- matrix(NA_real_, retained, 2L * K)
  kept_cuts <- array(NA_real_, c(retained, nrow(cut), K))
  lower_index <- cbind(c(Y), rep(seq_len(K), each = N))
  upper_index <- cbind(c(Y) + 1L, rep(seq_len(K), each = N))
  for (iteration in seq_len(burnin + retained)) {

In the first part, categories gives each item’s number of categories. Column $j$ of cut lists the limits of item $j$’s categories: row $c+1$ is the upper limit of category $c$, the first finite limit is zero, and $-300$ and 300 stand for the unbounded ends. A two-category item therefore has the single finite limit zero. The starting values come from ordinal_factor_start(), which uses the probit intercept of a two-category item and, for an item with more categories, cumulative-logit thresholds multiplied by 0.588, as the translated program does. With positive slopes required, the slopes start at one; the traits start at zero. Given the state returned by an earlier run, the function continues that run instead. The matrices lower_index and upper_index select, for each response, the limits of its observed category.

1
2
3
4
5
6
7
8
9
    # Latent responses, person by person and item by item within a person.
    mean <- sweep(outer(factor, slope), 2, intercept, "+")
    latent <- matrix(mt_truncated_normal_sweep(rng, c(t(mean)), c(t(matrix(cut[lower_index], N))),
      c(t(matrix(cut[upper_index], N)))), N, K, byrow = TRUE)
    # Factors given the latent responses and the item parameters.
    factor_variance <- positive_definite_inverse(matrix(1 + ordered_sum(slope * slope)))
    factor_sd <- cholesky_factor(factor_variance)
    center <- drop(factor_variance) * ordered_product(sweep(latent, 2, intercept), slope)
    factor <- drop(factor_sd) * mt_normal(rng, N) + center

In the second part, mean contains $d_j+\beta_jz_i$ for every person and item, and mt_truncated_normal_sweep() draws each $u_{ij}$ from the unit-variance normal distribution with that mean, restricted to the interval of the observed category. It works person by person and item by item, as the translated program does, using repeated normal draws when the interval contains enough of the distribution and the inverse distribution function otherwise. The trait update uses $P_z$ and the mean given above, written with the intercept $d_j=-\alpha_j$ as $P_z^{-1}\sum_j\beta_j(u_{ij}-d_j)$. The helpers ordered_sum(), ordered_product(), cholesky_factor() and positive_definite_inverse() are those of probit_gibbs().

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
    # Intercept and slope of each item.
    phi <- cbind(1, factor)
    factor_sum <- ordered_sum(factor)
    phi_phi <- matrix(c(N, factor_sum, factor_sum, ordered_sum(factor * factor)), 2L)
    variance <- positive_definite_inverse(prior_precision_matrix + phi_phi)
    prior_part <- ordered_product(prior_precision_matrix, prior_mean)
    lower <- cholesky_factor(variance)
    for (j in seq_len(K)) {
      center <- ordered_product(variance, prior_part + c(ordered_sum(latent[, j]), ordered_sum(latent[, j] * factor)))
      repeat {
        draw <- accumulate_product(lower, mt_normal(rng, 2L), center)
        if (!positive_slope || min(0, draw[2L]) >= 0) break
      }
      intercept[j] <- draw[1L]; slope[j] <- draw[2L]
    }

In the third part, phi is the design $D$ with rows $(1,z_i)$ and phi_phi is $D^\top D$, so variance is $P_D^{-1}$ when the prior precision is $I_2/4$. For item $j$, center is $P_D^{-1}D^\top u_j$ plus the prior-mean term, which is zero here, and draw adds the lower Cholesky factor of $P_D^{-1}$ times two standard normal draws. A draw with a negative slope is discarded and replaced. Repeating the bivariate normal draw until the slope is not negative gives a draw from that distribution conditioned on $\beta_j\geq0$, the full conditional stated above.

At seeds 1016141 through 1016144, retain the default 10,000 iterations per chain after 1,000 burn-in draws. To assess an item parameter, form a matrix with iterations in rows and chains in columns. Apply the same calculation to all eight slopes and eight intercepts.

1
2
3
probit_irt <- lapply(1016140L + 1:4, function(seed)
  run_items(FALSE,probit_Y,seed,10000L))
print(report_chains(probit_irt))
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
            mean         sd     Rhat  ESS_bulk  ESS_tail        MCSE
 [1,]  0.6527686 0.08305778 1.000645 3090.8972 5915.1175 0.001496563
 [2,]  0.8636739 0.09593534 1.003070 2213.8422 4470.0049 0.002043580
 [3,]  0.8684598 0.09255230 1.001451 2659.0974 4825.3176 0.001803995
 [4,]  1.0213858 0.09999351 1.001985 2218.6113 4416.7005 0.002136607
 [5,]  1.1440554 0.11345074 1.001895 1711.9905 3037.1637 0.002796432
 [6,]  0.9225505 0.09496466 1.001406 2526.5775 4965.2771 0.001898392
 [7,]  1.6994216 0.23452516 1.010643  393.5165  520.2317 0.012203805
 [8,]  1.2761738 0.15963372 1.013678  631.7556 1149.2035 0.006425912
 [9,]  1.0743446 0.07045388 1.000795 3518.2453 7143.6414 0.001190984
[10,]  0.9245075 0.07413195 1.001222 2636.8915 5286.3884 0.001447562
[11,]  0.6690707 0.06729369 1.000860 3267.7522 7935.2882 0.001176079
[12,]  0.3180849 0.06499833 1.000136 3391.9805 8224.1442 0.001116028
[13,] -0.2239586 0.06864726 1.000710 2887.4870 7314.7556 0.001278531
[14,] -0.6055040 0.06785091 1.001271 3128.6633 6222.6023 0.001216087
[15,] -1.5405514 0.17680192 1.010336  449.9973  634.8820 0.008533804
[16,] -1.6946717 0.14561991 1.012318  673.4985 1246.6237 0.005682975

Rows 7 and 15 belong to item seven, rows 8 and 16 to item eight. The slope of item seven has $\widehat R=1.01064$ and bulk effective sample size (ESS) 394, and its intercept has $\widehat R=1.01034$ and bulk ESS 450. For item eight the two values of $\widehat R$ are 1.01368 and 1.01232. The other twelve $\widehat R$ values are below 1.004. The diagnostic rule used here requires $\widehat R<1.01$ and both bulk and tail ESS above 400 for every parameter. The following fit doubles the retained length to 20,000 at the same seeds and burn-in. Each row of the resulting table describes one parameter. The maximum of the $\widehat R$ column and the minimum of each ESS column identify the least favorable value for each criterion.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
chain_table <- function(draws) {
  rows <- lapply(seq_len(ncol(draws[[1]])),function(j) {
    s <- chain_summary(do.call(cbind,lapply(draws,function(d)d[,j])))
    c(mean=s[["mean"]],Rhat=s[["Rhat"]],bulk=s[["ESS_bulk"]],tail=s[["ESS_tail"]],MCSE=s[["MCSE"]])
  })
  d <- as.data.frame(do.call(rbind,rows))
  d$parameter <- colnames(draws[[1]])
  d
}
item_diagnostics <- function(chains) chain_table(lapply(chains,function(r) r$draws))
meets_rule <- function(d) all(d$Rhat < 1.01 & d$bulk > 400 & d$tail > 400)
extrema <- function(d) c(largest_Rhat=max(d$Rhat),smallest_bulk=min(d$bulk),
  smallest_tail=min(d$tail))

dich_long <- lapply(1016140L + 1:4, function(seed)
  run_items(FALSE,probit_Y,seed,20000L))
dich_stats <- item_diagnostics(dich_long)
extrema(dich_stats)
meets_rule(dich_stats)

The largest $\widehat R$ is now 1.00927 and the smallest bulk and tail ESS are 668 and 823. All sixteen parameters meet the rule. Reusing the seeds reproduces the shorter chains at the beginning of the longer ones. Pooling both lengths would count the first draws twice. Meeting this screening rule is evidence of agreement for the sixteen reported item parameters, not proof of posterior exploration or an assessment of the omitted person traits.

Ordered categories and cutpoints

An ordered item locates its latent response in one of several intervals. For four categories labeled 0 through 3, let $\tau_1<\tau_2<\tau_3$ be the finite boundaries, with $\tau_0=-\infty$ and $\tau_4=\infty$. Record category $k$ when $\tau_k<u_{ij}\leq\tau_{k+1}$. For a unit-variance normal response with mean $\eta_{ij}$, this gives probability $\Phi(\tau_{k+1}-\eta_{ij})-\Phi(\tau_k-\eta_{ij})$. For example, with boundaries $(-1,0,1)$ and mean zero, category 1 gives the information that the latent response lies between $-1$ and zero. It has probability $\Phi(0)-\Phi(-1)$. To generate four such items, set their intercepts to zero and their slopes to 0.8, 1, 1.2 and 0.9. Seed 1614 generates 300 independent standard normal traits and four independent errors per person.

1
2
3
set.seed(1614); z <- rnorm(300)
latent <- outer(z,c(.8,1,1.2,.9))+matrix(rnorm(1200),300)
ordinal_Y <- (latent> -1)+(latent>0)+(latent>1)

The sum of the three comparisons counts the boundaries exceeded. The four items share their generating cutpoints. Estimation will allow each item its own cutpoints, so it also requires a convention for defining the origin of that item’s latent response.

If both an item intercept and all its cutpoints shift by the same amount, the four category probabilities remain unchanged. In the fitted coordinates let $u_{ij}\mid z_i\sim N(\lambda_{0j}+\lambda_{1j}z_i,1)$ with a standard normal trait. Thus $\lambda_{0j}$ is the latent-response mean at trait zero, and $\lambda_{1j}$ is its change per trait SD. Fix the first finite cutpoint $\gamma_{j1}=0$ and give the intercept and the two remaining ordered cutpoints flat priors on their allowed values. These flat priors are improper because their total integrals are infinite; fixing the first cutpoint removes a location ambiguity but does not by itself establish a proper posterior. The slope prior is $N(0,4)$ restricted to positive values.

Report thresholds as $\gamma_{jk}-\lambda_{0j}$, on the latent-response scale relative to its mean at trait zero. Dividing a reported threshold by the positive slope gives the trait value where the cumulative probability below that boundary is one half. For example, an intercept of one and finite cutpoints $(0,1,2)$ give the reported thresholds $(-1,0,1)$. At $z_i=0$, the probability of category 1 is $\Phi(1-1)-\Phi(0-1)=\Phi(0)-\Phi(-1)$, just as in the generating model. In the ordinal branch of run_items() and in the call below, subtracting the sampled intercept from the fixed cutpoint zero gives the first reported threshold in each draw.

If the latent responses were fixed, the full conditional for a free cutpoint $\gamma_{jk}$ would be uniform in the gap with endpoints

\[L=\max\{\gamma_{j,k-1},\max_{i:y_{ij}=k-1}u_{ij}\},\qquad U=\min\{\gamma_{j,k+1},\min_{i:y_{ij}=k}u_{ij}\}.\]

At the ends set $\gamma_{j0}=-\infty$ and $\gamma_{j4}=\infty$. If either adjacent category is empty, omit its observation bound. The neighboring cutpoint on that side still limits the move. An omitted observation bound can leave an infinite interval, which does not support a uniform probability distribution. With observations close to a boundary on both sides, a conditional Gibbs update can move only a short distance.

The fitted sampler, ordinal_factor_gibbs(), uses a different cutpoint update: it proposes the two free cutpoints of one item together, with proposal scale $0.05/4=0.0125$. It evaluates the category probabilities with the latent responses integrated out and accounts for the forward and reverse proposal probabilities. After the decision, it draws latent responses between the retained cutpoints. If the proposal is rejected, these fresh responses use the old cutpoints. The cutpoint move with responses integrated out and the subsequent response draw must retain their stated order. The last two parts of ordinal_factor_gibbs() carry out this move and return the draws.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
    # Metropolis-Hastings move of the free cutpoints of each item; for a binary item the move changes nothing but
    # still uses one uniform draw.
    for (j in seq_len(K)) {
      proposal <- cut[, j]
      mean <- ordered_product(phi, c(intercept[j], slope[j]))
      if (categories[j] > 2L) for (c in 3:categories[j]) {
        proposal[c] <- if (c == categories[j]) mt_normal_above(rng, cut[c, j], tune[j]^2, proposal[c - 1L]) else
          mt_truncated_normal(rng, cut[c, j], tune[j]^2, proposal[c - 1L], cut[c + 1L, j])
      }
      y <- Y[, j]
      top <- y == categories[j]; bottom <- y == 1L; middle <- !top & !bottom
      terms <- numeric(N)
      terms[top] <- log(1 - pnorm(proposal[y[top]] - mean[top], 0, 1)) -
        log(1 - pnorm(cut[y[top], j] - mean[top], 0, 1))
      terms[bottom] <- log(pnorm(proposal[y[bottom] + 1L] - mean[bottom], 0, 1)) -
        log(pnorm(cut[y[bottom] + 1L, j] - mean[bottom], 0, 1))
      terms[middle] <- log(pnorm(proposal[y[middle] + 1L] - mean[middle], 0, 1) -
        pnorm(proposal[y[middle]] - mean[middle], 0, 1)) -
        log(pnorm(cut[y[middle] + 1L, j] - mean[middle], 0, 1) - pnorm(cut[y[middle], j] - mean[middle], 0, 1))
      log_ratio <- 0
      for (term in terms) log_ratio <- log_ratio + term
      if (categories[j] > 2L) for (c in 3:categories[j]) {
        log_ratio <- log_ratio +
          log(pnorm(cut[c + 1L, j], cut[c, j], tune[j]) - pnorm(proposal[c - 1L], cut[c, j], tune[j])) -
          log(pnorm(proposal[c + 1L], proposal[c], tune[j]) - pnorm(cut[c - 1L, j], proposal[c], tune[j]))
      }
      if (mt_uniform(rng) <= exp(log_ratio)) {
        for (c in seq_len(nrow(cut))) {
          if (cut[c, j] == 300) break
          cut[c, j] <- proposal[c]
        }
        accepted[j] <- accepted[j] + 1
      }
    }

For an item with four categories, rows 3 and 4 of cut contain the two free cutpoints. The first is proposed from a normal distribution centered at its current value with standard deviation tune[j], $0.05/4$, restricted to lie between the value below it in the proposal and the current value above it; the second is restricted only to lie above the first proposed value. The vector terms contains, for each person, the log of the category probability $\Phi(\tau_{k+1}-\eta_{ij})-\Phi(\tau_k-\eta_{ij})$ under the proposed cutpoints minus its log under the current ones, with $\eta_{ij}$ in mean; the top and bottom categories use one tail probability. The second loop adds, for each proposed cutpoint, the log of the probability that its forward proposal falls inside its limits minus the log of the same probability for the reverse proposal. These terms correct for the restricted proposals. The move is accepted when a uniform draw does not exceed the exponential of the total, and the accepted cutpoints replace the current ones up to the upper end. For a two-category item the loop over free cutpoints is skipped, but one uniform draw is still used, as in the translated program.

1
2
3
4
5
6
7
8
9
10
11
    if (iteration > burnin) {
      draws[iteration - burnin, ] <- c(rbind(intercept, slope))
      kept_cuts[iteration - burnin, , ] <- cut
    }
  }
  sweeps <- sweeps + burnin + retained
  list(intercept = draws[, 2L * seq_len(K) - 1L, drop = FALSE], slope = draws[, 2L * seq_len(K), drop = FALSE],
    cuts = kept_cuts, acceptance = accepted / sweeps,
    state = list(rng = as.list(rng, all.names = TRUE, sorted = TRUE), intercept = intercept, slope = slope, cut = cut,
      factor = factor, accepted = accepted, sweeps = sweeps))
}

The last part stores the coefficients and cutpoints after burn-in; acceptance divides accepted by sweeps, which counts burn-in and retained iterations. The returned state contains the random number state and the current values, so a later call can continue the chain. The following four-chain call uses the default 1,000 burn-in and 20,000 retained iterations, with seeds 1016241 through 1016244. In it prior_precision=c(0,.25) gives the intercept a flat prior and the slope prior precision one quarter.

1
2
3
4
5
6
7
8
9
10
ordinal_irt <- lapply(1016240L + 1:4, function(seed) {
  fit <- ordinal_factor_gibbs(ordinal_Y+1L,seed,prior_precision=c(0,.25))
  cuts <- do.call(cbind,lapply(1:4,function(j)fit$cuts[,2:4,j]-fit$intercept[,j]))
  colnames(fit$slope) <- paste0("slope",1:4)
  colnames(cuts) <- paste0("threshold",rep(1:4,each=3),"_",1:3)
  list(draws=cbind(fit$slope,cuts),acceptance=fit$acceptance)
})
print(c(largest_absolute_threshold=max(vapply(ordinal_irt,
  function(r) max(abs(r$draws[,5:16])), 0.0))))
print(t(vapply(ordinal_irt,function(r)r$acceptance,numeric(4))))
1
2
largest_absolute_threshold 
                  2.061057 
1
2
3
4
5
          [,1]      [,2]      [,3]      [,4]
[1,] 0.9167143 0.9192857 0.9215238 0.9110000
[2,] 0.9149524 0.9164286 0.9268571 0.9132857
[3,] 0.9170000 0.9198095 0.9228571 0.9136190
[4,] 0.9193333 0.9133810 0.9257619 0.9190000

The largest absolute reported threshold in these draws is 2.061. Rows index chains and columns index items, giving default acceptance rates from 0.91100 to 0.92686. High acceptance alone says little about movement through the posterior when proposals are small. Double the retained length at the same seeds, assessing all four slopes and twelve thresholds after each fit. Each longer run repeats the draws of the shorter one before it continues, so code/examples/handout-completion/augmentation.R obtains the same draws by continuing each chain from the final state of the previous length. Table 16.1 gives the worst diagnostic in each column across the sixteen parameters. The three extrema in a row may belong to different parameters.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
ord_stats <- item_diagnostics(ordinal_irt)
extrema(ord_stats)
for (retained in 20000L * c(2L,4L,8L,16L,32L)) {
  ord_long <- lapply(1016240L + 1:4, function(seed)
    run_items(TRUE,ordinal_Y,seed,retained))
  ord_stats <- item_diagnostics(ord_long)
  print(c(retained_per_chain=retained,extrema(ord_stats)))
  if (retained == 320000L) print(ord_stats[ord_stats$parameter == "a3",])
  if (meets_rule(ord_stats)) break
}
range(vapply(ord_long,function(r) range(r$draws[,5:16]),numeric(2)))
rates <- do.call(rbind,lapply(seq_along(ord_long),function(i)
  data.frame(chain=i,item=1:4,acceptance=ord_long[[i]]$acceptance,
    retained_per_chain=retained)))
range(rates$acceptance)

Table 16.1. Diagnostics across the sixteen item parameters at each retained length.

Item modelDraws per chainLargest $\widehat R$Smallest bulk ESSSmallest tail ESS
Dichotomous10,0001.01368393.517520.232
Dichotomous20,0001.00927667.932823.223
Ordinal20,0001.05022108.198139.547
Ordinal40,0001.0552451.76564.116
Ordinal80,0001.02498147.344236.247
Ordinal160,0001.01302231.176336.946
Ordinal320,0001.00431610.533868.559

At 320,000 draws per chain, the largest $\widehat R$ is 1.00431, the smallest bulk ESS is 610.533 and the smallest tail ESS is 868.559; all three belong to slope three, whose row the loop prints at this length. This is the first tested length at which all three criteria are met for every parameter, so the loop stops before 640,000. The retained thresholds range from $-2.0507$ to 2.4530. These are observed extremes under the stated priors. For each item and chain, the sampler divides accepted cutpoint proposals by all iterations, including burn-in. The default denominator is 21,000 and the final denominator is 321,000. Extended rates range from 0.91208 to 0.92798. The saved acceptance table has one row for each combination of chain and item, sixteen rates in all.

Pólya-Gamma augmentation for logistic models

For logistic data, the quadratic in the coefficients can be obtained by introducing a different auxiliary variable. Consider $y$ successes in $m$ independent trials, with log odds $\eta$, and put $\kappa=y-m/2$. The binomial likelihood obeys the Pólya-Gamma identity

\[{m\choose y}\frac{\exp(y\eta)}{(1+\exp\eta)^m} ={m\choose y}\frac{\exp(\kappa\eta)}{2^m} \int_0^\infty \exp(-\omega\eta^2/2)\,p_{PG}(\omega\mid m,0)\,d\omega .\]

Here $p_{PG}(\cdot\mid m,0)$ is the $PG(m,0)$ Pólya-Gamma density. The integral equals $\cosh^{-m}(\eta/2)$, as can also be seen by writing $1+\exp(\eta)=2\exp(\eta/2)\cosh(\eta/2)$. Retaining $\omega$ in the integrand defines a joint distribution for the response and the auxiliary variable. At given $\eta$ the terms independent of $\omega$ cancel, and normalizing the $PG(m,0)$ density multiplied by $\exp(-\omega\eta^2/2)$ gives $PG(m,\eta)$. At given $\omega$, the terms involving the linear predictor have log density $\kappa\eta-\omega\eta^2/2$ up to a constant. This quadratic permits a normal coefficient update even though the original success probability is logistic.

For observation $i$ in group $g(i)$, let $\eta_i=x_i^\top\beta+o_i+b_{g(i)}$, where $o_i$ is a known offset and $b_g$ is a random intercept. With the group effect and offset fixed, a regression coefficient gives the change in conditional log odds per unit of its covariate. Given the group effects and coefficients, the observations are independent binomials. The group effects are independently $N(0,\tau^2)$, with $\tau^2\sim IG(2,1)$. The variance describes between-group variation in the conditional log odds at common covariates and offsets, in squared log-odds units.

Draw $\omega_i$ at the linear predictor formed from the coefficients and group effects entering the sweep. Write $\Omega=\operatorname{diag}(\omega_i)$, $\kappa_i=y_i-m_i/2$ and $h_i=o_i+b_{g(i)}$. Insert $X\beta+h$ into the augmented quadratic and add the log density of the normal prior with mean $b_0$ and covariance $B_0$. The normal conditional has precision $P$ and mean $\mu$ satisfying

\[P=X^\top\Omega X+B_0^{-1},\qquad P\mu=X^\top(\kappa-\Omega h)+B_0^{-1}b_0.\]

Use a coefficient prior independent of the group-variance prior, with $b_0=0$ and $B_0=4I$. Its precision is $I/4$, as in the probit fit. Given the new $\beta$ and a current random-intercept variance $\tau^2$, the normal for group $g$ has precision $\tau^{-2}+\sum_{i:g(i)=g}\omega_i$. Its mean is that precision’s reciprocal times $\sum_{i:g(i)=g}[\kappa_i-\omega_i(o_i+x_i^\top\beta)]$. One sweep below uses the old $b$ for the coefficient update and the new coefficients for the group update. The sum of squares for the final variance draw uses the newly sampled group effects.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
source("code/lib/bayes_factor.R")
pg_glmm_step <- function(y,X,id,old,offset=rep(0,length(y)),trials=rep(1,length(y))) {
  q <- ncol(X); m <- length(old$b)
  # Draw the auxiliary variables at the entering linear predictors.
  eta <- drop(X%*%old$beta)+offset+old$b[id]
  omega <- BayesLogit::rpg(length(y),trials,eta)
  kappa <- y-trials/2
  # Draw the fixed effects conditional on the entering group effects.
  beta <- draw_from_precision(crossprod(X,X*omega)+diag(.25,q),
    crossprod(X,kappa-omega*(offset+old$b[id])))
  sum_by_group <- function(v) {
    sums <- rowsum(v,id)
    result <- numeric(m)
    result[as.integer(rownames(sums))] <- sums[,1]
    result
  }
  # Update group effects using the new fixed effects.
  precision <- 1/old$variance+sum_by_group(omega)
  rhs <- sum_by_group(kappa-omega*(offset+drop(X%*%beta)))
  b <- rnorm(m,rhs/precision,1/sqrt(precision))
  # Update the variance using the new group effects.
  variance <- 1/rgamma(1,shape=2+m/2,rate=1+sum(b^2)/2)
  list(state=list(beta=beta,b=b,variance=variance),tilt_first=eta[1],omega_first=omega[1])
}

In the coefficient update, diag(.25,q) adds the prior precision $I/4$ to $X^\top\Omega X$. This is the precision supplied by the argument B0=.25 in the probit fit. The function draw_from_precision() solves the normal system using a Cholesky factor and adds noise with covariance $P^{-1}$.

The argument trials supplies the binomial totals. Inside pg_glmm_step(), the local variable m counts groups. The group sums put each observation’s terms in the precision and mean into the position of its own intercept. For a group whose auxiliary variables sum to a small number, the common prior precision $1/\tau^2$ accounts for a larger share of its conditional precision.

Fits to the binary GLMM80 responses

The binary responses in GLMM80 give one trial per observation. Each of 80 independent clusters contributes eight observations, with covariates equally spaced from $-1$ to 1 and zero offsets. Here the two fixed coefficients have prior $N_2(0,4I_2)$. The fixed intercept is the conditional log odds of success at $x=0$ for a cluster with $b_g=0$. For two observations in the same cluster one unit apart in $x$, the difference in conditional log odds equals the slope. The realized $b_g$ shifts all eight linear predictors in its cluster.

Multiplying the inverse gamma prior by the 80 normal densities gives shape $2+80/2=42$ and rate $1+\sum_g b_g^2/2$ for the conditional gamma draw of $1/\tau^2$. The stored grouped design in data/derived/ch09/fits.rds uses the observations from data/source/ch09/GLMM80-binary.rds.

To run four chains, the following functions assign a separate random number stream to each chain and repeatedly apply a supplied update. Each run discards 2,000 warmup sweeps and retains the next 4,000 transitions.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
source("code/lib/boundary_test.R")
four_streams <- function(seed, run) {
  RNGkind("L'Ecuyer-CMRG","Inversion","Rejection")
  set.seed(seed)
  streams <- replicate_streams(4L,.Random.seed)
  lapply(seq_along(streams), function(id) {
    assign(".Random.seed",streams[[id]],envir=.GlobalEnv)
    run(id)
  })
}
run_chain <- function(initial,kernel,extract,warm=2000L,keep=4000L) {
  # End warmup before recording the first transition.
  x <- initial
  for(i in seq_len(warm)) x <- kernel(x)$state
  seed_before <- .Random.seed
  samples <- matrix(NA_real_,keep,length(extract(x)))
  colnames(samples) <- names(extract(x))
  first_transition <- NULL
  for(i in seq_len(keep)) {
    move <- kernel(x)
    if(i == 1L) first_transition <- move[setdiff(names(move),"state")]
    x <- move$state
    samples[i,] <- extract(x)
  }
  list(draws=samples,state=x,first_transition=first_transition,
    rng_before=seed_before,rng_after=.Random.seed)
}

The function four_streams() initializes each stream and calls the supplied run(id) function with its chain number. Within that call, run_chain() passes the current state to kernel(), which must return a list containing the next state. Its extract() argument selects the numeric quantities to store in the rows of draws. The function also returns the final state, random-number states before and after retained sampling, and the extra fields from the first retained transition.

For the grouped data, start the four R streams from root seed 101634. Each chain starts with zero coefficients and group effects, and variance $0.3$ times the chain index. The extraction function retains the fixed intercept, fixed slope, random-intercept variance and first cluster’s deviation, in that order.

1
2
3
4
5
6
7
fits <- readRDS("data/derived/ch09/fits.rds")
grouped <- fits$binary
pg <- four_streams(101634,function(id) run_chain(
  list(beta=c(0,0),b=rep(0,grouped$groups),variance=.3*id),
  function(s) pg_glmm_step(grouped$y,grouped$X,grouped$group_index,s),
  function(s) c(s$beta,s$variance,s$b[1])))
print(report_chains(pg))
1
2
3
4
5
           mean        sd     Rhat  ESS_bulk  ESS_tail        MCSE
[1,] -0.1905070 0.1123798 1.000470  5813.262  9044.188 0.001475237
[2,]  0.7261306 0.1321672 1.000189 11369.982 14478.601 0.001241280
[3,]  0.4343528 0.1554540 1.003576  1688.049  2897.992 0.003650460
[4,] -0.1564351 0.4902753 1.000258 15132.523 13792.557 0.003985634

The four rows describe the fixed intercept, fixed slope, random-intercept variance and first cluster’s deviation. The fixed intercept has posterior mean $-0.19051$ with MCSE 0.00148, and the common slope has posterior mean 0.72613 with MCSE 0.00124. The random-intercept variance has posterior mean 0.43435 in squared log-odds units with MCSE 0.00365. The posterior SD of this variance parameter is 0.15545. This is the uncertainty about between-cluster variation given the 640 responses, whereas 0.00365 measures the precision achieved in estimating its mean from the four chains.

For the same observations, seven-node adaptive quadrature returned coefficients $-0.1912$ and 0.7212 at its stopping point. The components of fits$adaptive$beta give those two coefficients. The square root of fits$adaptive$G[1] is the reported standard deviation of 0.6057595. Square that value to compare variances. The resulting 0.3669 is below 0.4344 by more than the latter mean’s MCSE of 0.00365. The quadrature procedure optimizes an approximate marginal likelihood, while the simulation averages over the posterior given the specified priors. The numerical gap alone does not isolate the contribution of the prior.

Look inside the first retained transition of the first grouped chain. Its initial state is the one reached after 2,000 warmup sweeps. Observation one has covariate $-1$ and belongs to the first cluster. Its entering linear predictor is consequently the entering intercept minus the entering slope plus that cluster’s entering deviation. The random-number function supplies an auxiliary draw at this linear predictor. The construction of the augmented likelihood, the coefficient and group updates and their order are explicit in pg_glmm_step(). The values in the transition record identify the entering linear predictor and the auxiliary draw used in that coefficient update.

1
print(pg[[1]]$first_transition)
1
2
3
4
5
$tilt_first
[1] -1.064222

$omega_first
[1] 0.3029205

The draw is 0.3029205 at a linear predictor of $-1.064222$. A $PG(1,c)$ variable has mean $\tanh(c/2)/(2c)$ for $c\ne0$, with limit $1/4$ at zero. Substitution of this transition’s linear predictor gives 0.22880. A single draw can differ from its conditional mean. Replacing the draw by that mean would omit the variation in $\omega$ that enters the next normal coefficient draw.

A scalar check against quadrature

A separate scalar model permits a check of a complete posterior mean. Observe two successes in ten trials with only an intercept $x$, the common log odds of success, and prior $x\sim N(0,4)$. Here $\kappa=2-10/2=-3$. At the current $x$ draw one $\omega\sim PG(10,x)$ for the ten trials together. The next intercept has conditional variance $v=1/(\omega+1/4)$ and mean $-3v$. Run four streams from root seed 101644, each starting at zero, with 2,000 warmup and 4,000 retained draws. To compute the same expectation by quadrature, use the 81 nodes and weights for a standard normal and double each node to represent the prior SD of two. Multiplying the weights by the binomial probabilities at these nodes and normalizing them gives weights for the posterior mean.

1
2
3
4
5
6
7
8
9
10
11
12
13
source("code/lib/stability.R")
source("code/lib/integration.R")
rule <- normal_rule(81L); nodes <- 2*rule$nodes
mass <- normalize_logweights(log(rule$weights)+dbinom(2,10,plogis(nodes),log=TRUE))
pg_scalar <- four_streams(101644,function(id) run_chain(0,function(x) {
  w <- BayesLogit::rpg(1,10,x)
  v <- 1/(w+.25)
  list(state=rnorm(1,-3*v,sqrt(v)))
},identity))
scalar_moments <- c(quadrature_mean=sum(mass*nodes),
  PG_mean=mean(four_matrix(pg_scalar,1)),
  MCSE=mean_mcse(four_matrix(pg_scalar,1)))
print(scalar_moments)
1
2
quadrature_mean         PG_mean            MCSE 
   -1.327418943    -1.323132128     0.007240183 

The augmentation estimate is $-1.32313$ and the quadrature value is $-1.32742$. Their absolute difference of 0.00429 is smaller than the Monte Carlo standard error of 0.00724. Quadrature weights the intercept values directly by their binomial likelihood. Its agreement with the chain checks the mean obtained by alternating an auxiliary draw and a normal intercept draw. This comparison checks one posterior moment at the chosen quadrature order; increasing the number of nodes is a separate check on the numerical reference.

The probit regression and item samplers are translated from MCMCpack, which Section 16.10 runs with the same seeds for comparison; BayesLogit supplies the Pólya-Gamma random draws.

16.5 Random-walk Metropolis, Metropolis-within-Gibbs, and adaptive Metropolis-Hastings

To sample a binomial intercept, a random walk can compare its posterior density at the current and proposed values using the observed count and the prior. The unknown normalizing constant cancels in the ratio. When sampling one person’s trait at fixed item parameters, only that person’s responses and trait density entered the target density. When the proposed block is a population parameter, every observation whose density depends on it contributes to the ratio, along with its prior.

For a block $v$ with all other unknowns $w$ fixed, let $\ell(v)$ denote the joint log density of $Y,v,w$ up to terms constant in $v$. Its differences also give differences of the full conditional log density.

For a symmetric random walk from $v$ to $v^{\prime}$, the acceptance probability is $\min\lbrace 1,\exp[\ell(v^{\prime})-\ell(v)]\rbrace $. A rejected proposal contributes another visit to the current state. Omitting that visit would shorten residence times precisely where proposals are often rejected. Updating all parameters together uses the same rule on their joint posterior. If latent variables have already been integrated out, the observed-data likelihood supplies the likelihood term.

For two successes in ten trials, let $v$ be the log odds of success and give it a $N(0,4)$ prior. Its log posterior density is $2v-10\log(1+e^v)-v^2/8$ plus a constant. Four random walks used streams from root seed 101605 and began warmup at $j-2.5$ for chain $j=1,\ldots,4$. Each walk adjusted its proposal scale during warmup, then sampled with the scale fixed.

Compare its draws with the Pólya-Gamma draws for the same intercept. From the book directory, the calculation in code/practice/16.5.R reads one matrix per method. Each column contains 4,000 successive draws from one chain. The mean and SD use all 16,000 values, while mean_mcse() uses the column structure to estimate the Monte Carlo standard error of the mean (Section 16.8).

Warmup here includes proposal adaptation and is excluded from posterior summaries. The discarded initial Gibbs sweeps above used fixed update rules; discarding early draws and adapting a proposal are different operations.

1
2
3
4
5
6
source("code/lib/posterior_checks.R", local=TRUE)
scalar <- readRDS("data/derived/ch16/scalar-posterior-chains.rds")
posterior_moments <- t(vapply(scalar$draws, function(x) {
  c(mean=mean(x), sd=sd(as.numeric(x)), MCSE=mean_mcse(x))
}, c(mean=0,sd=0,MCSE=0)))
print(posterior_moments)
1
2
3
        mean        sd        MCSE
MH -1.318857 0.7230203 0.014960109
PG -1.323132 0.7446054 0.007240183

A separate quadrature calculation weights the binomial likelihood at 81 points by their normal prior weights. Doubling the standard normal nodes puts them on the prior scale. The weighted squared deviations give the posterior variance.

1
2
3
4
5
6
7
source("code/lib/stability.R")
source("code/lib/integration.R")
rule <- normal_rule(81L); nodes <- 2*rule$nodes
mass <- normalize_logweights(log(rule$weights)+dbinom(2,10,plogis(nodes),log=TRUE))
quadrature_mean <- sum(mass*nodes)
quadrature_sd <- sqrt(sum(mass*(nodes-quadrature_mean)^2))
c(mean=quadrature_mean, sd=quadrature_sd)

The quadrature mean is $-1.32742$ and the SD is 0.74599. The random-walk mean of $-1.31886$ differs by 0.00856, about 0.57 of its MCSE of 0.01496. The Pólya-Gamma mean is $-1.32313$ with MCSE 0.00724. Their posterior SD estimates are 0.72302 and 0.74461.

To see which proposal each random walk used, read the four warmup endpoints and the tuning results.

1
print(scalar$proposal)
1
2
3
4
5
          start proposal_scale_squared warmup_acceptance retained_acceptance
[1,] -1.8289950               1.198481             0.449             0.42925
[2,] -1.8101217               1.148213             0.451             0.45075
[3,] -0.9842387               1.130576             0.448             0.44225
[4,] -1.6358450               1.306121             0.475             0.42075

The squared proposal scales range from 1.130576 to 1.306121. The scalar increment is a scaled $t$ draw with one degree of freedom, so its variance does not exist. Warmup acceptance is reported to three decimal places, from 0.448 to 0.475. In retained sampling the acceptance fractions range from 0.42075 to 0.45075.

A Metropolis step inside a Gibbs sweep

A single nonconjugate block can also be updated inside a Gibbs sweep. For 20 people observed at $x=-1,0,1$, take $y_{it}=\beta_0+\beta_1x_t+b_i+e_{it}$ with independent unit-variance normal errors, $b_i\mid\sigma\sim N(0,\sigma^2)$ and $\beta\sim N_2(0,4I_2)$. The coefficient $\beta_0$ is the population mean response at $x_t=0$, while $\beta_1$ is the common mean-response change per unit of $x_t$. The deviation $b_i$ shifts all three responses for person $i$ by the same amount. Its SD $\sigma$ measures between-person variation in intercepts in response units. The residual variance is fixed at one and describes variation around each person’s conditional mean.

Give $\sigma$ a half-$t$ prior with four degrees of freedom and unit scale. Conditional on the current coefficients and $\sigma$, the normal update for $b_i$ has precision $3+\sigma^{-2}$ and a mean equal to the sum of that person’s fixed-effect residuals divided by this precision. For the fixed effects, regress $y_{it}-b_i$ on $(1,x_t)$ using the new $b_i$. The prior adds $I_2/4$ to the regression precision. With the new group effects fixed, propose $u^{\prime}=u+\epsilon$ on the log SD scale, where $u=\log\sigma$ and $\epsilon\sim N(0,0.3^2)$. Writing $\phi(b;0,s^2)$ for a normal density and $t_4$ for the standard $t$ density, the log conditional density on the log SD scale is

\[\ell(u)=\sum_{i=1}^{20}\log\phi(b_i;0,e^{2u}) +\log 2+\log t_4(e^u)+u+C .\]

The final $u$ is the log Jacobian of $\sigma=e^u$. Only the proposed log SD requires an acceptance decision. The normal draws of the group effects and coefficients both take effect in this sweep.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
.libPaths(c(".R-library", .libPaths()))
source("code/lib/mcmc.R")
source("code/lib/bayes_factor.R")
random_intercept_gibbs_mh <- function(Y, x, state, proposal_sd=.3) {
  Z <- cbind(1,x)
  groups <- nrow(Y)
  sigma <- exp(state$log_sd)
  # Draw the person intercepts at the current SD.
  precision_b <- ncol(Y)+1/sigma^2
  rhs_b <- rowSums(sweep(Y,2,drop(Z%*%state$beta)))
  b <- rnorm(groups,rhs_b/precision_b,1/sqrt(precision_b))
  # Regress the responses on the covariate after subtracting the new person effects.
  beta <- draw_from_precision(groups*crossprod(Z)+diag(.25,2),
    crossprod(Z,colSums(Y-b)))
  # Evaluate the conditional density on the log SD scale.
  target <- function(u) {
    tau <- exp(u)
    if(!is.finite(tau) || tau==0) return(-Inf)
    sum(dnorm(b,sd=tau,log=TRUE))+log(2)+dt(tau,df=4,log=TRUE)+u
  }
  move <- mh_step(state$log_sd,target,function(u)u+rnorm(1,sd=proposal_sd))
  list(state=list(beta=beta,b=b,log_sd=move$state),accepted=move$accepted)
}

In random_intercept_gibbs_mh(), precision_b is $3+\sigma^{-2}$ and rhs_b contains each person’s sum of fixed-effect residuals. The call to draw_from_precision() uses the precision groups*crossprod(Z)+diag(.25,2), the regression precision for $y_{it}-b_i$ on $(1,x_t)$ plus $I_2/4$. The function target() is $\ell(u)$ without $C$, and mh_step() (Section 14.2) accepts or rejects $u^{\prime}$.

Generate three measurements per person with intercept one, slope 0.5 and random-intercept SD 0.15. Four streams from root seed 101615 start with zero fixed and group effects and SDs of 0.2, 0.4, 0.6 and 0.8. The call to mcmc() runs 2,000 warmup sweeps. From each endpoint, resume_mcmc() records 4,000 further sweeps on the same stream.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
source("code/lib/boundary_test.R")
four_streams <- function(seed, run) {
  RNGkind("L'Ecuyer-CMRG","Inversion","Rejection")
  set.seed(seed)
  streams <- replicate_streams(4L,.Random.seed)
  lapply(seq_along(streams), function(id) {
    assign(".Random.seed",streams[[id]],envir=.GlobalEnv)
    run(id)
  })
}
four_matrix <- function(chains,j) vapply(chains,
  function(r)r$draws[,j],numeric(nrow(chains[[1]]$draws)))
report_chains <- function(chains) do.call(rbind,lapply(
  seq_len(ncol(chains[[1]]$draws)),function(j)
  chain_summary(four_matrix(chains,j))))
1
2
3
4
5
6
7
8
9
10
11
12
13
14
RNGkind("Mersenne-Twister","Inversion","Rejection")
set.seed(1606)
x <- c(-1,0,1); b <- rnorm(20,sd=.15)
Yweak <- matrix(rep(1+.5*x,each=20),20)+b+matrix(rnorm(60),20)
within_gibbs <- four_streams(101615,function(id) {
  start <- list(beta=c(0,0),b=rep(0,nrow(Yweak)),log_sd=log(.2*id))
  step <- function(state) random_intercept_gibbs_mh(Yweak,x,state)
  warm <- mcmc(start,step,2000L)
  kept <- resume_mcmc(warm,step,4000L)
  draws <- t(vapply(kept$draws,function(s)
    c(beta0=s$beta[1],beta1=s$beta[2],SD=exp(s$log_sd),b1=s$b[1]),numeric(4)))
  list(draws=draws)
})
print(report_chains(within_gibbs))
1
2
3
4
5
           mean        sd     Rhat   ESS_bulk   ESS_tail        MCSE
[1,]  1.1956209 0.1668149 1.000789  6575.4569  6846.0007 0.002081290
[2,]  0.6197738 0.1578343 0.999951 15763.4574 15706.6492 0.001257179
[3,]  0.4261677 0.1939586 1.010112   209.0417   113.9434 0.012801525
[4,] -0.1559816 0.3573953 1.000740  4690.8526  6631.8390 0.005646938

Read the third row on the SD scale. Its posterior mean is 0.4262, with $\widehat R=1.010112$, bulk effective sample size (ESS) 209 and tail ESS 114. It misses the criteria of $\widehat R<1.01$ and both ESS values above 400. In the same sweeps the fixed intercept and slope have bulk ESS of 6,575 and 15,763. The shortfall is specific to the scale of between-person variation, especially its tails.

Adapting the proposal shape during warmup

For a block of dimension $d$, the adaptive walk proposes $v^{\prime}=v+S_k U_k$. The components of $U_k$ are independent univariate $t$ draws, each with $d$ degrees of freedom. The lower triangular Cholesky factor $S_k$ of the proposal shape starts at the identity. Let $a_k$ be the proposal’s acceptance probability and $a^\star$ the chosen target acceptance probability, 0.44 in one dimension and 0.234 in higher dimensions. At warmup index $k$, put $h_k=U_k/\Vert U_k\Vert $ and $g_k=\min(1,d\,k^{-2/3})$. The matrix $S_kS_k^\top$ specifies proposal shape. It is not a covariance when $d\leq2$, and for $d>2$ the covariance is $dS_kS_k^\top/(d-2)$. Independent univariate $t$ components also do not produce the usual multivariate $t$ distribution. The target acceptance values are tuning choices, not universal optima for these targets. The next Cholesky factor satisfies

\[S_{k+1}S_{k+1}^\top =S_k\{I_d+g_k(a_k-a^\star)h_kh_k^\top\}S_k^\top .\]

For $a_k>a^\star$, the squared scale increases along the transformed proposal direction. An acceptance probability below its target value decreases it. The adjustment uses the probability even when the uniform draw rejects the move. The function adaptive_random_walk() in code/lib/augment.R draws the $t$ increments, makes the Metropolis decision and, during warmup, applies this update as a rank-one change of the Cholesky factor (adapt_proposal_factor()). It is translated from MCMC() of adaptMCMC and the Cholesky updates of ramcmc (code/NOTICE.md).

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
adaptive_random_walk <- function(target, n, start, scale = rep(1, length(start)), adapt = FALSE, target_acceptance,
                                 gamma = 2/3) {
  d <- length(start)
  states <- matrix(NA, ncol = d, nrow = n)
  states[1, ] <- start
  log_density <- rep(NA, n)
  log_density[1] <- target(states[1, ])
  M <- if (d > 1) { if (length(scale) == d) diag(scale) else scale } else matrix(scale)
  S <- t(chol(M))
  accepted <- 0
  for (i in 2:n) {
    t_draw <- rt(d, df = d)
    proposal <- c(states[i - 1, ] + S %*% t_draw)
    proposal_log_density <- target(proposal)
    alpha <- min(1, exp(proposal_log_density - log_density[i - 1]))
    if (!is.finite(alpha)) alpha <- 0
    if (runif(1) < alpha) {
      states[i, ] <- proposal
      log_density[i] <- proposal_log_density
      accepted <- accepted + 1
    } else {
      states[i, ] <- states[i - 1, ]
      log_density[i] <- log_density[i - 1]
    }
    if (adapt) S <- adapt_proposal_factor(S, t_draw, alpha, target_acceptance, i, gamma)
  }
  list(samples = states, log_density = log_density, proposal_scale = S %*% t(S),
    acceptance_rate = round(accepted / (n - 1), 3))
}

The first row of states is the start. In each step, t_draw contains $U_k$, the proposal adds $S_kU_k$ to the current state, and alpha is the acceptance probability $a_k$; a nonfinite value counts as zero. The uniform draw then decides whether the chain moves. The argument scale gives the initial proposal shape $S_1S_1^\top$, a diagonal matrix when it is a vector, and S is its lower Cholesky factor. With adapt = TRUE, every step updates the factor with adapt_proposal_factor().

1
2
3
4
5
6
7
adapt_proposal_factor <- function(S, t, alpha, target, n, gamma) {
  change <- alpha - target
  length_t <- 0
  for (v in t) length_t <- length_t + v * v
  u <- drop(S %*% t) / sqrt(length_t) * sqrt(min(1, length(t) * n^(-gamma)) * abs(change))
  cholesky_rank_one(S, u, if (change > 0) 1 else -1)
}

Here u is $S_kh_k$ multiplied by $\lbrace g_k\vert a_k-a^\star\vert \rbrace ^{1/2}$ with $g_k=\min(1,dk^{-2/3})$, so $S_kS_k^\top\pm uu^\top$ is the right side of the update above, with the sign of $a_k-a^\star$. The function cholesky_rank_one() returns the lower Cholesky factor of that matrix directly from $S_k$ and $u$, column by column, without factoring the new matrix again. The wrapper below separates warmup from retained sampling. Its first sampler call returns the final proposal shape and position; its second fixes that shape. Apply it to the scalar posterior already summarized above.

1
2
3
4
5
6
7
8
9
10
11
12
13
adaptive_metropolis <- function(start,target,warmup=2000L,keep=4000L,
                                acc.rate=if (length(start)==1L) .44 else .234) {
  warm <- adaptive_random_walk(target,warmup,start,adapt=TRUE,target_acceptance=acc.rate)
  # Start the fixed walk at the warmup endpoint.
  begin <- warm$samples[warmup,]
  rng_before <- .Random.seed
  kept <- adaptive_random_walk(target,keep+1L,begin,scale=warm$proposal_scale)
  moves <- diff(kept$samples)
  list(draws=kept$samples[-1L,,drop=FALSE],start=begin,proposal=warm$proposal_scale,
    warmup_acceptance=warm$acceptance_rate,acceptance=mean(rowSums(moves!=0)>0),
    squared_jump=mean(rowSums(moves^2)),proposals=keep,
    rng_before=rng_before,rng_after=.Random.seed)
}
1
2
3
scalar_log <- function(x)dbinom(2,10,plogis(x),log=TRUE)+dnorm(x,sd=2,log=TRUE)
mh_scalar <- four_streams(101605,function(id)
  adaptive_metropolis(id-2.5,scalar_log))

The 2,000 warmup rows include the initial state, leaving 1,999 attempted transitions. The second call starts at the last warmup state and requests 4,001 rows. Dropping its starting row leaves 4,000 attempted transitions. Taking differences before dropping that row includes the first retained move when calculating acceptance and squared displacement.

Freezing $S$ means that, conditional on the tuning result for a chain, every retained step uses the same transition rule. Continuing to adapt would require an argument for convergence with changing rules. Diminishing adaptation requires the largest total variation distance between successive transition rules, over starting states, to approach zero in probability. For a specified accuracy, consider how many steps the current rule would need to approach the posterior from the current state if that rule remained fixed. A further condition is that these times remain bounded in probability along the adaptive run. This is the bounded convergence condition.

An acceptance plot records how often proposals succeed. It establishes neither condition. Fixing the Cholesky factor $S$ after warmup lets the retained draws be assessed with one proposal rule per chain. Freezing adaptation does not establish that the retained chain has already reached the posterior.

Block and coordinate proposals

How much movement does a proposal buy? First target a centered bivariate normal with unit marginal variances and correlation 0.8. Then use the marginal posterior for the eight item parameters of the one-factor model for BAYES4 after integrating out the person factors. The joint proposal moves every coordinate at once. Its competitor starts at the same warmup endpoint and visits each coordinate in turn, with a centered normal increment scaled by the square root of the corresponding diagonal of $SS^\top$. Each acceptance decision uses the latest state. After the last coordinate, record one draw and the squared Euclidean distance from the preceding sweep endpoint.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
coordinate_sweeps <- function(start,target,scale,keep=4000L,extract=identity) {
  x <- start
  draws <- matrix(0,keep,length(extract(x)))
  moves <- jumps <- numeric(keep)
  for(i in seq_len(keep)) {
    previous <- x
    for(j in seq_along(x)) {
      step <- mh_step(x,target,function(u) {
        u[j] <- u[j]+rnorm(1,sd=scale[j])
        u
      })
      x <- step$state
      moves[i] <- moves[i]+as.integer(step$accepted)
    }
    # Measure the displacement after all coordinate proposals.
    jumps[i] <- sum((x-previous)^2)
    draws[i,] <- extract(x)
  }
  list(state=x,draws=draws,acceptance=sum(moves)/(keep*length(x)),
    squared_jump=mean(jumps),proposals=keep*length(x))
}

For the normal target, use root seeds 101655 for the block runs and 101665 for the coordinate runs. For the factor posterior, use 101675 and 101685. The observed matrix has 150 rows and four columns. On the sampling scale the first loading and the unique variances are logged, so the log target density includes their change-of-variables terms. After measuring displacement, convert the sampled parameters back to the original scale for reporting.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
walk_pair <- function(seed,start,target,extract) {
  block <- four_streams(seed,function(id) {
    r <- adaptive_metropolis(start(id),target)
    r$draws <- t(apply(r$draws,1,extract))
    r
  })
  coordinate <- four_streams(seed+10L,function(id)
    coordinate_sweeps(block[[id]]$start,target,sqrt(diag(block[[id]]$proposal)),
      extract=extract))
  list(block=block,coordinate=coordinate)
}
Rho <- matrix(c(1,.8,.8,1),2)
normal_log_density <- function(z)-sum(z*solve(Rho,z))/2
normal_walks <- walk_pair(101655,function(id)c(id-2.5,0),normal_log_density,identity)
Y <- readRDS("data/source/ch16/BAYES4.rds")
prior <- bayes4_prior()
log_target <- bayes4_target(Y,prior,transformed=TRUE,marginal=TRUE)
factor_start <- function(id,n) list(loading=c(.3,.5,.7,.9)*(.4+id/2),
  variance=rep(.2*id,4),z=rep(0,n))
factor_parameters <- function(s) setNames(c(s$loading,s$variance),
  c(paste0("loading",1:4),paste0("variance",1:4)))
factor_walks <- walk_pair(101675,function(id) {
  init <- factor_start(id,nrow(Y))
  bayes4_coordinates(init$loading,init$variance)
},log_target$value,function(u)factor_parameters(bayes4_unpack(u)))

In walk_pair(), start(id) supplies a chain’s initial sampling coordinates, target() evaluates their log density, and extract() converts them to the reported quantities. The returned block and coordinate lists each contain four chain records. For the factor model, factor_start() supplies the initial loadings, variances and zero factors, while factor_parameters() collects and names the eight population parameters for reporting.

For each method, pool the proposal counts from four chains. Each contributes the same number of sweeps. Average the squared distances over all sweeps, including those with zero displacement, and use one column per chain to estimate bulk ESS for the first reported parameter with bulk_ess() (Section 16.8).

1
2
3
4
5
6
7
8
9
for(comparison in list(normal=normal_walks,factor=factor_walks)) {
  print(do.call(rbind,lapply(comparison,function(chains) {
    draws <- four_matrix(chains,1)
    c(mean=mean(draws),MCSE=mean_mcse(draws),ESS=bulk_ess(draws),
      acceptance=mean(vapply(chains,function(x)x$acceptance,0.0)),
      squared_jump=mean(vapply(chains,function(x)x$squared_jump,0.0)),
      post_warmup_proposals_attempted=sum(vapply(chains,function(x)x$proposals,0.0)))
  })))
}
1
2
3
4
5
6
7
8
9
10
11
12
                   mean       MCSE       ESS acceptance squared_jump
block       0.036262381 0.02383324 1715.8329  0.2371875    0.6813736
coordinate -0.006009489 0.03453593  799.1292  0.3873125    0.5176280
           post_warmup_proposals_attempted
block                                16000
coordinate                           32000
                mean        MCSE       ESS acceptance squared_jump
block      0.7807978 0.003861493  384.1579  0.2289375   0.01338065
coordinate 0.7805640 0.002332888 1001.1455  0.7422656   0.03334235
           post_warmup_proposals_attempted
block                                16000
coordinate                          128000

For the first normal coordinate, the block gives bulk ESS 1,715.8 from 16,000 retained proposals, or 0.1072 per proposal. Coordinate updates accept more often, 0.387 against 0.237, but travel less per sweep on average in squared distance, 0.518 against 0.681. They give 799.1 effective draws from 32,000 proposals, or 0.0250 per proposal.

For the factor model the two means for the first loading, 0.7808 and 0.7806, agree closely. Coordinate updates attain a larger total ESS, 1,001.1 against 384.2, with acceptance 0.742 against 0.229. Each coordinate sweep requires eight proposals on the sampling scale. The jump column measures displacement in those eight coordinates, while ESS refers to the untransformed loading. Dividing by 128,000 and 16,000 respectively gives 0.00782 and 0.0240 effective draws per proposal. The ranking changes with the denominator.

These denominators omit warmup and the differing costs of a proposal. A method that fails the chain diagnostics cannot be endorsed for posterior inference solely from this ratio.

Each Metropolis proposal here has the same forward and reverse density on the scale of the decision. For an asymmetric proposal with density $q(v^{\prime}\mid v)$, add $\log q(v\mid v^{\prime})-\log q(v^{\prime}\mid v)$ to the log ratio of target densities in mh_step().

The fixed part of a scalar chain can be reproduced by restoring its starting state, proposal shape and random number stream. The two equality checks compare all retained rows and the final generator state for each of the four chains.

1
2
3
4
5
6
7
8
9
10
local({
  saved_seed <- .Random.seed
  for(r in mh_scalar) {
    assign(".Random.seed",r$rng_before,envir=.GlobalEnv)
    again <- adaptive_random_walk(scalar_log,4001L,r$start,scale=r$proposal)
    stopifnot(identical(again$samples[-1L,,drop=FALSE],r$draws),
      identical(.Random.seed,r$rng_after))
  }
  assign(".Random.seed",saved_seed,envir=.GlobalEnv)
})

In the correlated normal example, separate coordinate moves spend proposals crossing a narrow conditional distribution while the joint density extends farther along a diagonal. Hamiltonian Monte Carlo uses gradients of the log density to construct a trajectory that can reach a more distant point. Its cost includes the gradient evaluations along that trajectory, so comparing it with a random walk requires accounting for that work. The adaptive random walk is translated from adaptMCMC, which Section 16.10 runs from the same streams for comparison.

16.6 Hamiltonian Monte Carlo, NUTS, and noncentered parameterizations

For two strongly correlated parameters, a small increase in the first may be quite plausible if the second increases with it. A random walk chooses its direction without using the gradient at the proposed position. Hamiltonian Monte Carlo (HMC) uses the gradient to change direction as the proposal moves.

Let $q$ collect the quantities to be sampled, expressed in unconstrained coordinates, and let $\pi(q)$ denote their posterior density with respect to those coordinates. For a positive variance $v$, for example, a position coordinate $u=\log v$ contributes $u$ to the log density through the Jacobian of $v=e^u$. A derivative taken after this transformation must include the derivative of that term.

Introduce a vector $r$ of the same dimension as $q$, independent of the position, with distribution $N(0,M)$. The positive definite matrix $M$ is the mass matrix. The momentum draw uses $M$, while its normal density uses $M^{-1}$. Multiplying the two densities and taking the negative logarithm gives the Hamiltonian, or energy, up to an additive constant,

\[H(q,r)=-\log\pi(q)+\tfrac12 r^\top M^{-1}r .\]

Integrating the joint density over $r$ recovers the desired posterior for $q$. This permits a proposal to move through a region of lower posterior density by exchanging kinetic energy, the quadratic term, for an increase in the first term.

At the beginning of a trajectory draw a fresh momentum. Two equations specify how position and momentum evolve during an artificial time interval. Use the derivative of the energy with respect to momentum for the rate of change of position, and the negative derivative with respect to position for the rate of change of momentum. Differentiating the quadratic and the negative log density gives

\[\dot q=\frac{\partial H}{\partial r}=M^{-1}r,\qquad \dot r=-\frac{\partial H}{\partial q}=\nabla\log\pi(q).\]

The second equation turns the momentum toward increasing density. Substitution of these rates in the chain rule for $dH/dt$ gives two inner products of opposite signs, so the exact motion conserves energy. A leapfrog step approximates that motion using only the gradient of the log density. For one leapfrog step of length $\epsilon$, the intermediate momentum, new position and final momentum are

\[r_{1/2}=r+\tfrac{\epsilon}{2}\nabla\log\pi(q),\qquad q'=q+\epsilon M^{-1}r_{1/2},\qquad r'=r_{1/2}+\tfrac{\epsilon}{2}\nabla\log\pi(q').\]

In code/lib/hamiltonian.R the argument p represents $r$. The example uses $M=I$, so the position increment is the intermediate momentum multiplied by the step size. The two evaluations of gradient() use opposite ends of the position step.

1
2
3
4
5
6
leapfrog <- function(q,p,epsilon,gradient) {
  # Each half momentum step uses the gradient of the log posterior density at its adjacent position.
  half <- p+epsilon*gradient(q)/2
  position <- q+epsilon*half
  list(q=position,p=half+epsilon*gradient(position)/2)
}

A large gradient at the new position can change the final momentum substantially. Using that new gradient is essential when taking the same trajectory in reverse.

Suppose a leapfrog step ends at $(q^{\prime},r^{\prime})$. Start there with momentum $-r^{\prime}$ and take another step of the same length. The first half step cancels the final momentum increment of the outward step and leaves $-r_{1/2}$. The full step then leads back to $q$, where the last half step produces $-r$. The same argument works in reverse order through any fixed number of steps.

Each component update also preserves volume. With position fixed, adding a function of position to momentum gives a triangular block Jacobian with identity matrices on its diagonal. The position update has the same property with the roles exchanged. The product therefore has determinant one.

A trajectory through a correlated normal density

For a concrete trajectory, let the target distribution of $q$ be bivariate normal with mean zero, unit marginal variances and correlation 0.8. If $R$ is its covariance, its log density is $-q^\top R^{-1}q/2$ up to a constant, with gradient $-R^{-1}q$. From the book directory, define this target and take ten steps from the specified position and momentum.

1
2
3
4
5
6
7
8
9
10
11
12
Rho <- matrix(c(1,.8,.8,1),2)
invR <- solve(Rho)
correlated <- list(value=function(q) -drop(crossprod(q,invR %*% q))/2,
                   gradient=function(q) -drop(invR %*% q))
trajectory <- function(q,p,epsilon,steps) {
  s <- list(q=q,p=p)
  for(i in seq_len(steps)) s <- leapfrog(s$q,s$p,epsilon,correlated$gradient)
  s
}
origin <- c(.4,-.2)
momentum <- c(.1,1)
trajectory(origin,momentum,.1,10L)

For the first step, half is approximately $(0.02222,1.07222)$ and the new position is $(0.40222,-0.09278)$. At time one the position is $(0.22936,0.91941)$ and the momentum is $(0.11048,0.59667)$. Retaining both endpoint values makes it possible to retrace the path and measure the energy change before deciding whether to record the new position.

A path computed in finite steps generally ends at a different energy. To correct for that difference, view the fixed-length proposal as a map taking the starting point to the endpoint with momentum reversed. Applying this map twice returns the starting pair, and momentum reversal has absolute Jacobian determinant one. The forward and reverse maps thus compare equal volumes, so the Metropolis ratio for the pair is the ratio of their joint densities. Writing $\Delta H$ for final minus initial energy, the acceptance probability for a finite proposal is $\min(1,\exp(-\Delta H))$. A lower energy gives acceptance with probability one. A higher energy gives a chance of staying at the current position even if the trajectory traveled far. This update for the bivariate normal draws independent standard normal momenta, tests the endpoint, and returns exactly one position per call.

1
2
3
4
5
6
7
8
9
10
hmc_move <- function(q,epsilon,steps) {
  p <- rnorm(length(q))
  energy <- function(q,p) -correlated$value(q)+sum(p^2)/2
  start <- energy(q,p)
  stopifnot(is.finite(start))
  end <- trajectory(q,p,epsilon,steps)
  proposed <- energy(end$q,-end$p)
  if (!is.finite(proposed)) return(q)
  if (log(runif(1)) < min(0,start-proposed)) end$q else q
}

Taking logs avoids exponentiating a large energy difference. The calculation starts at finite energy and explicitly retains the old position when the proposed energy is nonfinite. The leapfrog function itself returns the position and momentum. The surrounding sampler makes the acceptance decision. At the next iteration the sampler draws a new momentum whether the last proposal moved or stayed. A package’s divergence indicator describes numerical trouble along a trajectory and will be read from the separate transition record.

Reversibility and volume preservation can be checked before assessing sampling from the intended model. Fix the starting pair and total time, halve the step twice, and reverse each endpoint momentum. Then differentiate the ten-step map numerically in its four input coordinates.

1
2
3
4
5
6
7
print(do.call(rbind,lapply(c(.2,.1,.05),function(eps) {
  s <- trajectory(origin,momentum,eps,round(1/eps))
  back <- trajectory(s$q,-s$p,eps,round(1/eps))
  energy <- function(z,p) -correlated$value(z)+sum(p^2)/2
  data.frame(epsilon=eps,energy_change=energy(s$q,s$p)-energy(origin,momentum),
    reversibility=max(abs(c(back$q-origin,back$p+momentum))))
})))
1
2
3
4
  epsilon energy_change reversibility
1    0.20  0.0090526319  1.110223e-16
2    0.10  0.0020620912  1.249001e-16
3    0.05  0.0005032085  5.551115e-16
1
2
3
4
5
6
7
8
9
source("code/lib/differentiation.R")
trajectory_map <- function(x) {
  s <- trajectory(x[1:2],x[3:4],.1,10L)
  c(s$q,s$p)
}
initial_phase <- c(origin,momentum)
jac <- vapply(1:4,function(j)
  num_grad(function(u) trajectory_map(u)[j],initial_phase)$gradient,numeric(4))
print(c(trajectory_volume_multiplier=det(jac)))
1
2
trajectory_volume_multiplier 
                           1 

The energy changes fall from 0.00905 to 0.00206 and 0.00050, approximately a factor of four at each halving. The reversal errors are at most $5.6\times10^{-16}$ and the volume multiplier prints as one. A map with those properties could still follow the gradient of the wrong density.

The joint factor-model density

To apply HMC to the factor model, its target density must include the person factors. For BAYES4, include all 150 person factors in the sampled state alongside the eight population parameters. At a given factor the four responses are conditionally independent normals. The direct joint density multiplies their densities by the standard normal factor densities and the independent loading and variance priors. The default loading prior is the normal distribution with SD two, truncated to positive values for the first loading, and the inverse gamma shape and rate are two and one.

Set the population coordinates to the stored mode of the transformed marginal posterior and the factors to zero. The direct evaluation on the original scales needs one log first-loading term and four log variance terms to give the density at this 158-dimensional position. The function log_joint_bayes4() takes the parameters, the observations and the person factors on their original scales, and adds the log densities of the population parameters, person factors and conditional responses.

1
2
3
4
5
6
7
log_joint_bayes4 <- function(Y,loading,variance,z,prior) {
  lp <- log_prior_bayes4(loading,variance,prior)
  if(!is.finite(lp)) return(-Inf)
  E <- Y-outer(z,loading)
  lp+sum(dnorm(z,log=TRUE))-.5*(length(Y)*log(2*pi)+nrow(Y)*sum(log(variance))+
    sum(colSums(E^2)/variance))
}

In the code, E contains the residuals $y_{ij}-\lambda_jz_i$, so the last term is the sum of the normal log densities of the responses with variances $\psi_j$. Adding the coordinate Jacobian gives the direct value to compare with the joint target bayes4_target(Y,prior,TRUE,FALSE), which the samplers below use. As in Section 16.2, the same density written as a Stan program, code/model_programs/bayes4_joint.stan, gives an independent value and gradient at the same point. Then compare the gradients coordinate by coordinate.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
.libPaths(c(".R-library", .libPaths()))
source("code/lib/bayes_factor.R")
Y <- readRDS("data/source/ch16/BAYES4.rds")
prior <- bayes4_prior()
bayes4_data <- list(N=nrow(Y),J=ncol(Y),Y=Y,loading_sd=prior$loading_sd,
                    shape=prior$shape,rate=prior$rate)
program <- function(name) rstan::stan_model(
  file.path("code/model_programs",paste0(name,".stan")),model_name=name)
shell <- function(model,data) rstan::sampling(model,data=data,chains=0L)
joint_model <- program("bayes4_joint")
joint_shell <- shell(joint_model,bayes4_data)
joint <- bayes4_target(Y,prior,transformed=TRUE,marginal=FALSE)
mode <- readRDS("data/derived/ch16/analysis.rds")$laplace$par
q <- c(mode,rep(0,nrow(Y)))
a <- bayes4_unpack(q)
direct <- log_joint_bayes4(Y,a$loading,a$variance,a$z,prior)+q[1]+sum(log(a$variance))
print(c(joint_density_gap=joint$value(q)-direct,
        Stan_minus_book=rstan::log_prob(joint_shell,q)-joint$value(q),
        Stan_gradient_gap=max(abs(rstan::grad_log_prob(joint_shell,q)-
                                    joint$gradient(q)))))
1
2
joint_density_gap   Stan_minus_book Stan_gradient_gap 
    -4.547474e-13     -2.273737e-13      5.684342e-14 

In this order the signed log-density differences are $-4.55\times10^{-13}$ and $-2.27\times10^{-13}$. The greatest absolute gradient difference is $5.68\times10^{-14}$.

Centered and noncentered random effects

Before returning to the repeated-response model fitted earlier by Metropolis-within-Gibbs, consider how a change of coordinates represents its Gaussian random effects. Suppose a group effect $b$ has mean zero and positive definite covariance $LL^\top$ conditional on the population parameters, with $L$ its lower triangular Cholesky factor. In centered coordinates the sampler updates $b$ itself; “centered” here describes the parameterization, not subtraction of the sample mean from the responses. If a diagonal scale in $L$ becomes small, the conditional prior concentrates the corresponding combination of effects into a narrow interval. In noncentered coordinates the sampler updates $z$ and computes $b=Lz$ before evaluating the responses. To find the density in $z$, fix the covariance parameters and multiply the density in $b$ by the absolute determinant of the transformation. For an effect of dimension $h$,

\[p_b(Lz\mid L)\,|\det L| =(2\pi)^{-h/2}|\det L|^{-1} \exp\!\left(-\tfrac12 z^\top z\right)|\det L| =(2\pi)^{-h/2}\exp\!\left(-\tfrac12 z^\top z\right).\]

The target density in $z$ therefore uses a standard normal density for $z$ and evaluates the likelihood at $Lz$. The normalizing determinant in the centered prior and the transformation determinant have canceled. In a random-intercept model this amounts to writing $b_i=\sigma z_i$. If the sampler also represents the positive standard deviation by $u=\log\sigma$, the scale prior is still a density per unit of $\sigma$. Its transformation contributes $u$ to the log density per unit of $u$.

The cancellation for the group effects did not involve that separate derivative. A draw of a person’s random intercept on the response scale is obtained by multiplying the sampled $z_i$ by the scale from the same draw.

For the repeated-response example there is a known constant difference. There are $m$ group effects and $K$ observations per group. The Stan program code/model_programs/random_intercept.stan, used only for this comparison, includes $-\log(2\pi)/2$ for each of the $mK$ unit-variance normal responses and each of the $m$ normal group effects or standardized effects. The book’s target density includes their quadratic terms and the centered scale term but omits those normalizing constants. Both implementations include the same normalized coefficient and scale priors. Consequently the Stan value minus the book’s value is $-m(K+1)\log(2\pi)/2$ in either parameterization.

The program writes both parameterizations with a data flag noncentered. The model fixes the residual standard deviation at one. The coefficient priors have standard deviation two, and the positive scale has a half-t prior with four degrees of freedom and scale one. Read the saved design to evaluate both versions on exactly the same observations. The function centered_intercepts() fixes this design and the choice of parameterization, returning value(u) and gradient(u) for the log target and its derivative.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
centered_intercepts <- function(Y,x,noncentered) {
  m <- nrow(Y); k <- ncol(Y)
  evaluate <- function(u) {
    scale <- exp(u[3]); v <- u[3+seq_len(m)]
    if(!is.finite(scale)||scale<=0) return(list(value=-Inf,gradient=rep(NaN,length(u))))
    b <- if(noncentered) scale*v else v
    E <- sweep(Y-b,2,u[1]+u[2]*x)
    sq <- sum(v^2)
    latent <- if(noncentered) -.5*sq else -m*u[3]-.5*sq/scale^2
    # A half-t prior on the SD contributes its density and one log-SD Jacobian.
    prior_scale <- log(2)+dt(scale,df=4,log=TRUE)+u[3]
    row_score <- rowSums(E)
    value <- -.5*sum(E^2)+sum(dnorm(u[1:2],sd=2,log=TRUE))+latent+prior_scale
    g <- c(sum(E)-u[1]/4,sum(colSums(E)*x)-u[2]/4,
      1-5*scale^2/(4+scale^2)+if(noncentered) sum(b*row_score) else -m+sq/scale^2,
      if(noncentered) scale*row_score-v else row_score-v/scale^2)
    list(value=value,gradient=g)
  }
  list(value=function(u)evaluate(u)$value,gradient=function(u)evaluate(u)$gradient)
}

In the centered form v contains the deviations $b_i$, with density $N(0,\sigma^2)$; in the noncentered form $b_i=\sigma v_i$ with standard normal $v_i$, and scale is $\sigma$. E contains the unit-variance residuals; dnorm(u[1:2],sd=2,log=TRUE) and prior_scale are the coefficient and scale priors stated above, the latter with the log-SD Jacobian. The third gradient component differentiates the prior and, in each form, the terms in $\log\sigma$. In u, the two fixed coefficients come first, followed by the log SD and then the 20 effects. Those final coordinates are the response-scale effects when noncentered=FALSE and standardized effects when it is TRUE. Subtract two log densities within each implementation before comparing.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
source("code/lib/augment.R")
study_dir <- function(label) file.path("results/studies",paste0("ch16-",label))
ri_input <- readRDS(file.path(study_dir("RI-centered"),"design.rds"))$design$data
ri_model <- program("random_intercept")
u1 <- c(.9,.4,log(.3),seq(-.2,.2,length.out=20))
u2 <- c(1.1,.6,log(.5),rep(.1,20))
for (nc in 0:1) {
  ri_input$noncentered <- nc
  fit <- shell(ri_model,ri_input)
  target <- centered_intercepts(ri_input$Y,ri_input$x,nc==1L)
  change <- rstan::log_prob(fit,u1)-rstan::log_prob(fit,u2)
  print(c(noncentered=nc,difference_of_differences=
            change-(target$value(u1)-target$value(u2)),
          gradient_gap=max(abs(rstan::grad_log_prob(fit,u1)-target$gradient(u1)))))
}
1
2
3
4
              noncentered difference_of_differences              gradient_gap 
             0.000000e+00             -7.105427e-15              3.552714e-15 
              noncentered difference_of_differences              gradient_gap 
             1.000000e+00             -2.131628e-14              3.552714e-15 

The differences of differences are about $-7.1\times10^{-15}$ and $-2.1\times10^{-14}$, and the gradients at the first point agree to $3.6\times10^{-15}$. The two points check the implementation at those inputs. The density formulas explain why the omitted term remains constant elsewhere.

The No-U-Turn Sampler and its adaptation

A fixed integration time raises a practical question. If the path is still heading away from its start, a longer trajectory could reach another part of the posterior. Continuing after it turns back costs further gradient evaluations to revisit positions nearby. The No-U-Turn Sampler (NUTS) adjusts trajectory length during sampling. The function nuts_step() in code/lib/nuts.R follows the algorithm of Stan’s sampler. It extends a trajectory by successive doublings. At each doubling it chooses a direction at random and attempts to add a subtree of the corresponding length. It tests the momenta for a turn back along the path and can stop within the attempted extension.

Within a valid new subtree, candidate selection uses weights proportional to joint density. A separate decision replaces the current candidate with this subtree’s candidate with probability equal to the smaller of one and the total joint-density weight in the new subtree divided by the total weight of the existing path. Thus this implementation does not simply draw once from the final whole path in proportion to density. The end of the last extension need not be the draw.

The function nuts_subtree() builds a subtree of $2^d$ leapfrog steps by joining two subtrees of depth $d-1$. Each point receives the log weight start_energy - h, the negative change in energy, and the second half’s candidate replaces the first half’s with probability equal to its share of the total weight. The function no_u_turn() lets the trajectory continue only while the velocities at both ends have positive inner products with the summed momentum. Its three calls check the whole subtree and the two joins between its halves.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
no_u_turn <- function(velocity_back, velocity_front, momentum_sum)
  sum(velocity_front * momentum_sum) > 0 && sum(velocity_back * momentum_sum) > 0
nuts_subtree <- function(target, position, momentum, depth, epsilon, inverse_mass, start_energy, max_energy_error) {
  if (depth == 0L) {
    step <- hmc_leapfrog(target, position, momentum, epsilon, inverse_mass)
    h <- hmc_energy(step$position, step$momentum, inverse_mass)
    divergent <- h - start_energy > max_energy_error
    velocity <- inverse_mass * step$momentum
    return(list(valid = !divergent, divergent = divergent, position = step$position, momentum = step$momentum,
      candidate = step$position, candidate_momentum = step$momentum, log_weight = start_energy - h,
      steps = 1L, acceptance = if (start_energy - h > 0) 1 else exp(start_energy - h),
      momentum_sum = step$momentum, first_momentum = step$momentum, last_momentum = step$momentum,
      first_velocity = velocity, last_velocity = velocity))
  }
  first <- nuts_subtree(target, position, momentum, depth - 1L, epsilon, inverse_mass, start_energy, max_energy_error)
  if (!first$valid) return(first)
  second <- nuts_subtree(target, first$position, first$momentum, depth - 1L, epsilon, inverse_mass, start_energy,
    max_energy_error)
  steps <- first$steps + second$steps
  acceptance <- first$acceptance + second$acceptance
  if (!second$valid) return(list(valid = FALSE, divergent = second$divergent, steps = steps, acceptance = acceptance))
  log_weight <- log_add(first$log_weight, second$log_weight)
  take_second <- second$log_weight > log_weight || runif(1) < exp(second$log_weight - log_weight)
  momentum_sum <- first$momentum_sum + second$momentum_sum
  persist <- no_u_turn(first$first_velocity, second$last_velocity, momentum_sum) &&
    no_u_turn(first$first_velocity, second$first_velocity, first$momentum_sum + second$first_momentum) &&
    no_u_turn(first$last_velocity, second$last_velocity, second$momentum_sum + first$last_momentum)
  list(valid = persist, divergent = FALSE, position = second$position, momentum = second$momentum,
    candidate = if (take_second) second$candidate else first$candidate,
    candidate_momentum = if (take_second) second$candidate_momentum else first$candidate_momentum,
    log_weight = log_weight, steps = steps, acceptance = acceptance, momentum_sum = momentum_sum,
    first_momentum = first$first_momentum, last_momentum = second$last_momentum,
    first_velocity = first$first_velocity, last_velocity = second$last_velocity)
}

Inside nuts_subtree(), hmc_leapfrog() takes one step of leapfrog() above with the diagonal inverse mass matrix: the position moves by $\epsilon M^{-1}$ times the half-step momentum, and the returned position carries its log density and gradient. The function hmc_energy() returns minus the log density plus $p^\top M^{-1}p/2$, and log_add(a, b) returns $\log(e^a+e^b)$, subtracting the larger argument before exponentiating.

In nuts_step(), each doubling calls nuts_subtree() from the front or the back of the current trajectory, and the same three checks of no_u_turn() are applied to the doubled trajectory. The transition records its depth, its leapfrog steps and the average of $\min\lbrace 1,\exp(H_0-H)\rbrace $ over those steps, the acceptance statistic used in adaptation.

The integrator also checks for excessive increases in energy relative to the start. An increase beyond the divergence threshold $\Delta_{\max}$, set to 1,000 by max_energy_error, signals that the numerical trajectory has lost accuracy; the subtree is then invalid and the transition is recorded as divergent.

During warmup, dual averaging uses acceptance information to adjust the step size toward a specified acceptance probability; step_size_update() performs one update of the log step size. In windows of warmup iterations each chain also estimates a diagonal inverse mass matrix, $M^{-1}$, that adjusts the relative scales of the coordinate updates. For 1,000 warmup iterations, counted from zero, mass_windows() ends the windows at iterations 99, 149, 249, 449 and 949. Each estimate shrinks the sample variances toward $10^{-3}$, and the step size is then chosen afresh. The retained transitions use the final inverse mass matrix and the exponential of the averaged log step size.

1
2
3
4
5
6
7
8
9
10
11
step_size_update <- function(averaging, acceptance) {
  a <- averaging
  a$count <- a$count + 1
  weight <- 1 / (a$count + a$offset)
  a$mean_shortfall <- (1 - weight) * a$mean_shortfall + weight * (a$target_acceptance - min(1, acceptance))
  log_step <- a$center - a$mean_shortfall * sqrt(a$count) / a$regularization
  shrink <- a$count^(-a$decay)
  a$mean_log_step <- (1 - shrink) * a$mean_log_step + shrink * log_step
  a$epsilon <- exp(log_step)
  a
}

Here center is the log of ten times the initial step size, regularization is 0.05, decay is 0.75 and offset is 10.

The following function definitions supply the sampling calls for reproducing the worked examples. Defining them does not run the chains; the comparisons below read the saved results. Each uses four chains, with 1,000 iterations of warmup and 1,000 further iterations per chain. The random starts are uniform on $(-2,2)$ in each unconstrained coordinate. The function hamiltonian_chains() gives chain $k$ the $k$th of independent L’Ecuyer-CMRG streams derived from the seed, so one chain can be rerun alone. Both functions are in code/lib/nuts.R.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
hamiltonian_chains <- function(target, dimension, report, seed, chains = 4L, chain = seq_len(chains), ...) {
  RNGkind("L'Ecuyer-CMRG", "Inversion", "Rejection")
  set.seed(seed)
  streams <- replicate_streams(chains, .Random.seed)
  runs <- lapply(chain, function(k) {
    assign(".Random.seed", streams[[k]], envir = .GlobalEnv)
    hamiltonian_chain(target, dimension, report, ...)
  })
  names_out <- colnames(runs[[1]]$draws)
  draws <- array(NA_real_, c(nrow(runs[[1]]$draws), length(runs), length(names_out)),
    dimnames = list(NULL, paste0("chain", chain), names_out))
  for (k in seq_along(runs)) draws[, k, ] <- runs[[k]]$draws
  list(draws = draws, diagnostics = lapply(runs, `[[`, "diagnostics"), chains = runs, seed = seed, chain = chain)
}

The streams come from replicate_streams() (Section 15.5), and the draws of all chains are placed in an array with iterations, chains and reported quantities as its three dimensions. Each chain is run by hamiltonian_chain(), shown in two parts.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
hamiltonian_chain <- function(target, dimension, report, warmup = 1000L, retained = 1000L, method = "NUTS",
                      target_acceptance = .8, max_depth = 10L, integration_time = 2 * pi, keep_warmup = FALSE,
                      max_energy_error = 1000) {
  stopifnot(method %in% c("NUTS", "static"))
  current <- random_start(target, dimension)
  start <- current$u
  inverse_mass <- rep(1, dimension)
  epsilon <- 1
  path_steps <- max(1L, as.integer(integration_time / epsilon))
  epsilon <- initial_step_size(target, current, epsilon, inverse_mass)
  averaging <- step_size_averaging(epsilon, target_acceptance)
  windows <- mass_windows(warmup)
  moments <- list(n = 0, mean = numeric(dimension), squares = numeric(dimension))
  columns <- if (method == "NUTS") c("acceptance", "step_size", "tree_depth", "leapfrog_steps", "divergent", "energy") else
    c("acceptance", "step_size", "integration_time", "energy")
  total <- warmup + retained
  first <- report(current$u)
  values <- matrix(NA_real_, total, length(first) + 1L, dimnames = list(NULL, c(names(first), "log_density")))
  diagnostics <- matrix(NA_real_, total, length(columns), dimnames = list(NULL, columns))

The first part draws the start with random_start(), sets a unit inverse mass matrix, chooses the initial step size with initial_step_size() and the averaging state with step_size_averaging(), and obtains the warmup windows from mass_windows().

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
  for (iteration in seq_len(total)) {
    adapting <- iteration <= warmup
    # After warmup the step size is the average of the log step sizes (one when there is no warmup); the number of
    # static leapfrog steps is not reset.
    if (iteration == warmup + 1L) epsilon <- exp(averaging$mean_log_step)
    if (method == "NUTS") {
      move <- nuts_step(target, current, epsilon, inverse_mass, max_depth, max_energy_error)
      diagnostics[iteration, ] <- c(move$acceptance, epsilon, move$tree_depth, move$leapfrog_steps, move$divergent,
        move$energy)
    } else {
      move <- static_hmc_step(target, current, epsilon, inverse_mass, path_steps)
      diagnostics[iteration, ] <- c(move$acceptance, epsilon, integration_time, move$energy)
    }
    current <- move$position
    values[iteration, ] <- c(report(current$u), current$value)
    if (adapting) {
      averaging <- step_size_update(averaging, move$acceptance)
      epsilon <- averaging$epsilon
      if (method == "static") path_steps <- max(1L, as.integer(integration_time / epsilon))
      counter <- iteration - 1L
      if (counter %in% windows$collect) {
        moments$n <- moments$n + 1
        delta <- current$u - moments$mean
        moments$mean <- moments$mean + delta / moments$n
        moments$squares <- moments$squares + delta * (current$u - moments$mean)
      }
      if (counter %in% windows$finish) {
        variance <- if (moments$n > 1) moments$squares / (moments$n - 1) else inverse_mass
        inverse_mass <- moments$n / (moments$n + 5) * variance + 1e-3 * 5 / (moments$n + 5)
        if (!all(is.finite(inverse_mass))) stop("the inverse mass matrix overflowed during warmup")
        moments <- list(n = 0, mean = numeric(dimension), squares = numeric(dimension))
        epsilon <- initial_step_size(target, current, epsilon, inverse_mass)
        if (method == "static") path_steps <- max(1L, as.integer(integration_time / epsilon))
        averaging <- step_size_averaging(epsilon, target_acceptance)
      }
    }
  }
  if (retained == 0L) epsilon <- exp(averaging$mean_log_step)
  kept <- warmup + seq_len(retained)
  out <- list(start = start, draws = values[kept, , drop = FALSE], diagnostics = diagnostics[kept, , drop = FALSE],
    step_size = epsilon, inverse_mass = inverse_mass, method = method, target_acceptance = target_acceptance,
    max_depth = max_depth, integration_time = integration_time, path_steps = if (method == "static") path_steps)
  if (keep_warmup) {
    out$warmup_draws <- values[seq_len(warmup), , drop = FALSE]
    out$warmup_diagnostics <- diagnostics[seq_len(warmup), , drop = FALSE]
  }
  out
}

Each iteration takes one transition with nuts_step() or, for static HMC, static_hmc_step() with the number of leapfrog steps set by the integration time, and stores the reported quantities and the transition record. The warmup adaptation described above appears in the code as step_size_update() at every warmup iteration, the running mean and sum of squared deviations of the position at the iterations listed in windows$collect, and the new inverse mass and step size at the end of each window. The warmup draws are returned as well only when keep_warmup is true.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
source("code/lib/boundary_test.R")
source("code/lib/nuts.R")
sample_model <- function(target,dimension,report,seed,...) {
  fit <- hamiltonian_chains(target,dimension,report,seed,chains=4L,warmup=1000L,retained=1000L,...)
  list(draws=fit$draws,diagnostics=fit$diagnostics)
}
normal_report <- function(u) setNames(u,c("q[1]","q[2]"))
fit_normal <- function() sample_model(correlated,2L,normal_report,101606)
fit_static <- function() sample_model(correlated,2L,normal_report,101616,method="static")
fit_factor <- function(target_acceptance=.8) sample_model(joint,length(q),bayes4_report,101626,
                                                          target_acceptance=target_acceptance)
ri_report <- function(noncentered) function(u)
  setNames(c(u[1:2],exp(u[3]),if(noncentered) exp(u[3])*u[-(1:3)] else u[-(1:3)]),
    c("beta[1]","beta[2]","sd_b",paste0("b[",seq_len(length(u)-3L),"]")))
fit_intercepts <- function(nc) sample_model(centered_intercepts(ri_input$Y,ri_input$x,nc==1L),
  3L+nrow(ri_input$Y),ri_report(nc==1L),if (nc==1L) 101646 else 101636)

The function sample_model() returns draws as an iteration-by-chain-by-quantity array and diagnostics as a list of transition-diagnostic matrices, one per chain. Both contain retained iterations only. The report functions name the stored quantities; the last column of draws, log_density, is the log density in sampling coordinates.

For the normal example, fit_normal() uses the default target acceptance probability of 0.8 and maximum tree depth ten. fit_static() uses the same normal target with an integration time of $2\pi$ during warmup and an adapted step size and diagonal metric. Its number of leapfrog steps, $2\pi$ divided by the step size and rounded down, is fixed at its value at the last warmup iteration. The seeds are 101606 and 101616. Both settings of fit_factor() use 101626. The centered and noncentered intercept fits use 101636 and 101646, respectively. The saved draws preserve a chain index, and the corresponding diagnostics preserve the amount of integration work for each retained draw.

Trajectory lengths and draws for the normal target

How much integration took place to obtain one draw? In a NUTS record, tree_depth reports the number of completed doublings and leapfrog_steps counts the steps actually taken in that transition, including those of a rejected final extension. Given reported depth $d$, the count therefore satisfies $2^d-1\leq n\leq 2^{d+1}-1$. It exceeds $2^d-1$ exactly when the last attempted extension was rejected, by a turn within it or by a divergence. The table labels equality with the lower count as complete; this is a step count, not a convergence flag. Read the saved records and tabulate the joint factor fit at its default target acceptance probability.

1
2
3
4
5
6
7
8
9
10
11
12
13
read_run <- function(label,id=1L) {
  readRDS(file.path(study_dir(label),sprintf("id-%06d.rds",id)))
}
normal <- read_run("NUTS-normal")
static <- read_run("HMC-normal")
nuts <- readRDS("data/derived/ch16/joint-nuts-chains.rds")
factor_run <- nuts$NUTS_080
ri <- list(centered=read_run("RI-centered"),noncentered=read_run("RI-noncentered"))
s <- do.call(rbind,factor_run$diagnostics)
depth <- s[,"tree_depth"]
steps <- s[,"leapfrog_steps"]
stopifnot(all(steps >= 2^depth-1 & steps <= 2^(depth+1)-1))
print(table(depth=depth,complete=steps==2^depth-1))
1
2
3
4
     complete
depth FALSE TRUE
    3     1    1
    4     5 3993

Of 4,000 transitions, 3,998 have depth four. In 3,993 of them the count is exactly 15. The other five took more steps at the same reported depth. Count divergent transitions separately and check how often the reported depth reached ten. To measure cost, sum the leapfrog counts over the 1,000 post-warmup transitions of each chain. To measure precision per unit of work, calculate bulk effective sample size (ESS) for one named parameter from the iteration-by-chain matrix, then divide by the sum of those counts across all four chains.

1
2
3
4
5
6
7
8
9
10
11
source("code/lib/posterior_checks.R")
cost <- function(record) {
  t(vapply(record$diagnostics,function(s) c(step_size=s[1,"step_size"],
    divergences=sum(s[,"divergent"]),depth_hits=sum(s[,"tree_depth"]>=10),
    retained_leapfrog_steps=sum(s[,"leapfrog_steps"])),numeric(4)))
}
efficiency <- function(record,parameter) {
  draws <- record$draws[,,parameter]
  bulk <- bulk_ess(draws)
  c(bulk_ESS=bulk,per_step=bulk/sum(cost(record)[,"retained_leapfrog_steps"]))
}

Every parameter in one fit has the same denominator. Its numerator can differ because the successive draws of one parameter may be more dependent than those of another. This ratio measures efficiency per recorded integration step. Timing comparisons would also need the cost of evaluating the gradient in each model. The denominator excludes warmup. In hmc_leapfrog() each step evaluates the log density and its gradient once, at the new position; the gradient at the start of a step comes from the previous step.

The normal example has known second moments against which to compare the draws on their original scale. Pool the two columns across the four chains to estimate a covariance matrix for each method. For static HMC, difference successive positions within each chain separately. Each difference then refers to successive observations of one chain.

1
2
3
4
5
6
7
positions <- function(record) lapply(1:4,function(k)
  record$draws[,k,c("q[1]","q[2]")])
print(cov(do.call(rbind,positions(normal))))
print(cov(do.call(rbind,positions(static))))
print(vapply(positions(static),function(q) mean(rowSums(abs(diff(q)))>0),0.0))
cost(normal)
sapply(c("q[1]","q[2]"),function(p) efficiency(normal,p))
MethodVariance of first coordinateCovarianceVariance of second coordinate
Target distribution1.00000.80001.0000
NUTS1.01060.82621.0243
Static HMC1.14090.93021.1105

Both sample covariances are positive. The NUTS sample covariance is 0.026 above the target covariance and the static estimate is 0.130 above it. To judge the discrepancies against simulation error would require MCSEs for these variance and covariance estimates. The MCSE of a coordinate mean answers a different question.

NUTS step sizes range from 0.438 to 0.522, with zero divergences and 5,054 to 6,652 recorded steps per chain. The two bulk ESS values, 1,156 and 1,125, give 0.050 and 0.049 effective draws per recorded step. For static HMC the fraction of adjacent pairs whose position changed ranges from 0.926 to 0.958 across chains. There are 999 such pairs among 1,000 retained positions. The sampler records also include the transition into the first retained position, so the cost calculation has 1,000 transitions per chain.

NUTS and Gibbs on the joint factor model

For a loading or a unique variance the corresponding population moment of the posterior is unknown. A Gibbs fit to the same joint factor model provides a comparison. Both methods sample the person factors and report loadings and variances on their original scales. Preserve the iteration order within each chain when calculating Monte Carlo standard errors. The two fits use independent random streams, so the variance of the difference between their estimated means is the sum of the two Monte Carlo variances. The following comparison, also in code/practice/16.6.R, uses one column per chain and matches parameters.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
gibbs <- readRDS("data/derived/ch16/factor-gibbs-chains.rds")
parameters <- dimnames(factor_run$draws)[[3]]
methods <- lapply(nuts,function(record) lapply(1:4,function(k) record$draws[,k,]))
methods$Gibbs <- lapply(gibbs,function(x) {colnames(x) <- parameters; x})
summarize <- function(chains,p) {
  x <- do.call(cbind,lapply(chains,function(c) c[,p]))
  chain_summary(x)
}
compare <- function(p) {
  g <- summarize(methods$Gibbs,p)
  n <- summarize(methods$NUTS_080,p)
  se <- sqrt(n["MCSE"]^2+g["MCSE"]^2)
  c(Gibbs=unname(g["mean"]),NUTS=unname(n["mean"]),Gibbs_MCSE=unname(g["MCSE"]),
    NUTS_MCSE=unname(n["MCSE"]),difference_in_MCSE=unname((n["mean"]-g["mean"])/se))
}
t(vapply(parameters[1:8],compare,numeric(5)))
cost(factor_run)
vapply(parameters,function(p) efficiency(factor_run,p)[1],0.0)

At the default target acceptance probability of 0.8, chains two and four spend all their retained iterations in a different region from chains one and three and from every Gibbs chain. Their mean first loadings are 0.00993 and 0.00976, against 0.78076 and 0.78125 in chains one and three, and their third loadings are negative. Pooled over the four chains, the first loading has $\widehat R=1.7334$ and bulk ESS 6.1, so the pooled NUTS mean of 0.39542 is not an estimate of the posterior mean to set beside the Gibbs estimate of 0.78006. The second unique variance takes similar values in both regions: its NUTS mean is 0.54647 with MCSE 0.00103 and its Gibbs mean is 0.54636 with MCSE 0.00031, a difference of 0.10 combined MCSEs. Agreement for one coordinate does not establish agreement for the others. The chain step sizes lie between 0.277 and 0.324. Each chain records about 15,000 leapfrog steps and zero divergences.

How does the behavior of the four chains change at a higher target acceptance probability? The second setting is reproduced by fit_factor(.95), with the observations and seed fixed. Inspect the two saved retained arrays in nuts. The target_acceptance_probability column of results/completion/16.6-trajectories.csv records the requested setting. To learn where each chain spent these iterations, put its mean loading beside its sign count, proportion negative and range. Select the fourth chain directly from the array to recover its complete path.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
chain_means <- do.call(rbind,lapply(names(methods),function(m)
  do.call(rbind,lapply(seq_along(methods[[m]]),function(k)
    data.frame(method=m,chain=k,t(colMeans(methods[[m]][[k]])),check.names=FALSE)))))
by_chain <- do.call(rbind,lapply(names(nuts),function(m) {
  a <- nuts[[m]]$draws[,,"loading[3]"]
  n <- colSums(a<0)
  data.frame(method=m,chain=1:4,cost(nuts[[m]]),negative_third_loading=n,
             proportion_negative=n/nrow(a),minimum=apply(a,2,min),maximum=apply(a,2,max))
}))
show <- c("method","chain","loading[1]","loading[3]")
merge(by_chain,chain_means[,show],by=c("method","chain"))
chain4 <- nuts$NUTS_095$draws[,4,"loading[3]"]
c(negative=sum(chain4<0),range(chain4))
stopifnot(all(nuts$NUTS_095$draws[,,"loading[1]"]>0))
summarize(methods$NUTS_095,"loading[1]")[c("Rhat","ESS_bulk")]
Target acceptance probabilityChainMean loading 3Negative drawsProportion negativeMinimumMaximum
0.8010.9481000.772821.14981
0.802−0.92321,0001−1.20870−0.69639
0.8030.9429000.720641.25976
0.804−0.92101,0001−1.18474−0.64527
0.9510.9392000.713171.16844
0.9520.9389000.697791.18050
0.9530.9470000.735311.17133
0.954−0.91471,0001−1.17488−0.66023

At 0.95 the step sizes range from 0.153 to 0.213 and the leapfrog totals from 19,640 to 30,984 per chain. At both settings the divergence and depth-limit counts are zero in all four chains.

At 0.95 all 1,000 draws of the third loading in chain four are negative, as in chains two and four at 0.8. Every draw in the other chains is positive. The first loading remains positive in every draw. At 0.95 its mean is 0.01023 in chain four and ranges from 0.7798 to 0.7835 in the other chains. The sign constraint allows a very small positive first loading alongside a negative third loading. For the first loading, the four-chain $\widehat R$ is 1.5315 and bulk ESS is only 7.2; at 0.8 they are 1.7334 and 6.1. An average over the four chains would weight the regions according to how many chains remained in each. These paths give no basis for using those weights as posterior probabilities, so a pooled estimate is withheld for both runs. The negative third loading is not obtained by reversing all loadings together: the first loading remains positive. The orientation constraint therefore does not remove this sampling difficulty.

A separate density calculation can test whether the book’s target and the Stan program evaluate the same model at specified inputs. At index $k=1,2,3,4$, multiply the loading vector $(0.3,0.5,0.7,0.9)$ by $0.4+k/2$, use $0.2k$ for each variance, and set every factor to zero. Join the stored comparisons to a fresh evaluation at each point.

1
2
3
4
5
6
7
8
parameter_points <- read.csv("data/derived/ch16/joint-density-checks.csv")
computed <- do.call(rbind,lapply(parameter_points$parameter_point,function(k) {
  q <- bayes4_coordinates(c(.3,.5,.7,.9)*(.4+k/2),rep(.2*k,4),rep(0,nrow(Y)))
  numerical_log_posterior_gradient <- num_grad(joint$value,q)$gradient
  data.frame(parameter_point=k,log_density=joint$value(q),
             max_gradient_difference=max(abs(joint$gradient(q)-numerical_log_posterior_gradient)))
}))
merge(parameter_points,computed,by="parameter_point",suffixes=c("_stored","_computed"))
PointStored log densityRecomputed log densityMaximum R gradient difference from numerical derivativesCompiled minus R log densityMaximum compiled versus R gradient difference
1−1658.7293−1658.7293$2.72\times10^{-8}$$-4.55\times10^{-13}$$1.71\times10^{-13}$
2−1143.0117−1143.0117$2.16\times10^{-8}$$-4.55\times10^{-13}$$8.53\times10^{-14}$
3−1024.9275−1024.9275$3.67\times10^{-8}$0$5.68\times10^{-14}$
4−992.2406−992.2406$6.30\times10^{-8}$$-1.14\times10^{-13}$$4.26\times10^{-14}$

The last two columns come from the stored evaluations of both programs. The R evaluations and numerical derivative checks use the constructed inputs identified by parameter_point. Agreement of the log densities within $4.55\times10^{-13}$ at these points answers a question about implementation. It supplies no evidence about the time a chain should spend in either region.

Centered and noncentered fits to the repeated responses

Return now to the repeated-response study and compare its centered and noncentered sampling results. It measures the same response on three occasions for each of 20 people. An individual intercept shifts all three measurements together. To examine how much these observations reveal about heterogeneity, generate the data with occasion covariates $-1,0,1$, fixed intercept one, fixed slope 0.5 and between-person SD 0.15. Draw one intercept per person and an independent normal error with SD one for every measurement. The following code reconstructs the observed response matrix used in both fits.

1
2
3
4
5
RNGkind("Mersenne-Twister","Inversion","Rejection")
set.seed(1606)
x <- c(-1,0,1); b <- rnorm(20,sd=.15)
Yweak <- matrix(rep(1+.5*x,each=20),20)+b+matrix(rnorm(60),20)
stopifnot(identical(Yweak,ri_input$Y),identical(x,ri_input$x))

The 20 rows are independent people and the three columns are repeated observations. Fit the model with residual SD fixed at one, independent $N(0,4)$ priors on the two fixed coefficients, and a half Student $t$ prior with four degrees of freedom and scale one on the between-person SD. The generating SD is known in this simulation but is treated as unknown when fitting. For given fixed coefficients, averaging one person’s three residuals gives an estimate of that person’s random intercept with conditional error SD $1/\sqrt{3}$, appreciably larger than 0.15. This comparison explains why the individual records give limited information about the effects.

In the centered form their prior spread varies with $\sigma$. In the noncentered form each standardized effect has unit prior spread, while its contribution to all three fitted responses is multiplied by $\sigma$.

Which representation estimates the between-person SD more efficiently on these data? Obtain a numerical reference by integrating the normal group effects and the two normal fixed coefficients analytically. Conditional on $\sigma$ and the fixed coefficients, one person’s response vector has covariance $I_K+\sigma^2\mathbf1\mathbf1^\top$. Its determinant is $1+K\sigma^2$ and its inverse is $W=I_K-s\mathbf1\mathbf1^\top$, where $s=\sigma^2/(1+K\sigma^2)$. For the common design $X$ with columns one and occasion, the conditional posterior precision of the coefficients is $A=mX^\top W X+I_2/4$. Its mean is $A^{-1}h$ with $h=X^\top W\sum_i y_i$. Completing the square adds $h^\top A^{-1}h/2-\log\vert A\vert /2$ to the log weight.

Evaluate the weights on an equally spaced SD grid from 0.0001 to 6 by 0.0001, multiply by the half-$t$ density, and normalize. The grid spacing cancels from these ratios. This finite grid omits values below 0.0001 and above 6. Refining its spacing and endpoints is necessary to assess numerical integration error.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
grid <- seq(1e-4,6,by=1e-4)
X <- cbind(1,x)
m <- nrow(Yweak)
k <- ncol(Yweak)
total <- colSums(Yweak)
terms <- t(vapply(grid,function(tau) {
  s <- tau^2/(1+k*tau^2)
  W <- diag(k)-s
  A <- m*crossprod(X,W %*% X)+diag(2)/4
  h <- drop(crossprod(X,W %*% total))
  beta <- solve(A,h)
  Q <- sum(Yweak^2)-s*sum(rowSums(Yweak)^2)
  log_weight <- -m*log1p(k*tau^2)/2-Q/2+sum(h*beta)/2-
    as.numeric(determinant(A)$modulus)/2+log(2)+dt(tau,df=4,log=TRUE)
  c(log_weight,beta)
},numeric(3)))
w <- exp(terms[,1]-max(terms[,1]))
w <- w/sum(w)
sd_mean <- sum(w*grid)
c(beta0=sum(w*terms[,2]),beta1=sum(w*terms[,3]),SD=sd_mean,
  SD_posterior_SD=sqrt(sum(w*(grid-sd_mean)^2)))

The quadratic Q sums $y_i^\top W y_i$ over people. The weighted coefficient means and SD summaries provide the numerical reference. Now read the within-Gibbs draws and compare them with the saved centered and noncentered fits, preserving one column per chain for each summary.

1
2
3
4
5
6
7
8
9
10
within <- lapply(1:4,function(i) read_run("RI-within-Gibbs",i)$draws)
sd_table <- function(j) {
  p <- c("beta[1]","beta[2]","sd_b")[j]
  s <- lapply(ri,function(r) chain_summary(r$draws[,,p]))
  s$within_Gibbs <- chain_summary(do.call(cbind,lapply(within,function(a) a[,j])))
  t(vapply(s,function(x) x[c("mean","MCSE")],numeric(2)))
}
lapply(1:3,sd_table)
lapply(ri,cost)
lapply(ri,function(r) efficiency(r,"sd_b"))
QuantityGrid meanCentered mean (MCSE)Noncentered mean (MCSE)Within-Gibbs mean (MCSE)
Fixed intercept1.194411.19388 (0.00314)1.19566 (0.00311)1.19562 (0.00208)
Occasion slope0.618870.61643 (0.00260)0.61836 (0.00229)0.61977 (0.00126)
Between-person SD0.398260.42610 (0.01266)0.38845 (0.00676)0.42617 (0.01280)

For each fixed coefficient, all three estimates differ from the grid mean by less than their own MCSE. For the SD, the absolute differences are about 2.2, 1.5 and 2.2 MCSEs for centered, noncentered and within-Gibbs sampling.

The grid gives a posterior SD of 0.20741 for $\sigma$ itself. This measures uncertainty about the population scale given the observations, whereas each MCSE measures simulation uncertainty in the corresponding estimated mean.

Neither NUTS run diverged or reached the depth limit. For $\sigma$ the centered fit gave bulk ESS 214, or 0.0022 per recorded leapfrog step, compared with 927 and 0.0161 for the noncentered fit.

With little information per person, standardization removes the prior dependence of the sampled effects on the scale. Here the resulting fit estimated the scale more precisely per integration step. When repeated measurements determine each $b_i$ precisely, the likelihood can instead tie $z_i$ closely to $\sigma$ through their product. The relative efficiency depends on that information and on the quantity being estimated. The supplied nuts_step() and static_hmc_step() are translated from the samplers of Stan (code/NOTICE.md); in R, rstan provides HMC and NUTS.

16.7 Discrete latent variables, label switching, and marginalization

The first person in the simulated LCA6 data has ones on the first three items and zeros on the last three. Which response profile might this person share with other respondents? Let $C_i$ be the unobserved class of person $i$, with $\Pr(C_i=c)=\pi_c$ for $c=1,2,3$. The six dichotomous responses $Y_{ij}$ are independent conditional on that person’s class, and $p_{jc}$ is the probability of a yes on item $j$ in class $c$. The 600 people’s class draws are independent given $\pi$, and each person supplies one six-item response pattern. From the book directory, read the response matrix and inspect the first row.

1
2
3
4
5
.libPaths(c(".R-library", .libPaths()))
source("code/lib/stability.R")
source("code/lib/mixtures.R")
Y <- readRDS("data/source/ch12/LCA6.rds")
Y[1,]

For this person, the probability of the observed pattern given class $c$ is $p_{1c}p_{2c}p_{3c}(1-p_{4c})(1-p_{5c})(1-p_{6c})$. Denote that conditional probability for any row by $f_c(y_i)$. Give the three proportions a $\operatorname{Dirichlet}(1,1,1)$ prior and the 18 item probabilities independent $\operatorname{Beta}(1,1)$ priors, independent also of the proportions. These priors make no distinction among the three class numbers. A question about the probability of a response pattern will therefore be easier to interpret across draws than a question about a particular numbered column.

Given the current proportions and item probabilities, the joint probability of class $c$ and row $y_i$ is $\pi_c f_c(y_i)$. Divide by the sum over the three classes to obtain $w_{ic}=\Pr(C_i=c\mid y_i,\pi,P)$, where $P=(p_{jc})$. Draw one class per person from these categorical probabilities. If $n_c$ people receive label $c$ and $s_{jc}$ of them answer yes on item $j$, the complete-data likelihood contains the factors $\pi_c^{n_c}$ and $p_{jc}^{s_{jc}}(1-p_{jc})^{n_c-s_{jc}}$. Multiplication by the priors gives the two remaining updates in a Gibbs sweep,

\[\pi\mid C,Y\sim\operatorname{Dirichlet}(1+n_1,1+n_2,1+n_3),\qquad p_{jc}\mid C,Y\sim\operatorname{Beta}(1+s_{jc},1+n_c-s_{jc}).\]

The following sweep draws the allocations, then the proportions and item probabilities conditional on those allocations. An empty class has zero counts and its item probabilities are drawn from their prior.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
gibbs_lca_step <- function(Y,state) {
  k <- length(state$mass)
  w <- mixture_posterior(lca_log_emission(Y,state$probability),state$mass)$posterior
  cumulative <- w
  for (j in seq_len(k-1L)) cumulative[,j+1L] <- cumulative[,j]+w[,j+1L]
  allocation <- 1L+rowSums(runif(nrow(Y))>cumulative[,-k,drop=FALSE])
  counts <- tabulate(allocation,k)
  v <- rgamma(k,1+counts)
  P <- matrix(0,ncol(Y),k)
  for(c in seq_len(k)) {
    successes <- colSums(Y[allocation==c,,drop=FALSE])
    P[,c] <- rbeta(ncol(Y),1+successes,1+counts[c]-successes)
  }
  list(state=list(mass=v/sum(v),probability=P,allocation=allocation))
}

The allocation step compares one uniform variate per person with the first two cumulative probabilities in that person’s row. For the proportions, independent gamma draws with the indicated shapes and a common rate of one have a Dirichlet distribution after division by their sum.

To see the categorical update on an observed row, evaluate these class probabilities at the final state of the first saved allocation chain. Its proportions and item probabilities supply the inputs for a possible next sweep.

1
2
3
4
5
source("code/lib/posterior_checks.R")
lca <- readRDS("data/derived/ch16/latent-class-posterior-chains.rds")
state <- lca$terminal_state
w <- mixture_posterior(lca_log_emission(Y,state$probability),state$mass)$posterior
w[1,]

The first respondent’s probabilities are approximately 0.99698, 0.00167 and 0.00134. The label attached to the largest of these numbers refers to the columns in this particular state.

Label switching and alignment

Permuting the class proportions and the columns of $P$ together only changes the order of the three terms in each person’s marginal probability. The prior density is also unchanged. Consequently every labeling has a counterpart with the same posterior density under each of the six permutations. If different chains use different labels for the same response profile, a pooled mean for raw_item1_class1 averages probabilities for different profiles.

For the aligned summaries, the reference assigns each person to the most probable class at the stored three-class likelihood fit. The equivalence classes representatives (ECR) method then chooses, separately for each retained draw, the permutation that maximizes agreement with those reference allocations. The aligned_item1_class1 column reports the first-item success probability in the class matched to reference class one. The item1_success column instead sums $\pi_c p_{1c}$ over classes for a new person.

The exercise in code/practice/16.7.R reads four chain matrices for each method from lca$draws. For a given quantity, bind the four columns of draws side by side to preserve the information about which draws came from the same chain.

1
2
3
4
5
6
7
8
9
10
11
summaries <- lapply(lca$draws,function(chains) {
  t(vapply(colnames(chains[[1]]),function(parameter) {
    x <- do.call(cbind,lapply(chains,function(draws) draws[,parameter]))
    chain_summary(x)
  },c(mean=0,sd=0,Rhat=0,ESS_bulk=0,ESS_tail=0,MCSE=0)))
})
by_chain <- vapply(lca$draws$allocation,function(x)
  colMeans(x[,c("raw_item1_class1","aligned_item1_class1")]),numeric(2))
print(by_chain)
summaries$allocation[c("raw_item1_class1","aligned_item1_class1","item1_success"),
                     c("mean","Rhat","ESS_bulk")]
Item 1 probability in the allocation samplerSample mean$\widehat R$Bulk ESS
Class numbered 1 in each raw draw0.68781.52817.1
Class matched to reference class 10.87091.00022,879.8
New person’s success, summed over classes0.65010.999916,284.0

The raw class-one mean is 0.1388 in chain two and lies between 0.8703 and 0.8715 in the other three. Their pooled value, 0.6878, describes none of these chains well. Once labels are matched, the corresponding mean in chain two is 0.8710. The last row answers a different question directly from $\sum_c\pi_c p_{1c}$ at each draw. A new person’s class is unknown, and the probability of success on item one uses all three classes even when the labels are well aligned.

Construct the reference allocation from the stored three-class likelihood fit by assigning each person to the class with the largest posterior membership probability. Row two of each fitted item table contains its success probabilities. The resulting vector zpivot contains one class number per person.

1
2
3
4
ml <- readRDS("data/derived/ch12/fits.rds")$lca$model
P_ml <- do.call(rbind,lapply(ml$probability,function(p) p[2,]))
w_ml <- mixture_posterior(lca_log_emission(Y,P_ml),ml$mass)$posterior
zpivot <- max.col(w_ml,ties.method="first")

ECR needs each draw’s allocation history to compare with this reference before the draw can be reduced to the reported probabilities. The four Gibbs chains use independent streams from seed 101607. Each starts with equal proportions and independent item probabilities uniform between 0.2 and 0.8. Each row retained after warmup contains three proportions, 18 item probabilities in column order, and 600 allocations.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
source("code/lib/boundary_test.R")
RNGkind("L'Ecuyer-CMRG","Inversion","Rejection")
set.seed(101607)
streams <- replicate_streams(4L,.Random.seed)
allocation_history <- function(chain) {
  assign(".Random.seed",streams[[chain]],envir=.GlobalEnv)
  s <- list(mass=rep(1/3,3),probability=matrix(runif(18,.2,.8),6))
  for (i in seq_len(2000L)) s <- gibbs_lca_step(Y,s)$state
  history <- matrix(NA_real_,4000L,21L+nrow(Y))
  for (i in seq_len(nrow(history))) {
    s <- gibbs_lca_step(Y,s)$state
    history[i,] <- c(s$mass,s$probability,s$allocation)
  }
  history
}

The function align_chain() applies ECR to a complete allocation history and extracts the aligned first-item probability. The ECR step, ecr_permutations() in code/lib/latent_class_posterior.R, compares all six permutations of each draw’s labels with the reference allocation and takes the first, in lexicographic order, with the largest agreement. It is translated from label.switching, which solves the same assignment problem by linear programming (code/NOTICE.md).

1
2
3
4
5
6
7
8
9
10
11
12
ecr_permutations <- function(pivot, allocations, K) {
  permutations <- as.matrix(expand.grid(rep(list(seq_len(K)), K)))[, K:1, drop = FALSE]
  permutations <- permutations[apply(permutations, 1, function(p) !anyDuplicated(p)), , drop = FALSE]
  out <- matrix(NA_integer_, nrow(allocations), K)
  for (s in seq_len(nrow(allocations))) {
    agree <- matrix(tabulate(allocations[s, ] + K * (pivot - 1L), K * K), K, K)
    cost <- rowSums(agree) - agree
    totals <- vapply(seq_len(nrow(permutations)), function(r) sum(cost[cbind(seq_len(K), permutations[r, ])]), 0)
    out[s, ] <- order(permutations[which.min(totals), ])
  }
  out
}

The matrix permutations lists the six orderings of the labels 1, 2 and 3 in lexicographic order. For draw $s$, entry $(k,l)$ of agree counts the people placed in class $k$ by the draw and in class $l$ by the reference allocation pivot, and cost counts the people in draw class $k$ outside reference class $l$. The permutation with the smallest total cost, the first one in case of a tie, has the largest agreement. The returned row is its inverse, order() of the permutation: entry $l$ names the draw’s label that corresponds to reference class $l$.

Here the frequency tables are read from the saved fits. The shorter exercise object stores the summaries and one terminal state.

1
2
3
4
5
6
7
8
9
10
11
12
align_chain <- function(chain) {
  history <- allocation_history(chain)
  slots <- seq_len(21L)
  ecr <- ecr_permutations(zpivot,history[,-slots,drop=FALSE],3L)
  p1 <- history[cbind(seq_len(nrow(history)),3L+6L*(ecr[,1]-1L)+1L)]
  list(aligned_item1_class1=p1,permutations=table(apply(ecr,1,paste,collapse="")))
}
read_chain <- function(label,i) {
  readRDS(file.path("results/studies",paste0("ch16-",label),sprintf("id-%06d.rds",i)))
}
permutations <- lapply(1:4,function(i) read_chain("LCA-alloc",i)$permutations)
print(permutations)
Allocation chainOld labels in aligned orderRetained draws with this permutation
1$(1,3,2)$4,000
2$(2,3,1)$4,000
3$(1,2,3)$4,000
4$(1,3,2)$4,000

In align_chain(), ecr[,1] identifies the old column to put first for each draw. The item probabilities start after the three proportions, with six entries per class.

Within each chain the best permutation was constant throughout the retained draws. In chain two the old second column supplies the aligned first column, which accounts for the change in its item mean.

To see how all quantities transform together, deliberately place the old columns in the order $(3,1,2)$ in one terminal state. Proportions and probabilities move with their column. An old allocation of one now points to column two, which match() finds by looking up the old label in the new order.

1
2
3
4
5
6
7
8
9
state <- lca$terminal_state
order <- c(3L,1L,2L)
relabeled <- list(mass=state$mass[order],probability=state$probability[,order],
                  allocation=match(state$allocation,order))
all_six <- function(s) sum(s$mass*apply(s$probability,2,prod))
print(list(first_six_before=state$allocation[1:6],
           first_six_after=relabeled$allocation[1:6],
           probability_all_six=c(before=all_six(state),after=all_six(relabeled)),
           restored_allocations=sum(order[relabeled$allocation]==state$allocation)))
1
2
3
4
5
6
7
8
9
10
11
12
$first_six_before
[1] 1 2 1 1 1 2

$first_six_after
[1] 2 3 2 2 2 3

$probability_all_six
   before     after 
0.1190082 0.1190082 

$restored_allocations
[1] 600

The first six class assignments change, yet the probability of all six successes at these parameters is 0.1190082 under either labeling. Applying the inverse change recovers the allocations of all 600 people.

Relabeling supplies a consistent reporting convention. It cannot recover posterior regions that the chains did not visit or determine their probability weights.

Alignment uses a fitted reference to name a draw after sampling. Another convention is to require a strict order, for example $p_{11}>p_{12}>p_{13}$, in the model itself. The probability of a tie is zero under the continuous prior. For parameter values with distinct first-item probabilities, exactly one of their six label permutations satisfies that ordering. Exchangeability assigns that region one sixth of the unrestricted prior probability, and the symmetric likelihood gives it one sixth of the unrestricted posterior probability. The normalized density on that region is six times its unrestricted value. For a function constant across permutations, integration over the ordered region with this density gives the same expectation as integration over all six regions.

Ordering by one item need not name profiles in the same way as matching all respondents to the reference allocation. If substantive theory places different priors on named classes or requires several particular item inequalities simultaneously, those assumptions need their own specification and normalization.

Summing out class membership

A leapfrog step changes a coordinate by a real-valued increment and evaluates a derivative at the new position. A class number takes isolated integer values, so there is no corresponding derivative in the class coordinate. Summing over the possibilities gives a differentiable likelihood as a function of the class proportions and item probabilities when all proportions are positive and all item probabilities lie strictly between zero and one.

Class membership can therefore be summed out before sampling. For one response pattern define $a_{ic}=\log\pi_c+\log f_c(y_i)$ and $b_i=\max_c a_{ic}$. Its log probability is $b_i+\log\sum_c\exp(a_{ic}-b_i)$, so even an unlikely pattern can be evaluated on the log scale. Its derivative with respect to $a_{ic}$ is $w_{ic}$. Thus the derivative of this person’s log probability with respect to a class-specific parameter is that class’s conditional score multiplied by the posterior probability that this person belongs to the class. With $\pi_1=1-\pi_2-\pi_3$, the derivative of the log likelihood with respect to a free proportion $\pi_c$ is $\sum_i(w_{ic}/\pi_c-w_{i1}/\pi_1)$.

To evaluate the log posterior density in unconstrained coordinates, the R function uses two baseline-category logits $\eta_c=\log(\pi_c/\pi_1)$ and 18 item logits $\xi_{jc}=\log[p_{jc}/(1-p_{jc})]$. Transforming from the two logits to the free proportions has Jacobian determinant $\pi_1\pi_2\pi_3$ and transforming each item logit to a probability contributes $p_{jc}(1-p_{jc})$ to the Jacobian determinant. Differentiating the resulting log posterior density gives

\[\frac{\partial\log\pi(\eta,\xi\mid Y)}{\partial\eta_c} =\sum_i(w_{ic}-\pi_c)+1-3\pi_c,\qquad \frac{\partial\log\pi(\eta,\xi\mid Y)}{\partial\xi_{jc}} =\sum_i w_{ic}(y_{ij}-p_{jc})+1-2p_{jc}.\]

The last two terms in each expression come from its log Jacobian. The normalized Dirichlet prior contributes the constant $\log\Gamma(3)$ on the set of positive class proportions summing to one. The sourced function lca_posterior_target() implements this density and gradient for a fixed response matrix. At strictly positive class proportions summing to one and item probabilities strictly between zero and one, check the transformed log density against all 600 rows and compare the pattern-weighted gradient both with the gradient computed row by row, including the prior and log-Jacobian terms, and with numerical derivatives.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
source("code/lib/latent_class_posterior.R")
source("code/lib/differentiation.R")
target <- lca_posterior_target(Y)
u <- seq(-.3,.4,length.out=20L)
s <- target$unpack(u)
log_jac <- sum(log(s$mass))+sum(log(s$probability)+log1p(-s$probability))
rows <- mixture_posterior(lca_log_emission(Y,s$probability),s$mass)
totals <- colSums(rows$posterior)
gradient_mass <- totals-nrow(Y)*s$mass+1-3*s$mass
# Weighted success residuals plus the derivative of the log Jacobian for the item logits.
gradient_item <- crossprod(Y,rows$posterior)-sweep(s$probability,2,totals,"*")+
  1-2*s$probability
stopifnot(abs(rows$loglik+lgamma(3)+log_jac-target$value(u))<1e-8,
          max(abs(c(gradient_mass[-1],gradient_item)-target$gradient(u)))<1e-8,
          max(abs(target$gradient(u)-num_grad(target$value,u)$gradient))<1e-4)

In the sourced implementation, the function lca_posterior_target() fixes the response matrix and returns unpack(u), value(u) and gradient(u). The first converts two class-proportion logits followed by 18 item logits arranged down each class column to mass and an item-by-class probability matrix. The other two evaluate the transformed log density and its gradient in the same coordinate order. For these complete observations the function evaluates 56 distinct patterns, weighting each by its frequency.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
lca_posterior_target <- function(Y,K=3L) {
  J <- ncol(Y)
  # Every occurrence of a response pattern contributes the same likelihood and score.
  key <- apply(Y,1,paste,collapse=":")
  index <- match(key,unique(key))
  pattern <- Y[!duplicated(index),,drop=FALSE]
  frequency <- tabulate(index,nrow(pattern))
  observed <- 1*!is.na(pattern)
  success <- pattern
  success[is.na(success)] <- 0
  stopifnot(all(success %in% 0:1))
  failure <- observed-success
  unpack <- function(u) {
    log_mass <- c(0,head(u,K-1))
    list(mass=normalize_logweights(log_mass),probability=matrix(plogis(tail(u,-(K-1))),J,K))
  }
  evaluate <- function(u) {
    s <- unpack(u)
    P <- s$probability; pi <- s$mass
    if(any(P<=0 | P>=1) || any(pi<=0)) return(list(value=-Inf,gradient=rep(NaN,length(u))))
    emission <- success%*%log(P)+failure%*%log1p(-P)
    posterior <- mixture_posterior(emission,pi)
    weights <- frequency*posterior$posterior
    totals <- colSums(weights)
    # The two Jacobians come from free mass logits and independent item logits.
    value <- sum(frequency*posterior$observation_loglik)+lgamma(K)+sum(log(pi))+sum(log(P)+log1p(-P))
    score_p <- crossprod(success,weights)-P*crossprod(observed,weights)+1-2*P
    score_pi <- totals-nrow(Y)*pi+1-K*pi
    list(value=value,gradient=c(score_pi[-1],score_p))
  }
  last_u <- last_result <- NULL
  at <- function(u) {
    if(!identical(u,last_u)) {
      last_result <<- evaluate(u)
      last_u <<- u
    }
    last_result
  }
  list(unpack=unpack,value=function(u)at(u)$value,gradient=function(u)at(u)$gradient)
}

In evaluate(), emission contains each pattern’s log probability in each class, mixture_posterior() (Section 12.1) gives the log pattern probabilities and the class probabilities, and value adds the frequency-weighted log likelihood, $\log\Gamma(K)$ for the uniform prior of the proportions and the logs of the two Jacobians. The item score is the expected successes minus $p_{jk}$ times the expected number of observed answers plus $1-2p_{jk}$, and the proportion score is the expected class count minus $n\pi_k$ plus $1-K\pi_k$, for all classes after the first.

For sampling with NUTS, the sampler works directly in these 20 unconstrained coordinates. As an independent check of the density, code/model_programs/latent_class.stan writes the same posterior in Stan, with the proportions declared as nonnegative values summing to one and the item probabilities between zero and one. Its data supply P distinct response patterns on J items, their frequencies, and the number of classes K.

To compare log densities on the common constrained scale, supply the same proportions and item probabilities to the compiled program and obtain its own unconstrained coordinates. Exclude each transformation Jacobian when comparing the two values.

1
2
3
4
5
6
7
8
9
10
key <- apply(Y,1,paste,collapse=":")
index <- match(key,unique(key))
d <- list(P=max(index),J=ncol(Y),K=3L,pattern=Y[!duplicated(index),,drop=FALSE],
          frequency=tabulate(index))
model <- rstan::stan_model("code/model_programs/latent_class.stan",model_name="latent_class")
shell <- rstan::sampling(model,data=d,chains=0L)
v <- rstan::unconstrain_pars(shell,list(mass=s$mass,probability=s$probability))
print(c(Stan_minus_book=rstan::log_prob(shell,v,adjust_transform=FALSE)-
          (target$value(u)-sum(log(s$mass))-
             sum(log(s$probability)+log1p(-s$probability)))))
1
2
Stan_minus_book 
   4.547474e-13 

The signed difference at the chosen point is $4.55\times10^{-13}$. The sampler can now follow gradients in continuous coordinates with all three possibilities for each person’s class included in the likelihood.

What probability do the two samplers assign to a new respondent answering yes on all six items? At one draw calculate $g(\pi,P)=\sum_c\pi_c\prod_{j=1}^6p_{jc}$. The product remains inside the class sum because the new respondent has one class shared by all six answers. Average $g$ over the posterior draws to obtain the posterior predictive probability. Use the saved values from the allocation sweeps and reconstruct the same function from the proportions and item probabilities in the marginalized fit. The latter is the book’s NUTS sampler with seed 101617 and four chains, each with 1,000 warmup and 1,000 retained iterations.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
source("code/lib/boundary_test.R")
source("code/lib/nuts.R")
mass_names <- paste0("mass[",1:3,"]")
item_names <- paste0("probability[",rep(1:6,3),",",rep(1:3,each=6),"]")
lca_report <- function(u) {
  s <- target$unpack(u)
  setNames(c(s$mass,s$probability),c(mass_names,item_names))
}
fit_marginal <- function() hamiltonian_chains(target,20L,lca_report,101617)
record <- read_chain("LCA-marginal",1L)
prediction <- apply(record$draws[,,c(mass_names,item_names)],c(1,2),function(v)
  all_six(list(mass=v[1:3],probability=matrix(v[4:21],6))))
a <- summaries$allocation["probability_all_one",]
m <- chain_summary(prediction)
print(rbind(allocation=a,integrated=m))
difference_mcse <- (m["mean"]-a["mean"])/sqrt(m["MCSE"]^2+a["MCSE"]^2)
1
2
3
                mean         sd     Rhat  ESS_bulk  ESS_tail         MCSE
allocation 0.1383200 0.01306018 1.000346 13579.326 14576.790 0.0001119405
integrated 0.1385604 0.01342708 0.999892  6914.039  3603.812 0.0001615395

The two predictive estimates are 0.13832 and 0.13856. Their difference is about 1.2 combined Monte Carlo standard errors when the two independent variances are added. Both estimates average over parameter uncertainty. The terminal state’s 0.1190082 was one term of the allocation average.

Compare integration work and the diagnostics for a labeled column as well.

1
2
3
4
t(vapply(record$diagnostics,function(s) c(
  step_size=unname(s[1,"step_size"]),leapfrog_steps=sum(s[,"leapfrog_steps"]),
  divergences=sum(s[,"divergent"]),depth_hits=sum(s[,"tree_depth"]>=10)),numeric(4)))
summaries$marginal["raw_item1_class1",c("mean","Rhat","ESS_bulk")]

The marginalized fit records 7,932 to 9,536 leapfrog steps per chain, step sizes from 0.413 to 0.464, and no divergences or depth-limit hits. Its unaligned first item probability in the class numbered one averages 0.5047, with $\widehat R=1.735$ and bulk ESS 6.1. Summing over individual allocations leaves the symmetry between parameter columns intact.

For the predictive probability the effective sizes are 13,579 and 6,914, obtained from 16,000 Gibbs sweeps and 4,000 NUTS transitions respectively. A NUTS transition can use several gradient evaluations, so neither the number of retained draws nor their effective size alone establishes which method costs less for a given precision.

Marginalizing continuous factors and hidden state paths

A continuous latent variable can sometimes be integrated out analytically. At fixed loadings $\lambda$ and unique variances $\psi$ in the one-factor model for BAYES4, a person’s response vector has covariance $\lambda\lambda^\top+\operatorname{diag}(\psi)$ after integrating out the standard normal factor. At the original-scale MAP estimates, evaluate the first person’s four responses under this multivariate normal. Independently multiply the four conditional densities at each of 81 quadrature nodes and integrate that product with the standard normal weights.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
source("code/lib/bayes_factor.R")
source("code/lib/integration.R")
check <- bayes4_unpack(readRDS("data/derived/ch16/analysis.rds")$MAP$par)
Y4 <- readRDS("data/source/ch16/BAYES4.rds")
rule <- normal_rule(81L)
conditional_ll <- function(z)
  sum(dnorm(Y4[1,],check$loading*z,sqrt(check$variance),log=TRUE))
marginal_check <- c(
  normal_log_marginal_density=bayes4_pointwise(Y4[1,,drop=FALSE],
                                               check$loading,check$variance),
  quadrature_log_marginal_density=logsumexp(log(rule$weights)+
    vapply(rule$nodes,conditional_ll,0.0)))
print(c(marginal_check,quadrature_minus_normal=
  marginal_check[["quadrature_log_marginal_density"]]-
  marginal_check[["normal_log_marginal_density"]]))

Both calculations give a log marginal density of $-5.374238$, with quadrature minus the analytic result equal to $1.30\times10^{-8}$. Having the analytic density lets a random walk propose only population parameters. The augmented Gibbs sampler also draws the person factors. For the first loading, compare how many operations of each kind were used per effective draw.

1
2
3
4
5
6
7
8
9
10
walk <- lapply(1:4,function(i) read_chain("RW-factor-block-adaptive",i))
gibbs <- lapply(1:4,function(i) read_chain("factor-Gibbs",i))
first_loading_ess <- function(chains) {
  x <- do.call(cbind,lapply(chains,function(r) r$draws[,"loading1"]))
  bulk_ess(x)
}
proposals <- sum(vapply(walk,function(r) as.numeric(r$proposals),0.0))
sweeps <- sum(vapply(gibbs,function(r) nrow(r$draws),0L))
c(proposals_per_effective_draw=proposals/first_loading_ess(walk),
  sweeps_per_effective_draw=sweeps/first_loading_ess(gibbs))

The block walk achieved bulk ESS 384.2 from 16,000 proposals, about 41.6 proposals per effective draw. Gibbs achieved 14,638 from 80,000 sweeps, about 5.5 sweeps per effective draw. A proposal on the analytic marginal and a whole conditional sweep perform different calculations. Comparing elapsed time per effective draw would require timings for both.

For discrete latent variables with repeated observations, return to the hidden Markov model. Here the sum must respect dependence between consecutive states. Let $A_{hk}$ denote the probability of moving from state $h$ to state $k$, $e_k(y_t)$ the response probability or density in state $k$, and $\delta_k$ the initial state probability. The initial probabilities and each row of $A$ sum to one. Assume a first-order state process and responses independent given the state sequence.

The forward quantity $\alpha_t(k)$ is the joint probability or density of the responses through time $t$ and state $k$ at that time. Start with $\alpha_1(k)=\delta_k e_k(y_1)$ and update $\alpha_t(k)=e_k(y_t)\sum_h\alpha_{t-1}(h)A_{hk}$. The sum of the final entries is the likelihood of that person’s sequence over all state paths. Multiplying the sequence likelihoods across independent people and applying the parameter priors provides a posterior for continuous parameters on which NUTS can operate. In R, rstan provides NUTS and label.switching provides ECR relabeling for allocation draws; Section 16.10 compares ecr_permutations() with the latter.

16.8 Rank-normalized split R-hat, effective sample size, and Monte Carlo standard error

Posterior summaries computed from stored draws require chains that agree with one another and contain enough information about the quantity being summarized. This section develops three diagnostics, beginning with four Gibbs chains for the one-factor model for BAYES4: rank-normalized split $\widehat R$ for agreement between chains, bulk and tail effective sample sizes, and the Monte Carlo standard error of a posterior mean. It then checks the calculations against the posterior package and applies them to the chapter’s saved chain sets.

Agreement in location and spread

For the first loading in the one-factor model for BAYES4, four Gibbs chains give a posterior mean of 0.78006. How precisely do those chains estimate that mean, and do they agree about the spread of the loading? Both questions require knowing which draws belong to the same chain. From the book directory, read the four matrices of Gibbs draws. The calculation used in code/practice/16.8.R takes the same loading from each matrix and binds the columns without changing their time order. Each row of x is one retained iteration and each column is one independently run chain. The diagnostic functions in code/lib/posterior_checks.R split each column into an early and a late half so that a drift within one run can appear as a difference between halves.

1
2
3
4
5
6
7
8
9
10
11
12
.libPaths(c(".R-library", .libPaths()))
gibbs <- readRDS("data/derived/ch16/factor-gibbs-chains.rds")
parameter <- colnames(gibbs[[1]])[1]
x <- do.call(cbind,lapply(gibbs,function(chain) chain[,parameter]))
split_halves <- function(x) {
  x <- as.matrix(x)
  h <- nrow(x)%/%2L
  if(h<3L || any(!is.finite(x))) return(NULL)
  cbind(x[seq_len(h),,drop=FALSE],x[nrow(x)-h+seq_len(h),,drop=FALSE])
}
s <- split_halves(x)
rbind(original=dim(x),split=dim(s))

The original dimensions are 20,000 by four. The split matrix has 10,000 rows and eight columns, with the four early halves followed by the four late halves. The eight halves still come from four independently generated chains. Splitting preserves time order within each half. For a chain of odd length, take equally many rows from the beginning and the end and omit its middle observation.

The distances between a few extreme loadings can have a large influence on a variance. To compare where chains spend their time, rank the values across all halves together. Give equal observations the average of the positions they occupy in the sorted sample. For a pooled rank $r$ among $S$ retained split draws, the normal score is

\[z=\Phi^{-1}\!\left(\frac{r-3/8}{S+1/4}\right),\]

where $\Phi^{-1}$ is the standard normal quantile function. The offsets map the smallest and largest ranks to probabilities strictly between zero and one and give them symmetric scores. After the transformation, put every value back in its half-chain and iteration. Ranking separately within each column would give all columns essentially the same rank distribution even if one chain had explored only small loadings.

1
2
3
4
5
6
rank_normalize <- function(x) {
  S <- length(x)
  matrix(qnorm((rank(x,ties.method="average")-3/8)/(S+1/4)),nrow(x),ncol(x))
}
z <- rank_normalize(s)
c(draw=s[1,1],rank=rank(s,ties.method="average")[1],normal_score=z[1,1])

The first loading drawn by chain one is 0.69281. Its rank is 9,012 out of 80,000, giving a normal score of $-1.21258$. The ranking changes the scale of this observation while preserving the identity of its neighbors in the chain.

Let $n$ be the length of each half-chain, $m$ the number of halves, and $z_{tj}$ the score at iteration $t$ in half $j$. Write $\bar z_j$ and $s_j^2$ for that half’s mean and sample variance and $\bar z$ for the grand mean. There are two sources of information about spread. The average within-half variance $W$ measures fluctuations over the region visited by each half. Variation of the half-chain means adds information about regions that a single trajectory may have missed. Define

\[W=\frac{1}{m}\sum_j s_j^2,\qquad B=\frac{n}{m-1}\sum_j(\bar z_j-\bar z)^2,\qquad \widehat V^+=\frac{n-1}{n}W+\frac{B}{n},\qquad \widehat R_z=\sqrt{\widehat V^+/W}.\]

When the halves cover different locations, their means can differ substantially even if each half is quiet. That raises $B/n$ relative to $W$. In R, var(colMeans(v)) is already $B/n$. Dividing $\widehat V^+$ by $W$ gives the expression under the square root below.

1
2
3
4
5
6
7
rhat_ratio <- function(v) {
  n <- nrow(v)
  W <- mean(apply(v,2,var))
  if (W==0) return(NA_real_)
  sqrt((n-1)/n+var(colMeans(v))/W)
}
rhat_ratio(z)

For the first loading, $W=0.99919$ and $B=9.55134$ on the normal-score scale. With 10,000 draws per half, the ratio of standard deviations is 1.00043. Agreement of the half-chain means alone can conceal a difference in spread.

To check spread, fold the values around the median of the original pooled draws. A loading equally far above or below that median now gives the same absolute deviation. Rank these distances together, transform them to normal scores, and compute the variance ratio again. Report the larger of the rank-normalized ratios before and after taking absolute deviations from the pooled median as split $\widehat R$. The median comes from the full matrix, including the middle iteration of an odd-length chain. To see what folding contributes, use seed 1608 to make four columns of independent standard normal observations. The six diagnostic examples retain this array or change its location, scale, rounding, or within-chain variation. In the scale example, double only column four.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
split_rhat <- function(x) {
  if (any(!is.finite(x))) return(NA_real_)
  s <- split_halves(x)
  if (is.null(s) || all(s==s[1])) return(NA_real_)
  folded <- abs(s-median(as.numeric(x)))
  max(rhat_ratio(rank_normalize(s)),rhat_ratio(rank_normalize(folded)))
}
RNGkind("Mersenne-Twister","Inversion","Rejection")
set.seed(1608)
iid <- matrix(rnorm(4004),1001L,4L)
diagnostic_examples <- list(iid=iid,shifted=sweep(iid,2,c(0,0,0,1),"+"),
  scaled=sweep(iid,2,c(1,1,1,2),"*"),tied=round(iid),constant=matrix(1,1001L,4L),
  stuck=matrix(rep(1:4,each=1001L),1001L))
a <- diagnostic_examples$scaled
v <- split_halves(a)
c(location=rhat_ratio(rank_normalize(v)),
  folded=rhat_ratio(rank_normalize(abs(v-median(a)))))

The rank-normalized ratio before taking absolute deviations is 1.00000 to five decimal places. Folding lifts it to 1.06129 because the fourth column contains more observations far from the median.

Effective sample size for bulk and tails

To assess Monte Carlo precision, now estimate how serial dependence and differences between chains affect the effective number of draws for a particular quantity. For any values $v_{tj}$ in half-chain $j$, estimate the autocovariance at lag $k$ from pairs separated by $k$ iterations. Center each observation on its own half-chain mean. The estimate and its average over halves are

\[\hat\gamma_j(k)=\frac{1}{n}\sum_{t=1}^{n-k} (v_{tj}-\bar v_j)(v_{t+k,j}-\bar v_j),\qquad \bar\gamma(k)=\frac{1}{m}\sum_j\hat\gamma_j(k).\]

Every lag uses divisor $n$, even though only $n-k$ pairs contribute. Consequently $W=n\bar\gamma(0)/(n-1)$. Using $\widehat V^+$ from the same values, estimate $\hat\rho_k=1-[W-\bar\gamma(k)]/\widehat V^+$ for positive lags and set $\hat\rho_0=1$. If the chain means disagree, the denominator $\widehat V^+$ increases and a short stretch of small within-chain correlations supplies less evidence of independent sampling.

1
2
3
4
5
6
7
8
9
10
chain_autocovariance <- function(x) {
  n <- length(x)
  extended <- c(x-mean(x),numeric(n))
  # Zero padding gives a linear rather than a circular correlation.
  power <- Mod(fft(extended))^2
  Re(fft(power,inverse=TRUE))[seq_len(n)]/(as.numeric(length(extended))*n)
}
n <- nrow(z)
v <- z[,1]-mean(z[,1])
c(direct=sum(v[-n]*v[-1])/n,fft=chain_autocovariance(z[,1])[2])

The fast Fourier transform (FFT) obtains the lagged cross-products together. Appending $n$ zeros prevents the lagged products from treating the end of the series as adjacent to its beginning. The inverse transform supplies an additional multiplier equal to the padded length, which the function divides out.

The returned vector starts at lag zero, so its second element, [2], is the autocovariance at lag one. The direct calculation beside the function uses the first 9,999 centered scores and their immediate successors in the first half of the first loading chain.

For independent stationary chains with a common marginal distribution of finite variance and common summable autocorrelations, the variance of their pooled mean is approximately the variance of one draw times $\tau/S$, where $\tau=1+2\sum_{k\geq1}\rho_k$ and the total draw count is $S$. In the split-chain estimate $S=nm$, but the two halves of an original chain are not additional independent runs. The effective sample size (ESS) is the number of independent draws that would give that variance. Estimating all lags out to $n-1$ would give very noisy terms nearly the same influence as the well-estimated early ones. Geyer’s initial positive sequence groups $\hat\rho_0+\hat\rho_1$, $\hat\rho_2+\hat\rho_3$ and so on. The initial monotone sequence then prevents later retained pair sums from exceeding the preceding ones.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
effective_draws <- function(s) {
  if(is.null(s) || any(!is.finite(s)) || all(s==s[1])) return(NA_real_)
  n <- nrow(s); S <- length(s)
  acov <- rowMeans(vapply(seq_len(ncol(s)),function(j)chain_autocovariance(s[,j]),numeric(n)))
  within <- acov[1]*n/(n-1)
  # Different constant chains can still have positive between-chain variance.
  pooled <- acov[1]+if(ncol(s)>1) var(colMeans(s)) else 0
  rho <- 1-(within-acov)/pooled
  rho[1] <- 1
  # Initial positive sequence, including lag zero and lag one before any loop.
  retained <- numeric(n)
  lag <- 0L
  even <- 1
  odd <- rho[2L]
  retained[1:2] <- c(even, odd)
  while (lag < n - 5L && !is.nan(even + odd) && even + odd > 0) {
    lag <- lag + 2L
    even <- rho[lag + 1L]
    odd <- rho[lag + 2L]
    if (even + odd >= 0) retained[lag + 1:2] <- c(even, odd)
  }
  max_lag <- lag
  if (even > 0) retained[max_lag + 1L] <- even
  lag <- 0L
  while (lag <= max_lag - 4L) {
    lag <- lag + 2L
    previous_pair <- sum(retained[c(lag - 1L, lag)])
    if (sum(retained[lag + 1:2]) > previous_pair)
      retained[lag + 1:2] <- previous_pair / 2
  }
  # The original algorithm includes lag zero when max_lag is zero (R's 1:0 index).
  initial_sum <- if (max_lag == 0L) retained[1L] else sum(retained[seq_len(max_lag)])
  tau <- -1 + 2 * initial_sum + retained[max_lag + 1L]
  S/max(tau,1/log10(S))
}
effective_draws(z)

Starting at lag zero, the code admits consecutive positive sums while the first lag of the pair is less than $n-5$. Each admitted sum is reduced to at most the preceding adjusted sum, giving the initial monotone sequence.

Because the first pair includes lag zero, twice the sum of these adjusted pairs counts $\hat\rho_0$ twice. Subtract one, then add the positive part of the first unused even-lag estimate once. Finally bound the denominator below by $1/\log_{10}S$, which caps ESS at $S\log_{10}S$. Negative serial correlation can improve the precision of a mean and give an ESS above $S$. For the rank scores of the loading the calculation gives 14,638 effective draws from 80,000 retained values. The positivity and monotonicity results underlying this sequence method require conditions such as reversibility of the transition rule.

Bulk ESS applies this calculation to the rank-normalized split draws. Tail ESS asks how well the chains estimate cumulative probabilities near the extremes. For each pooled sample quantile $\hat Q_\alpha$ at $\alpha=0.05$ and $0.95$, replace a draw by the indicator $I(\theta\leq\hat Q_\alpha)$. Its mean is the fraction of draws at or below that cutoff. Compute an ESS for each indicator matrix and take the smaller value.

1
2
3
4
5
6
7
8
9
10
11
12
bulk_ess <- function(x) {
  s <- split_halves(x)
  if(is.null(s)) return(NA_real_)
  effective_draws(rank_normalize(s))
}
tail_ess <- function(x) {
  s <- split_halves(x)
  if(is.null(s)) return(NA_real_)
  cut <- quantile(x,c(.05,.95),names=FALSE)
  # The same cumulative indicator is used at both quantiles.
  min(effective_draws(1*(s<=cut[1])),effective_draws(1*(s<=cut[2])))
}

The two calls to effective_draws() preserve the time order of visits on either side of each threshold. The smaller of these two estimates is the reported tail ESS. The exact complement of the upper cumulative indicator is $I(\theta>\hat Q_{0.95})$. Using a weak upper inequality instead would move every draw equal to the cutoff into the upper group. Such ties can arise when draws are rounded for reporting or when a rejected proposal repeats a parameter value. A chain that estimates a central rank precisely can still give an imprecise estimate of a tail probability.

Monte Carlo error of posterior means

For a posterior mean, apply the autocorrelation calculation to the quantity actually averaged, on its reporting scale. If $s_\theta$ is the sample SD across draws, estimate the Monte Carlo standard error (MCSE) as $s_\theta/\sqrt{\widehat{\mathrm{ESS}}_{\theta}}$. The numerator estimates posterior spread. The denominator uses ESS for the original values, whose autocorrelations can differ from those of their ranks. Compare this estimate for the four loadings with two alternatives. Divide each chain into 200 consecutive batches of 100 draws, then divide the sample SD of the 800 batch means by $\sqrt{800}$. Alternatively, use the four independent chain means and divide their sample SD by two. Interpreting this as a standard error also requires a central limit approximation for the mean; finite stored values alone do not establish that approximation.

1
2
3
4
5
6
7
8
9
10
11
12
mean_mcse <- function(x) sd(as.numeric(x))/sqrt(effective_draws(split_halves(x)))
chain_summary <- function(x) {
  c(mean=mean(x),sd=sd(as.numeric(x)),Rhat=split_rhat(x),
    ESS_bulk=bulk_ess(x),ESS_tail=tail_ess(x),MCSE=mean_mcse(x))
}
mcse_by_loading <- t(vapply(colnames(gibbs[[1]])[1:4],function(parameter) {
  x <- do.call(cbind,lapply(gibbs,function(chain) chain[,parameter]))
  batch <- as.vector(apply(x,2,function(chain) colMeans(matrix(chain,nrow=100))))
  c(autocorrelation=mean_mcse(x),batch_means=sd(batch)/sqrt(length(batch)),
    independent_chains=sd(colMeans(x))/sqrt(ncol(x)))
},c(autocorrelation=0,batch_means=0,independent_chains=0)))
print(mcse_by_loading)
1
2
3
4
5
         autocorrelation  batch_means independent_chains
loading1    0.0006080674 0.0005986397       0.0005560702
loading2    0.0004929218 0.0004805606       0.0002974675
loading3    0.0007505739 0.0007328633       0.0003046406
loading4    0.0005382885 0.0005244278       0.0004213945

For loading one, the posterior SD is 0.07334 and the ESS for its original values is 14,548. Dividing by the square root of that count gives an MCSE of 0.000608, compared with 0.000599 from batches and 0.000556 from the four means. The batch calculation requires sufficiently long batches for their means to be nearly independent. The last column rests on only four values. For loading three it gives 0.000305, whereas the two estimates that exploit within-chain information give 0.000751 and 0.000733. A smaller estimate from the four means gives little reason by itself to report more decimal places.

Checking the diagnostic calculations

Return to the six constructed arrays to check the calculations against a reference implementation. A diagnostic can fail to exist even when the mean of the stored draws is easy to compute. Compare the four diagnostic functions with posterior 1.6.1. The book’s functions follow the definitions and settings of posterior without sharing its code, so agreement shows that those settings were matched (Section E.3). Each has four columns of 1,001 observations, leaving 4,000 values after splitting. The function chain_summary() combines the mean and posterior SD with split R-hat, bulk and tail ESS, and the mean MCSE. Its ESS_tail entry is the minimum just defined. The first four arrays give the following results in both implementations.

1
2
3
4
5
6
for (a in diagnostic_examples) {
  book <- chain_summary(a)[c("Rhat","ESS_bulk","ESS_tail","MCSE")]
  reference <- c(posterior::rhat(a),posterior::ess_bulk(a),
                 posterior::ess_tail(a),posterior::mcse_mean(a))
  print(rbind(book=book,reference=reference))
}
ArraySplit $\widehat R$Bulk ESSTail ESSMean MCSE
Independent normal draws0.999704,003.83,930.90.01574
Fourth chain shifted up by one1.1038524.9126.30.21998
Fourth chain multiplied by two1.061294,100.6115.90.02050
Draws rounded to integers0.999614,031.83,893.30.01626

A shift raises $\widehat R$ and reduces bulk ESS from about 4,004 to 25. For the array with the fourth column doubled, the bulk effective sample size is 4,100.6, yet its tail effective sample size is only 115.9. The two counts reflect within-chain dependence and between-chain differences for different functions of those draws. Assigning average ranks to ties allows these diagnostics to be calculated for the rounded array. The two constant examples require separate readings.

Constant arrayImplementationSplit $\widehat R$Bulk ESSTail ESSMean MCSE
Every entry equals oneBothNANANANA
Each chain fixed at a different valueBookNA4.032258NA0.556846
Each chain fixed at a different valueposterior 1.6.1$\infty$4.032258NA0.556846

When each chain is stuck at a different constant, the within-chain variance is zero despite differences between means. Both implementations now give bulk ESS 4.032258 and mean MCSE 0.556846. The book returns NA for the undefined within-chain ratio in $\widehat R$, while the reference prints infinity. These values signal a failure to explore. Any nonfinite input or half-chain shorter than three makes split_halves() return NULL, so the four book diagnostics are unavailable. For half-chains of length three through five, effective_draws() retains the initial autocorrelation terms before testing whether further lag pairs can be formed. The same initial positive and monotone sequence calculation is used for longer chains.

The rounded normal draws also provide a direct check of the upper-tail convention. Compute the 95th percentile from all 4,004 original values, then apply that cutoff to the split matrix. Compare the book’s ESS for this one indicator with posterior::ess_quantile() at the same probability. Comparing only the two reported tail minima could hide a discrepancy at the upper cutoff if the lower one supplied the minimum.

1
2
3
4
5
6
7
tied <- diagnostic_examples$tied
q95 <- unname(quantile(tied,.95))
v <- split_halves(tied)
upper <- 1*(v<=q95)
c(cutpoint=q95,equal=sum(v==q95),at_or_below=sum(upper),above=sum(v>q95))
c(book=effective_draws(upper),
  reference=unname(posterior::ess_quantile(tied,probs=.95)))

The cutoff is two. Of the 4,000 split values, 250 equal two and 24 exceed it. The cumulative indicator puts all 250 ties among its 3,976 ones. A count of draws greater than or equal to two would give 274. The two implementations use the cumulative event and give an upper-cutoff ESS of about 4,064. The smaller ESS at the lower cutoff, 3,893, is the value reported for the rounded array.

Screening the saved chain sets

Apply the diagnostics to the quantity each study set out to estimate. The saved table has 116 parameter or functional rows across 21 named sets of chains. Within each set, take the largest $\widehat R$ and the smallest bulk and tail ESS over its rows. Mark the set as passing when the first is below 1.01 and both effective sizes exceed 400 across the chains combined. The three extremes can come from different parameters. Every required diagnostic in this saved table is finite, so the comparisons below apply to available numerical values. Passing these thresholds is a screening decision for the listed quantities, not proof of convergence; the desired precision must be assessed through their MCSEs.

1
2
3
4
5
6
7
8
9
by_parameter <- read.csv("data/derived/ch16/diagnostics-by-parameter.csv")
by_set <- do.call(rbind,lapply(unique(by_parameter$chain_set),function(name) {
  rows <- by_parameter[by_parameter$chain_set==name, ]
  data.frame(chain_set=name,largest_Rhat=max(rows$Rhat),
             smallest_bulk_ESS=min(rows$ESS_bulk),smallest_tail_ESS=min(rows$ESS_tail))
}))
by_set$passes <- with(by_set,largest_Rhat<1.01 & smallest_bulk_ESS>400 &
                        smallest_tail_ESS>400)
print(by_set,row.names=FALSE)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
         chain_set largest_Rhat smallest_bulk_ESS smallest_tail_ESS passes
             gibbs     1.000450       8765.963839       15827.93111   TRUE
         lmm_gibbs     1.000451       3795.511184        3630.63570   TRUE
         pg_scalar     1.000100      10784.522223       12428.78117   TRUE
        probit_glm     1.000483      12750.964387       22060.71205   TRUE
        probit_irt     1.013678        393.516546         520.23172  FALSE
       ordinal_irt     1.050220        108.198012         139.54683  FALSE
                pg     1.003576       1688.049265        2897.99244   TRUE
         mh_scalar     1.001898       2403.470240        2453.91182   TRUE
      within_gibbs     1.010112        209.041740         113.94336  FALSE
      normal_block     1.001864       1715.832922        1939.85518   TRUE
 normal_coordinate     1.004178        799.129166        1331.11120   TRUE
      factor_block     1.035968        206.712485         387.99825  FALSE
 factor_coordinate     1.008556        685.955769        1020.32063   TRUE
       normal_nuts     1.004445       1125.288885        1221.86915   TRUE
        normal_hmc     1.048734       8577.207284        1744.05818  FALSE
       factor_nuts     1.734178          6.098693         105.16555  FALSE
       ri_centered     1.022602        213.679490         146.04004  FALSE
    ri_noncentered     1.003892        927.096931        1047.85551   TRUE
             alloc     1.528104          7.149608          29.12482  FALSE
           mar_lca     1.734660          6.107542         152.45190  FALSE
          weak_fit     1.001222       2740.284671        2921.21460   TRUE

Nine sets miss a threshold at the recorded lengths. In separate extensions, the longer dichotomous and ordinal item runs first meet all three criteria at 20,000 and 320,000 draws per chain, respectively. For the between-person SD, the within-Gibbs and centered NUTS estimates both differ from the grid mean 0.39826 by about 2.2 of their own MCSEs. Static HMC on the normal target misses only the $\widehat R$ rule, with 1.0487 for the first coordinate. For the block random walk on the marginal factor posterior, the third unique variance gives both the maximum $\widehat R$ 1.0360 and the minimum bulk ESS 206.7. Those block random-walk draws supply a comparison of proposal costs. In the two latent class sets, the raw probability for item one in class one accounts for the failure. Compare the traces of that labeled probability and the six-success prediction, and inspect the MCSE on the row for the quantity to be reported.

1
2
3
4
5
6
7
8
9
by_parameter[by_parameter$chain_set=="factor_block",
             c("parameter","Rhat","ESS_bulk","ESS_tail","MCSE")]
lca <- readRDS("data/derived/ch16/latent-class-posterior-chains.rds")
trace_quantity <- function(parameter) {
  paths <- do.call(cbind,lapply(lca$draws$allocation,function(x) x[,parameter]))
  matplot(paths,type="l",lty=1,xlab="Retained sweep",ylab=parameter)
}
trace_quantity("raw_item1_class1")
trace_quantity("probability_all_one")

The allocation chains disagree about which profile is called class one, while the prediction sums over profiles.

Factor Gibbs meets all three thresholds, but default factor NUTS does not: two of its chains remain in the region with a near-zero first loading, and the first loading has $\widehat R=1.7334$. The separate factor run with target acceptance probability 0.95 has zero retained divergences, but its fourth chain remains in the same region and the first loading has $\widehat R=1.5315$.

For a separate check of the diagnostic implementations, let $d$ and $d_{\rm ref}$ be a diagnostic and its reference value on the same input. Across the four diagnostics and all 21 sets, code/checks/ch16_reference.R gives a maximum of $5.9\times10^{-13}$ for $\vert d-d_{\rm ref}\vert /\max(1,\vert d_{\rm ref}\vert )$. That agreement checks the diagnostic calculations. Precision for a scientific conclusion still depends on the functional, its MCSE and the regions explored by the chains.

16.9 Posterior predictive checks, WAIC, and PSIS-LOO with marginal likelihood contributions

A fitted model can also be judged by the responses it predicts. This section first uses posterior predictive replications to ask whether new samples from the one-factor model for BAYES4 resemble the observed sample. It then scores the observed respondents by WAIC and by leave-one-out prediction with Pareto-smoothed importance sampling (PSIS-LOO). Both scores use each respondent’s marginal likelihood contribution, the density of the four answers with the factor integrated out. The last parts consider other prediction units and replicate the ChickWeight weight trajectories.

The response distribution for a new person

Suppose 150 new people supply four continuous responses under the one-factor model fitted to BAYES4. Would the first two responses show as much association as in the observed sample? A posterior predictive replication answers this question in two stages. Draw population parameters from their posterior distribution given the observed responses, then generate a new sample under those parameters. Write $\theta=(\lambda,\psi)$ for the four loadings and four unique variances. Uncertainty about $\theta$ is shared by everyone in a replication, so draw it once for the whole sample. The person factors and response errors then vary independently across new respondents.

A further measurement on a respondent already observed raises a different question. At the same parameter draw, that respondent’s earlier answers provide information about their factor. An incoming respondent has supplied no such answers.

First derive the marginal response distribution for a new person; it will supply both the predictive replications and the person-level densities used for predictive scoring. To assess prediction for a new person, use the observed response matrix and the population parameter columns from the four saved Gibbs chains. From the book directory, join the matrices in chain order. Each chain contributes 20,000 rows. The ninth column of the original matrices contains a draw of the first observed person’s factor.

1
2
3
4
5
6
7
.libPaths(c(".R-library", .libPaths()))
source("code/lib/stability.R")
source("code/lib/bayes_factor.R")
source("code/lib/posterior_checks.R")
Y <- readRDS("data/source/ch16/BAYES4.rds")
gibbs <- readRDS("data/derived/ch16/factor-gibbs-chains.rds")
parameters <- do.call(rbind,gibbs)[,1:8,drop=FALSE]

For a new person’s response vector, draw one factor $z_i\sim N(0,1)$ and let $y_i=\lambda z_i+e_i$, with $e_i\sim N_4(0,\operatorname{diag}\psi)$ independent of $z_i$. Because this is a sum of independent normal vectors, integrating over the factor gives mean zero and covariance $\Sigma_\theta=\lambda\lambda^\top+\operatorname{diag}\psi$. Its off-diagonal entry $\lambda_1\lambda_2$ is the covariance induced by the same factor in responses one and two. Multiplying four separately integrated univariate densities would discard that association. At posterior draw $s$, the contribution of person $i$ to the marginal log likelihood is

\[\ell_{si}=\log\int \left\{\prod_{j=1}^4 p(y_{ij}\mid z,\theta_s)\right\}\phi(z)\,dz =-\tfrac12\{4\log(2\pi)+\log|\Sigma_{\theta_s}| +y_i^\top\Sigma_{\theta_s}^{-1}y_i\},\]

where $\phi$ is the standard normal density. Evaluate this joint marginal density for each observed response vector at every saved parameter draw.

1
2
3
4
5
6
7
8
9
bayes4_pointwise <- function(Y,loading,variance) {
  # Whiten all person vectors with a single four-by-four Cholesky factor.
  R <- chol(tcrossprod(loading)+diag(variance,length(variance)))
  chol_scaled_residual <- forwardsolve(t(R),t(Y))
  -length(loading)*log(2*pi)/2-sum(log(diag(R)))-colSums(chol_scaled_residual^2)/2
}
pointwise <- t(vapply(seq_len(nrow(parameters)),function(s)
  bayes4_pointwise(Y,parameters[s,1:4],parameters[s,5:8]),numeric(nrow(Y))))
pointwise[1,1]

A triangular solve supplies the quadratic form for every observed person at the same draw. Here R is the upper Cholesky factor of $\Sigma_{\theta_s}$, so sum(log(diag(R))) is $\tfrac12\log\vert \Sigma_{\theta_s}\vert $ and the column sums of chol_scaled_residual^2 are $y_i^\top\Sigma_{\theta_s}^{-1}y_i$. The function returns one log density per response vector. Transposing the collected results puts the 80,000 draws in rows and the 150 people in columns.

For the first respondent at the first draw, the log density is $-5.61613$. Leaving out that respondent removes all four answers together. Using a factor estimated from any of those answers to predict the whole vector would pass information from the omitted record into its own prediction.

Replicating sample means, variances, and covariance

Return to the opening question about the association between the first two responses in a new sample. The same marginal distribution can be sampled by generating the common factor explicitly. At one draw of the parameters, bayes4_generate() generates 150 standard normal factors and one error per item and person. For each simulated sample, calculate the first item’s sample mean and variance and the sample covariance between items one and two. Across replications, the means reflect both respondent sampling and the model’s zero response intercepts. The variances and covariances also depend on the population parameter draw. The function below makes one replicated sample per row of the parameter matrix, in chain order. The first row suffices to check the seed and the order of the draws. For the quantiles, read all 80,000 rows of the saved predictive matrix. Compare the observed summaries with quantiles taken down the corresponding columns.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
replicate_stats <- function(p,n) {
  yrep <- bayes4_generate(n,p[1:4],p[5:8])$Y
  c(mean1=mean(yrep[,1]),variance1=var(yrep[,1]),cov12=cov(yrep[,1],yrep[,2]))
}
posterior_predictive <- function(parameters,n) {
  t(vapply(seq_len(nrow(parameters)),function(s)
    replicate_stats(parameters[s,],n),numeric(3L)))
}
RNGkind("L'Ecuyer-CMRG","Inversion","Rejection")
set.seed(1619)
first_rep <- posterior_predictive(parameters[1,,drop=FALSE],nrow(Y))[1,]
predictive <- readRDS("data/derived/ch16/analysis.rds")$predictive
stopifnot(isTRUE(all.equal(unname(first_rep),unname(predictive[1,]))))
print(cbind(observed=c(mean(Y[,1]),var(Y[,1]),cov(Y[,1],Y[,2])),
            t(apply(predictive,2,quantile,c(.025,.5,.975)))))
1
2
3
4
            observed       2.5%          50%     97.5%
mean1     -0.1195883 -0.1583481 0.0005963592 0.1601879
variance1  0.9496041  0.7107597 0.9801917764 1.3582615
cov12      0.4480929  0.2501104 0.4525330898 0.7214756

The observed first-item mean, $-0.11959$, lies toward the lower end of the central 95 percent interval from $-0.15835$ to $0.16019$. Its variance, 0.94960, lies between 0.71076 and 1.35826, and the observed covariance, 0.44809, is close to the replicate median of 0.45253. These three summaries look plausible for 150 new respondents under the fitted model. An interval in this table describes variation in a replicated sample statistic. For example, the covariance interval concerns what another sample might exhibit even if the estimated posterior mean of the covariance has very small Monte Carlo error.

WAIC from person-level log densities

A predictive score asks a more specific question about the observed data. How much probability density does the fitted model assign to each respondent’s actual four answers? For person $i$, average $L_i(\theta_s)=\exp(\ell_{si})$ over the $S$ posterior draws, then take the logarithm. Summing those logs gives the log pointwise predictive density (lppd). The same people helped determine the posterior that scores their answers, which favors the fitted model. The widely applicable information criterion (WAIC) estimates how much this reuse increases the apparent predictive fit using the posterior variation in each person’s log likelihood contribution. Let $\bar\ell_i$ be the mean down column $i$. On the expected log pointwise predictive density (elpd) scale, the calculation is

\[\mathrm{lppd}=\sum_i\left[\log\sum_s e^{\ell_{si}}-\log S\right],\qquad p_{\rm WAIC}=\sum_i\frac{1}{S-1}\sum_s(\ell_{si}-\bar\ell_i)^2,\qquad \widehat{\mathrm{elpd}}_{\rm WAIC}=\mathrm{lppd}-p_{\rm WAIC}.\]

A respondent whose log density changes substantially over plausible parameter values contributes a larger penalty. Both averaging and variance estimation operate within a person. Taking the variance of a sum over people would also introduce cross-person covariance terms.

1
2
3
4
5
6
7
8
9
waic <- function(log_likelihood) {
  stopifnot(is.matrix(log_likelihood),nrow(log_likelihood)>1,
            all(is.finite(log_likelihood)))
  lppd <- apply(log_likelihood,2,logsumexp)-log(nrow(log_likelihood))
  penalty <- apply(log_likelihood,2,var)
  data.frame(unit=seq_along(lppd),lppd=lppd,penalty=penalty,elpd=lppd-penalty)
}
waic_person <- waic(pointwise)
waic_person[1,]

In the table returned by waic(), the elpd column gives one corrected contribution per person. For person one the log of the mean density is $-5.38562$ and the penalty is 0.06485, giving a corrected score of $-5.45047$. Larger elpd means greater predictive density on average on the log scale.

Leave-one-out prediction by importance weighting

Leave-one-out (LOO) cross-validation addresses reuse of the observations directly. Write $Y_{-i}$ for the other 149 response vectors. Conditional independence across respondents gives $p(\theta\mid Y)\propto L_i(\theta)p(\theta\mid Y_{-i})$. To use draws from the full posterior for an expectation under the reduced-data posterior, the importance ratio is therefore proportional to $1/L_i(\theta)$. At the saved draws its unnormalized log value is $-\ell_{si}$. Dividing each ratio by the sum of all ratios supplies weights that add to one. In particular, the predictive density and its unsmoothed estimate satisfy

\[p(y_i\mid Y_{-i})=\int L_i(\theta)p(\theta\mid Y_{-i})\,d\theta,\qquad \frac{\sum_s L_i(\theta_s)^{-1}L_i(\theta_s)} {\sum_s L_i(\theta_s)^{-1}} =\frac{S}{\sum_s\exp(-\ell_{si})}.\]

This identity also explains the WAIC penalty. For $F_i(t)=\log E_{\theta\mid Y}[\exp(t\ell_i)]$, the full-data log predictive density is $F_i(1)$ and the leave-one-out log predictive density is $-F_i(-1)$. When a second-order expansion around zero is adequate, their difference is approximately $F_i^{\prime\prime}(0)=\operatorname{Var}_{\theta\mid Y}(\ell_i)$. The raw importance estimate has a practical weakness. A draw under which the omitted response is very unlikely receives a large ratio. If the reduced-data posterior puts substantial probability in a region rarely visited by the full-data fit, a small number of such draws can determine the estimate.

Pareto-smoothed importance sampling (PSIS) uses the ordered upper tail of the ratios to stabilize their largest values. How many ratios should enter the tail fit? Let $r_{\rm eff}$ denote the effective sample size for the likelihood values divided by the number of draws. The rule used here takes

\[M=\left\lceil\min\{S/5,\;3\sqrt{S/r_{\rm eff}}\}\right\rceil .\]

In the factor model, draws came from Markov chains. For each respondent exponentiate their column of log densities after subtracting its maximum. This positive rescaling preserves the autocorrelations of the likelihood and avoids very small absolute likelihoods. Restore the four chain columns in their original order and estimate effective sample size for the scaled likelihood values. Effective size for a loading, or for the ranks of the log likelihoods, would describe serial dependence in a different quantity.

1
2
3
4
5
6
7
eff <- vapply(seq_len(ncol(pointwise)),function(i) {
  log_l <- pointwise[,i]
  values <- matrix(exp(log_l-max(log_l)),ncol=4)
  effective_draws(split_halves(values))/length(values)
},0.0)
S <- nrow(pointwise)
c(relative_efficiency=eff[1],tail_length=ceiling(min(S/5,3*sqrt(S/eff[1]))))

For person one, $r_{\rm eff}$ is about 0.233 and the rule selects 1,759 of the 80,000 ratios. All respondents have the same number of posterior draws, but their likelihoods need not have the same autocorrelations.

For a single respondent, subtract the largest log ratio from the log ratios and sort them in ascending order. Let $u$ be the ratio just below the largest $M$, on this rescaled ratio scale. The tail observations for fitting are the excesses $x_j=r_{(S-M+j)}-u$ for $j=1,\ldots,M$. Approximate their distribution by a generalized Pareto distribution with scale $\sigma>0$ and shape $k$. Its survival probability at excess $x$ is $(1+kx/\sigma)^{-1/k}$ on its support, with exponential limit at $k=0$. A positive shape allows a power-law upper tail. To fit the shape and scale together, the Zhang and Stephens profile calculation works with $b=-k/\sigma$. For a candidate $b$, calculate $k(b)=M^{-1}\sum_j\log(1-bx_j)$. Substituting into the density gives the profile log likelihood $M\lbrace \log[-b/k(b)]-k(b)-1\rbrace $. A negative shape instead gives a finite upper endpoint; every fitted excess must satisfy $1+kx/\sigma>0$. The shape need not be positive for the fit to be valid.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
fit_gpd_tail <- function(excess) {
  x <- sort(excess)
  n <- length(x)
  if(n<5L || any(!is.finite(x)) || any(x<0) || x[floor(n/4+.5)]<=0 || max(x)<=0)
    return(list(valid=FALSE,reason="insufficient distinct positive excesses"))
  grid <- 30L+floor(sqrt(n))
  theta <- 1/max(x)+(1-sqrt(grid/(seq_len(grid)-.5)))/(3*x[floor(n/4+.5)])
  # For each grid value, profile out the scale and weight by the profile likelihood.
  shape <- vapply(theta,function(t)mean(log1p(-t*x)),0.0)
  ratio <- ifelse(theta==0,1/mean(x),-theta/shape)
  lw <- n*(log(ratio)-shape-1)
  finite <- is.finite(lw) & is.finite(theta)
  if(!any(finite)) return(list(valid=FALSE,reason="no finite profile weights"))
  t <- sum(theta[finite]*normalize_logweights(lw[finite]))
  raw <- mean(log1p(-t*x))
  scale <- if(t==0) mean(x) else -raw/t
  list(valid=is.finite(scale)&&scale>0,reason="profile",
       shape=(n*raw+5)/(n+10),scale=scale)
}

The code uses a grid based on the largest excess and an order statistic near the lower quartile of the excesses. It normalizes the finite profile weights on this grid and averages $b$ with those weights. The code names the candidate profile coordinates theta and their weighted average t.

At that weighted value, raw is the unregularized shape and scale is its associated scale estimate. The reported shape is $(M\,\mathrm{raw}+5)/(M+10)$, a weighted average of the fitted shape and 0.5. The influence of this regularization decreases as the number of usable tail observations grows. The scale used to predict tail quantiles comes from the profile fit before shape shrinkage.

Replace each ordered tail excess by a fitted quantile at probability $p_j=(j-1/2)/M$. Evaluating strictly inside the unit interval gives a finite quantile for the largest rank even for an unbounded fitted tail. Write $z_j=-\log(1-p_j)$. The replacement excess is $\sigma[\exp(kz_j)-1]/k$, or $\sigma z_j$ in the exponential limit. Add back $u$ to obtain the replacement ratio. Cap it at the largest observed raw ratio, which is one after rescaling. The body of the ratio distribution remains empirical. Finally subtract the log of the sum of all resulting ratios to normalize the log weights.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
psis_weights <- function(log_ratio,r_eff=1) {
  n <- length(log_ratio)
  stopifnot(n > 0L, all(is.finite(log_ratio)),length(r_eff)==1L,is.finite(r_eff),r_eff>0)
  m <- ceiling(min(n/5,3*sqrt(n/r_eff)))
  log_scaled <- log_ratio-max(log_ratio)
  order <- order(log_scaled)
  valid <- m>=5L && m<n
  fit <- list(valid=FALSE,reason="too few tail draws")
  if(valid) {
    ids <- tail(order,m)
    threshold <- log_scaled[order[n-m]]
    # expm1 preserves small excesses close to the threshold.
    excess <- exp(log_scaled[ids])*(-expm1(threshold-log_scaled[ids]))
    fit <- fit_gpd_tail(excess)
    if(fit$valid) {
      p <- (seq_len(m)-.5)/m
      z <- -log1p(-p)
      q <- if(abs(fit$shape)<1e-9) fit$scale*z else
        fit$scale*expm1(fit$shape*z)/fit$shape
      log_scaled[ids] <- pmin(0,log(exp(threshold)+q))
    }
  }
  list(log_weight=log_scaled-logsumexp(log_scaled),
    shape=if(fit$valid) fit$shape else Inf,
    scale=if(fit$valid) fit$scale else NA_real_,valid=fit$valid,
    status=fit$reason,tail_length=m,
    diagnostic_threshold=min(.7,1-1/log10(n)))
}

The function stores each replacement log ratio in the original draw’s slot, so the corresponding weight is applied to the likelihood from that same parameter draw.

A nonfinite input log ratio fails the input check. With finite inputs, a tail shorter than five cannot support this fit. Constant ratios give zero excesses, and ties at the threshold can leave too few positive excesses for the grid. If the fit is unusable, the function normalizes the original ratios and returns valid=FALSE and shape=Inf. The status accompanies the predictive calculation. Retaining numerical weights in that case permits inspection of the raw estimate, while the infinite diagnostic flags the lack of a usable fitted tail. Here valid concerns the numerical tail fit, not posterior convergence or predictive adequacy. In particular, constant ratios give usable equal importance weights even though a Pareto tail cannot be fitted to their zero excesses.

Denote the resulting normalized weights by $\tilde w_{si}$. The PSIS estimate of person $i$’s leave-one-out log predictive density is $\log\sum_s\tilde w_{si}\exp(\ell_{si})$. Inside that sum, $\exp(\ell_{si})$ is still the marginal density of all four observed answers at the full-data draw. Reweighting changes how heavily each draw contributes to the prediction. Add the person-specific log scores to estimate the leave-one-out elpd for the sample. The fitted shape is useful at the same level of aggregation as the weight calculation. A heavy upper tail for one respondent can be obscured by summing predictive scores over all respondents.

1
2
3
4
5
6
7
8
9
10
psis_loo <- function(log_likelihood,r_eff=rep(1,ncol(log_likelihood))) {
  stopifnot(is.matrix(log_likelihood),length(r_eff)==ncol(log_likelihood))
  do.call(rbind,lapply(seq_len(ncol(log_likelihood)),function(j) {
    result <- psis_weights(-log_likelihood[,j],r_eff[j])
    data.frame(unit=j,
      log_predictive=logsumexp(result$log_weight+log_likelihood[,j]),
      k=result$shape,threshold=result$diagnostic_threshold,
      tail=result$tail_length,status=result$status)
  }))
}

Read k alongside threshold and status for every unit. The sample-size guideline is $\min\lbrace 1-1/\log_{10}S,0.7\rbrace $, equal to 0.7 for both sample sizes used here. An estimated shape above the guideline gives a reason to check the prediction by actually omitting that unit. The shape describes how well the full posterior supplies draws for that omission. An unusual response can receive a low predictive density even when its importance weights behave well. The guideline uses the nominal draw count; strongly dependent draws can make that choice too optimistic. It is a diagnostic recommendation, not a guarantee of a specified predictive error.

Two scalar checks with known omission distributions

Two normal examples check that distinction against leave-one-out predictions obtained by integration. Both use 10,000 independent posterior draws each, so $r_{\rm eff}=1$ and $M=300$ for both. First suppose observations have unit variance and unknown mean $\mu$ with prior $N(0,4)$. For any retained subset of $n$ responses the posterior variance is $v=(1/4+n)^{-1}$ and the mean is $m=v\sum y_j$. Integrating the sampling distribution over that posterior gives $N(m,1+v)$ for the omitted response. Draw the full-data posterior at seed 1609, use each observed value to form one log likelihood column, and compare PSIS with the corresponding analytic omission.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
RNGkind("Mersenne-Twister","Inversion","Rejection")
conjugate_y <- c(-1,-.5,0,.5,1,5)
posterior_normal <- function(y,prior_variance=4) {
  v <- 1/(1/prior_variance+length(y))
  c(mean=v*sum(y),variance=v)
}
set.seed(1609)
cond <- posterior_normal(conjugate_y)
draws <- rnorm(10000L,cond[1],sqrt(cond[2]))
scalar_ll <- vapply(conjugate_y,function(y) dnorm(y,draws,1,log=TRUE),
                    numeric(length(draws)))
exact <- vapply(seq_along(conjugate_y),function(i) {
  cond <- posterior_normal(conjugate_y[-i])
  dnorm(conjugate_y[i],cond[1],sqrt(1+cond[2]),log=TRUE)
},0.0)
print(cbind(waic(scalar_ll),psis_loo(scalar_ll)[,-1],exact=exact))
Omitted observationPSIS log predictive densityExact log predictive densityEstimated shape
−1−2.92727−2.934690.38530
−0.5−2.00731−2.012070.32804
0−1.38422−1.387070.27715
0.5−1.05803−1.059690.23522
1−1.02878−1.029920.22610
5−11.48896−11.506120.72162

The first five approximations differ from their exact values by less than 0.008. When the observation 5 is left out, the remaining observations sum to zero. Their predictive distribution has mean zero and variance $1+(5+1/4)^{-1}$. It assigns little density to 5. The full-data posterior has shifted toward that observation, and the estimated shape of 0.72162 exceeds the guideline.

For a second example, observe only zero and use a $N(0,100)$ prior on $\mu$. The full-data posterior variance is $v=100/101$ and the raw ratio is proportional to $\exp(\mu^2/2)$. Its survival probability beyond a large ratio $r$ is a normal tail beyond $\vert \mu\vert \approx\sqrt{2\log r}$, proportional asymptotically to $r^{-1/v}/\sqrt{\log r}$ up to a constant. The Pareto shape is therefore $100/101$, or 0.99010. Continue the random number stream with the next 10,000 independent draws.

1
2
3
4
companion <- rnorm(10000L,sd=sqrt(100/101))
heavy <- psis_weights(-dnorm(0,companion,1,log=TRUE))
print(c(k=heavy$shape,theoretical=100/101,threshold=heavy$diagnostic_threshold,
  exact_refit_predictive=dnorm(0,sd=sqrt(101),log=TRUE)))
1
2
3
4
                     k            theoretical              threshold 
              0.895125               0.990099               0.700000 
exact_refit_predictive 
             -3.226499 

Dropping the only observation restores the prior, so its exact predictive distribution is $N(0,101)$. The log density at zero is $-3.22650$. Here even a response at the prior mean gives a high shape estimate, 0.895125. Removing zero greatly increases uncertainty about $\mu$ without moving its mean.

Checking person-level predictions against a package and a refit

Return to the 150 respondents. Feed the same log densities and person-specific relative efficiencies to the book functions and to loo::loo(). The book’s psis_weights() follows the tail length and the Pareto fit of loo without sharing its code, so agreement shows that those settings were matched (Section E.3).

1
2
3
4
person_loo <- psis_loo(pointwise,eff)
ref_loo <- loo::loo(pointwise,r_eff=eff,cores=1L)
print(head(data.frame(waic_person,PSIS=person_loo$log_predictive,k=person_loo$k,
                      reference=ref_loo$pointwise[,"elpd_loo"])))
1
2
3
4
5
6
7
  unit      lppd     penalty      elpd      PSIS            k reference
1    1 -5.385622 0.064846527 -5.450469 -5.450501  0.015747221 -5.450501
2    2 -4.201977 0.019331235 -4.221308 -4.221312 -0.039047609 -4.221312
3    3 -4.533737 0.028551114 -4.562288 -4.562295 -0.005433264 -4.562295
4    4 -3.411623 0.009629134 -3.421252 -3.421253 -0.067913225 -3.421253
5    5 -6.514425 0.105088215 -6.619514 -6.619553  0.050530494 -6.619553
6    6 -3.791136 0.010240316 -3.801376 -3.801377 -0.026761866 -3.801377

In the first six rows, elpd contains the WAIC-corrected log scores and reference contains the package estimates from PSIS. For person one, the estimated shape is 0.016 and both PSIS calculations give a log score of $-5.45050$. Now use all 150 columns to find the largest discrepancies and compare the total scores.

1
2
3
4
5
6
7
print(c(largest_k=max(person_loo$k),largest_k_person=which.max(person_loo$k),
  k_above_0.5=sum(person_loo$k>.5),k_above_0.7=sum(person_loo$k>.7),
  PSIS_elpd=sum(person_loo$log_predictive),WAIC_elpd=sum(waic_person$elpd),
  loo_elpd=sum(ref_loo$pointwise[,"elpd_loo"]),
  largest_loo_difference=
    max(abs(person_loo$log_predictive-ref_loo$pointwise[,"elpd_loo"])),
  largest_k_difference=max(abs(person_loo$k-ref_loo$diagnostics$pareto_k))))
1
2
3
4
5
6
             largest_k       largest_k_person            k_above_0.5 
          2.109791e-01           2.700000e+01           0.000000e+00 
           k_above_0.7              PSIS_elpd              WAIC_elpd 
          0.000000e+00          -7.261596e+02          -7.261530e+02 
              loo_elpd largest_loo_difference   largest_k_difference 
         -7.261596e+02           1.580958e-13           3.914924e-14 

The summed PSIS elpd prints as $-726.1596$ in both calculations. The corresponding WAIC-corrected elpd is $-726.1530$. To report WAIC on its conventional deviance scale, multiply that corrected sum by $-2$.

The largest absolute difference between implementations is $1.58\times10^{-13}$ for an individual predictive log density and $3.91\times10^{-14}$ for a fitted shape. No person’s estimated shape exceeds even 0.5.

Person 27 has the largest shape, 0.211, so this person provides a concrete check on the full-data reweighting. Remove row 27 and fit the identical factor model to the other 149 respondents. Each of four refit chains discarded 1,000 sweeps and retained 20,000. At each refit draw use its loadings and unique variances to score row 27 with the factor already integrated out. The function below gives that calculation for one seed. Read the 80,000 saved log densities, average their exponentials on the log scale, and compare with the full-data PSIS estimate.

1
2
3
4
5
6
7
8
9
10
11
12
13
source("code/lib/factor_gibbs.R")
omitted_person <- which.max(person_loo$k)
prior <- bayes4_prior()
refit_log_densities <- function(seed) {
  fit <- bayes4_gibbs(Y[-omitted_person,,drop=FALSE],prior,seed)
  apply(fit$draws,1,function(p)
    bayes4_pointwise(Y[omitted_person,,drop=FALSE],p[1:4],p[5:8]))
}
seeds <- 1016190L+1:4
# To regenerate the saved vector: unlist(lapply(seeds,refit_log_densities))
v <- readRDS("data/derived/ch16/analysis.rds")$refit_person_log_density_draws
print(c(person=omitted_person,PSIS=person_loo$log_predictive[omitted_person],
        refit_log_predictive_density=logsumexp(v)-log(length(v))))
1
2
3
4
                      person                         PSIS 
                   27.000000                    -9.231922 
refit_log_predictive_density 
                   -9.238816 

For person 27, PSIS gives $-9.23192$ and the omission fit gives $-9.23882$. The PSIS estimate is higher by about 0.00689 log units. The omission fit uses Monte Carlo integration too, and the displayed results give no MCSE for this difference. Agreement with the package tests the smoothing calculation. The refit addresses the separate question of how closely reweighting the full-data draws approximates prediction from a posterior fitted without those four answers.

Prediction units and sources of uncertainty

A new observation need not belong to a new person. Suppose a group has already supplied responses $y_g$ and the question concerns a further measurement $y_g^\ast $ at a known occasion. Given parameters $\theta$, the available observations inform the group’s random effect through $p(b_g\mid y_g,\theta)$. Average $p(y_g^\ast \mid b_g,\theta)$ over this conditional distribution and then over parameter draws based on the available data, including $y_g$. If the group is new, the first integral uses the population distribution of its random effect. Specifying which responses will be available at prediction time determines which calculation to evaluate.

The same issue arises for a hidden Markov sequence. Adjacent observations depend through the latent state transitions. To forecast the next occasion for an existing sequence, filter the state distribution using responses up to the prediction time, propagate it through the transition matrix, and average the new response density over the resulting state probabilities. Conditioning on later observations answers an interpolation question. To predict an independent person’s whole sequence, use the sequence likelihood with all paths summed out.

Four kinds of variation enter these comparisons. A discrepancy between an observed covariance and those in replicated samples bears on whether the fitted response model reproduces that association. Monte Carlo error concerns how much a reported estimate changes with a finite sequence of posterior draws, including draws from an omission fit. Approximation error arises when WAIC’s correction or a smoothed importance distribution substitutes for fitting the model with a respondent left out. Finally, respondents differ in how predictable their answer patterns are. That variation across independent units matters when generalizing a difference in predictive scores to new respondents, even if every person’s score could be integrated exactly.

A replication that resembles the observed sample on three statistics provides evidence about those features. Establishing that the sampler explored its posterior still requires chain diagnostics and checks against known target distributions. In R, the loo package provides PSIS-LOO and WAIC for a matrix of pointwise log likelihoods.

Replicated weight trajectories under the observed schedule

Return to the ChickWeight model in Section 16.3. Its normal random intercept induces dependence among measurements from the same chick, and its fixed coefficients specify a quadratic mean trajectory for each diet. A posterior predictive check should preserve that dependence. To generate a new set of chicks at the observed diets and measurement times, draw population parameters from their joint posterior, draw one new intercept for each chick, and then generate all of its measurements using that intercept.

For posterior draw $s$, the replicate is

\[b_i^{\mathrm{rep},s}\sim N(0,\tau^{2,s}),\qquad y_{it}^{\mathrm{rep},s}=x_{it}^\top\beta^s+b_i^{\mathrm{rep},s} +\epsilon_{it}^{\mathrm{rep},s},\qquad \epsilon_{it}^{\mathrm{rep},s}\sim N(0,\sigma^{2,s}).\]

This prediction integrates over the population of chick effects. It does not condition on the fitted effect of an already observed chick. The observation schedule is fixed, so the calculation does not reproduce a process of dropout or death. Those would require additional modeling assumptions.

For each diet and time, compare the observed mean and variance with their distributions in replicated samples. Means examine the trajectory, while variances examine the shared variance structure. Each replicate uses the same measurement-to-chick mapping, so repeated measurements retain their modeled dependence.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
chick_cell <- interaction(chick$Diet, chick$Time, drop = TRUE, lex.order = TRUE)
chick_cell_rows <- split(seq_len(nrow(chick)), chick_cell)
chick_cell_metadata <- do.call(rbind, lapply(chick_cell_rows, function(rows)
  data.frame(Diet = as.character(chick$Diet[rows[1]]), Time = chick$Time[rows[1]], n = length(rows))))
chick_cell_statistics <- function(weight100) {
  means <- vapply(chick_cell_rows, function(rows) mean(weight100[rows]), 0.0)
  variances <- vapply(chick_cell_rows, function(rows) var(weight100[rows]), 0.0)
  c(means, variances)
}
chick_observed_statistics <- chick_cell_statistics(chick$weight100)
chick_predictive <- function(draws, seed) {
  set.seed(seed)
  chosen <- round(seq(1, nrow(draws), length.out = min(1000L, nrow(draws))))
  replicate_statistics <- matrix(NA_real_, length(chosen), length(chick_observed_statistics))
  negative_fraction <- numeric(length(chosen))
  for (s in seq_along(chosen)) {
    draw <- draws[chosen[s], ]
    beta <- draw[colnames(chick_X)]
    new_intercepts <- rnorm(chick_groups, sd = sqrt(draw["between_chick_variance"]))
    replicated <- drop(chick_X %*% beta) + new_intercepts[chick_group] +
      rnorm(nrow(chick), sd = sqrt(draw["residual_variance"]))
    replicate_statistics[s, ] <- chick_cell_statistics(replicated)
    negative_fraction[s] <- mean(replicated < 0)
  }
  list(statistics = replicate_statistics, negative_fraction = negative_fraction)
}

The factor chick_cell identifies a diet-and-time combination. The function chick_cell_statistics() places its means first and its variances second. The predictive function uses up to 1,000 posterior draws distributed across the pooled chains. Within a replicate, new_intercepts[chick_group] repeats the same generated chick effect at all its observed times. A separate normal error is generated for each measurement.

Apply the calculation under both priors. The table converts means to grams and variances to squared grams. It displays days 0, 10 and 21, while the saved cell table contains every observed time.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
chick_prediction <- list()
chick_prediction_tables <- list()
for (chick_prior_name in names(chick_chains)) {
  chick_pooled <- do.call(rbind, lapply(chick_chains[[chick_prior_name]], `[[`, "draws"))
  chick_predicted <- chick_predictive(chick_pooled, 160490L + match(chick_prior_name, names(chick_chains)))
  chick_bounds <- t(apply(chick_predicted$statistics, 2L, quantile, c(.025, .5, .975), names = FALSE))
  chick_cells <- nrow(chick_cell_metadata)
  chick_cell_table <- data.frame(prior = chick_prior_name, rbind(chick_cell_metadata, chick_cell_metadata),
    statistic = rep(c("mean_grams", "variance_grams_squared"), each = chick_cells),
    observed = chick_observed_statistics * rep(c(100, 10000), each = chick_cells),
    lower = chick_bounds[, 1] * rep(c(100, 10000), each = chick_cells),
    median = chick_bounds[, 2] * rep(c(100, 10000), each = chick_cells),
    upper = chick_bounds[, 3] * rep(c(100, 10000), each = chick_cells), row.names = NULL)
  chick_cell_table$outside_pointwise_interval <- chick_cell_table$observed < chick_cell_table$lower |
    chick_cell_table$observed > chick_cell_table$upper
  chick_prediction[[chick_prior_name]] <- chick_predicted
  chick_prediction_tables[[chick_prior_name]] <- chick_cell_table
}
chick_prediction_table <- do.call(rbind, chick_prediction_tables)
print(chick_prediction_table[chick_prediction_table$Time %in% c(0, 10, 21), ], row.names = FALSE)
print(aggregate(outside_pointwise_interval ~ prior + statistic,
                 chick_prediction_table, sum))
print(data.frame(prior = names(chick_prediction),
  mean_fraction_negative_weight = vapply(chick_prediction,
    function(x) mean(x$negative_fraction), 0.0)))
write.csv(chick_prediction_table, file.path("data/derived/ch16", "ch16-predictive-cells.csv"),
           row.names = FALSE)
saveRDS(chick_prediction, file.path("data/derived/ch16", "ch16-predictive.rds"))
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
            prior Diet Time  n              statistic     observed      lower     median      upper
             main    1    0 20             mean_grams   41.4000000  21.427219   40.74623   60.57754
             main    1   10 19             mean_grams   93.0526316  72.168274   91.71039  110.40358
             main    1   21 16             mean_grams  177.7500000 161.472362  181.27204  201.72618
             main    2    0 10             mean_grams   40.7000000   9.998649   38.95154   65.69998
             main    2   10 10             mean_grams  108.5000000  82.032754  108.42070  133.38230
             main    2   21 10             mean_grams  214.7000000 189.722661  218.31109  244.32890
             main    3    0 10             mean_grams   40.8000000   1.006802   28.53589   54.92997
             main    3   10 10             mean_grams  117.1000000  97.911541  126.50179  151.92569
             main    3   21 10             mean_grams  270.3000000 240.556348  266.84067  293.36966
             main    4    0 10             mean_grams   41.0000000  14.419041   41.33494   68.08782
             main    4   10 10             mean_grams  126.0000000  95.795296  120.98959  148.08430
             main    4   21  9             mean_grams  238.5555556 216.144745  242.23022  270.23707
             main    1    0 20 variance_grams_squared    0.9894737 537.891395 1095.79597 2027.73790
             main    1   10 19 variance_grams_squared  508.1637427 510.862459 1078.48379 2111.40731
             main    1   21 16 variance_grams_squared 3445.9333333 495.293417 1105.82425 2187.72640
             main    2    0 10 variance_grams_squared    2.2333333 319.179110 1055.07168 2555.42580
             main    2   10 10 variance_grams_squared  590.2777778 340.734633 1058.58513 2416.48914
             main    2   21 10 variance_grams_squared 6105.5666667 326.727323 1073.53560 2593.89556
             main    3    0 10 variance_grams_squared    1.0666667 350.526427 1102.61229 2550.85879
             main    3   10 10 variance_grams_squared  407.6555556 322.951732 1035.21371 2495.69334
             main    3   21 10 variance_grams_squared 5129.7888889 332.799932 1035.26971 2446.18630
             main    4    0 10 variance_grams_squared    1.1111111 342.287153 1019.36161 2376.01212
             main    4   10 10 variance_grams_squared  130.6666667 367.148991 1059.02927 2467.11408
             main    4   21  9 variance_grams_squared 1879.0277778 293.436863 1023.51479 2558.48133
 larger_variances    1    0 20             mean_grams   41.4000000  20.871918   41.19880   61.25489
 larger_variances    1   10 19             mean_grams   93.0526316  72.062484   92.05730  111.49690
 larger_variances    1   21 16             mean_grams  177.7500000 159.068585  181.08048  204.05245
 larger_variances    2    0 10             mean_grams   40.7000000  14.160847   39.13255   65.37824
 larger_variances    2   10 10             mean_grams  108.5000000  81.619520  108.05836  133.84547
 larger_variances    2   21 10             mean_grams  214.7000000 193.130416  218.47319  247.86853
 larger_variances    3    0 10             mean_grams   40.8000000   1.283839   27.54116   54.31742
 larger_variances    3   10 10             mean_grams  117.1000000  99.159437  126.06136  152.47242
 larger_variances    3   21 10             mean_grams  270.3000000 239.492851  266.65433  293.86527
 larger_variances    4    0 10             mean_grams   41.0000000  13.321184   42.44664   69.10873
 larger_variances    4   10 10             mean_grams  126.0000000  96.516492  121.95708  148.70082
 larger_variances    4   21  9             mean_grams  238.5555556 212.018761  243.43147  273.94589
 larger_variances    1    0 20 variance_grams_squared    0.9894737 534.577379 1145.12448 2179.87534
 larger_variances    1   10 19 variance_grams_squared  508.1637427 546.217597 1143.13872 2191.84897
 larger_variances    1   21 16 variance_grams_squared 3445.9333333 492.269245 1136.99332 2325.69062
 larger_variances    2    0 10 variance_grams_squared    2.2333333 363.676329 1110.73652 2596.54223
 larger_variances    2   10 10 variance_grams_squared  590.2777778 329.382322 1076.72518 2702.31147
 larger_variances    2   21 10 variance_grams_squared 6105.5666667 364.495464 1131.85564 2607.77182
 larger_variances    3    0 10 variance_grams_squared    1.0666667 338.898550 1131.29253 2696.73779
 larger_variances    3   10 10 variance_grams_squared  407.6555556 365.455523 1075.55932 2680.23852
 larger_variances    3   21 10 variance_grams_squared 5129.7888889 310.097771 1097.84965 2554.17743
 larger_variances    4    0 10 variance_grams_squared    1.1111111 346.724994 1109.83719 2664.47402
 larger_variances    4   10 10 variance_grams_squared  130.6666667 364.861969 1066.69756 2642.36348
 larger_variances    4   21  9 variance_grams_squared 1879.0277778 321.780919 1068.40100 2766.97181
 outside_pointwise_interval
                      FALSE
                      FALSE
                      FALSE
                      FALSE
                      FALSE
                      FALSE
                      FALSE
                      FALSE
                      FALSE
                      FALSE
                      FALSE
                      FALSE
                       TRUE
                       TRUE
                       TRUE
                       TRUE
                      FALSE
                       TRUE
                       TRUE
                      FALSE
                       TRUE
                       TRUE
                       TRUE
                      FALSE
                      FALSE
                      FALSE
                      FALSE
                      FALSE
                      FALSE
                      FALSE
                      FALSE
                      FALSE
                      FALSE
                      FALSE
                      FALSE
                      FALSE
                       TRUE
                       TRUE
                       TRUE
                       TRUE
                      FALSE
                       TRUE
                       TRUE
                      FALSE
                       TRUE
                       TRUE
                       TRUE
                      FALSE
             prior              statistic outside_pointwise_interval
1 larger_variances             mean_grams                          0
2             main             mean_grams                          0
3 larger_variances variance_grams_squared                         34
4             main variance_grams_squared                         34
                            prior mean_fraction_negative_weight
main                         main                    0.02425087
larger_variances larger_variances                    0.02496367

The lower and upper columns are pointwise 95% predictive bounds for each summary. They describe replicated sample means or variances, rather than credible intervals for a parameter. The count of summaries outside these bounds helps locate discrepancies, but it is not a calibrated overall test: many related summaries are examined, and the same data were used to estimate the model.

All 48 observed diet-by-time means fall within their pointwise predictive intervals under both priors, but 34 of the 48 variances fall outside. The discrepancy is substantial at birth: the four observed variances are approximately 1 to 2 squared grams, while the main-prior predictive medians are about 1,019 to 1,103 squared grams. By day 21, the observed variances for diets 1 through 3 instead exceed their predictive upper bounds. The constant marginal variance $\tau^2+\sigma^2$ cannot reproduce this change in dispersion over time. The mean comparisons therefore do not establish an adequate longitudinal covariance model.

The mean fraction of negative replicated measurements is about 2.43 percent under the main prior and 2.50 percent under the alternative prior. These physically impossible values are another limitation of the fitted normal model. Increasing the prior variance scales leaves both predictive discrepancies largely unchanged. Random slopes or time-dependent residual variances would be substantive alternatives to examine; the present calculation does not fit those alternatives or change the Chapter 8 example.

If leave-one-out prediction were added for a new chick, the independent prediction unit would be the whole chick trajectory. Its likelihood contribution would integrate over that chick’s random intercept. Omitting one measurement while estimating the same chick’s effect from its other measurements would target a different prediction problem.

16.10 Verifying samplers with analytic posteriors and simulation-based calibration

This section checks the chapter’s samplers against known answers. It begins with posteriors whose values are known analytically and with agreement between samplers, then uses simulation-based calibration to check the factor-model computation across datasets generated from the prior and investigates a calibration failure for the first loading. It ends with prior sensitivity in the simulated and observed examples and a summary of what these checks establish.

Reference values and agreement between samplers

If a sampler gives a plausible mean for a factor loading, which parts of the calculation has that number checked? Start with distributions for which particular steps have known answers. With five independent normal measurements of unit variance and a $N(0,4)$ prior on their mean, the posterior precision is $5+1/4$. Multiplying the sum of the observations by its reciprocal gives the posterior mean. These two numbers check the weights given to data and prior and the scale of the simulated variation. In a Gibbs update of a residual variance, the sum of squared errors changes the rate for its reciprocal. Comparing draws with quantiles of the corresponding inverse gamma distribution checks both the rate and the inversion. A truncated normal probability checks a different operation, the placement of the latent response on the side of the threshold selected by the observed category. For a correlated normal pair, the marginal variances can be right even when the covariance is wrong. Compare the sampled cross-product about the means of the target distribution with the known covariance. For a binomial intercept with two successes in ten trials, numerical quadrature gives a posterior mean of $-1.32742$ and SD of 0.74599 against which to check either an augmentation or a Metropolis update. Each comparison concerns a quantity with a reference value obtained independently of the chain.

For the 150 respondents in BAYES4, the full posterior has no comparable analytic solution. The population parameters can nevertheless be estimated with a Gibbs sampler that draws the person factors, a Metropolis random walk that integrates them out, or Hamiltonian Monte Carlo with the factors included. Compare the same original-scale parameter under the same prior. For the first loading, the Gibbs mean was 0.78006 with Monte Carlo standard error (MCSE) 0.000608. Two of the four chains of the default No-U-Turn sampler (NUTS) remained in a region with a first loading near zero, and the pooled NUTS mean of 0.39542 has $\widehat R=1.733$; it is not an estimate to compare with the Gibbs mean. For the second unique variance, which takes similar values in both regions, the Gibbs and NUTS means were 0.54636 and 0.54647. The difference divided by the square root of the sum of the squared MCSEs is about 0.1. Agreement on one parameter gives little information about the precision of a different parameter. The marginal block random walk had a maximum split $\widehat R$ of 1.036 and minimum bulk effective sample size of 207. Use its draws to compare movement per proposal. Its precision limits its value as a reference fit. The Laplace approximation uses local curvature and the variational fit restricts the family of distributions. A narrow interval from either approximation raises a question about its representation of posterior uncertainty.

Several samplers of this chapter are translations of package programs: factor_gibbs(), random_coefficient_gibbs() with inverse_wishart_draw(), probit_gibbs(), ordinal_factor_gibbs(), adaptive_random_walk() and the relabeling ecr_permutations() (code/NOTICE.md). The reference script code/checks/ch16_reference.R runs each source program with the chapter’s seeds or random number streams and prints the largest absolute difference between the two sets of draws; for the relabeling it counts the draws on which the two choose different permutations. A difference of zero, or one of the size of rounding error, shows that the translation repeats the program’s arithmetic and its use of random numbers. It does not check the source program itself. The mixed-model sampler can differ by rounding because the two programs solve the mixed model equations in different orders.

On the macOS computer with an ARM processor that produced this chapter’s results, the item samplers are the exception. Across the four chains, the largest absolute differences from the draws of MCMCirtKd range from 1.09 to 1.31, and those from MCMCordfactanal range from 0.99 to 1.17. On a Linux computer with an x86-64 processor, both differences are zero, and the item draws of MCMCpack itself differ between the two computers. The difference therefore lies in the floating-point arithmetic of the compiled package on the two computers, not in the translation. In the item chains each draw depends on all earlier ones, so a difference in the last digits of one update is carried into every later draw and can grow over the iterations. The other comparisons on the macOS computer remain at the size of rounding error or zero: at most $2.8\times10^{-13}$ for MCMCprobit, $3.6\times10^{-15}$ for MCMCfactanal, $1.5\times10^{-11}$ for MCMCglmm and $1.6\times10^{-14}$ for adaptMCMC, with no draws on which the relabeling programs choose different permutations.

Ranks across prior-predictive datasets

Simulation-based calibration (SBC) extends the comparison to a model whose posterior is known only through computation. Draw $\theta^\ast $ from a proper prior and simulate observations $Y^\ast $ from the sampling model at that parameter. Fit the model to those observations. Why should the generating value have an ordinary rank among draws from the resulting posterior? Conditional on $Y^\ast =y$, Bayes’ rule assigns $\theta^\ast $ the density $p(\theta\mid y)$. Conditional on the same $y$, an exact independent sampler draws each $\theta^{(s)}$ from that density without using $\theta^\ast $. The generating value and the $L$ simulated values are then exchangeable. For a continuous scalar quantity $h(\theta)$, each of the $L+1$ positions of $h(\theta^\ast )$ in their ordering has probability $1/(L+1)$. A histogram needs many independent datasets because each fit supplies only one rank per quantity. For a discrete quantity, count the draws strictly below the generating value and add a uniform random integer from zero through the number of ties. This places the generating value at random among equal values. The continuous examples use a strict inequality. With dependent draws, even correct posterior marginals do not by themselves give the exchangeable ordering used in this derivation.

Two experiments use a single chain of the book’s NUTS sampler per dataset. In the first, a normal mean and five observations are drawn. In the second, fresh population parameters are drawn and four responses are generated for each of 30 new people. The first loading is positive in the generator and in the fitted model. The fitted target is bayes4_target(Y,prior,TRUE,TRUE) for the simulated responses, a four-dimensional normal response with covariance $\lambda\lambda^\top+\operatorname{diag}(\psi)$. Each person’s factor has been integrated out. The joint fit to the observed 150-person sample included those factors as parameters. The function calibration_replication() in code/lib/calibration.R sets one dataset’s seed, simulates the generating values and the observations, and runs the fit on the same random stream.

1
2
3
4
5
6
7
8
9
10
11
12
calibration_replication <- function(seed, simulate, fit) {
  RNGkind("Mersenne-Twister", "Inversion", "Rejection")
  set.seed(seed)
  generated <- simulate()
  result <- tryCatch(fit(generated$data), error = function(e) e)
  if (inherits(result, "error"))
    return(list(seed = seed, completed = FALSE, reason = conditionMessage(result), truth = generated$truth,
      data = generated$data))
  above <- 1L * sweep(result$draws[, names(generated$truth), drop = FALSE], 2, generated$truth, ">")
  list(seed = seed, completed = TRUE, reason = "", truth = generated$truth, data = generated$data, above = above,
    diagnostics = result$diagnostics)
}

The matrix above records, for each retained draw and generating value, whether the draw exceeds the generating value. The following calls from the book directory give the repeated fits. The chain uses 1,000 warmup and 1,000 retained iterations.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
.libPaths(c(".R-library", .libPaths()))
for (f in c("bayes_factor","boundary_test","nuts","calibration"))
  source(paste0("code/lib/",f,".R"))
prior <- bayes4_prior()
sbc_record <- function(simulate,fit,M) {
  runs <- lapply(calibration_seeds(M),calibration_replication,simulate=simulate,fit=fit)
  done <- vapply(runs,`[[`,TRUE,"completed")
  columns <- cumsum(done); columns[!done] <- NA_integer_
  list(above=lapply(runs[done],`[[`,"above"),
    truth=do.call(cbind,lapply(runs[done],`[[`,"truth")),
    diagnostics=simplify2array(lapply(runs[done],`[[`,"diagnostics")),
    data=lapply(runs,`[[`,"data"),
    replication_map=data.frame(replication=seq_along(runs),seed=calibration_seeds(M),completed=done,
      reason=vapply(runs,`[[`,"","reason"),result_column=columns))
}
one_chain <- function(target,dimension,report) {
  fit <- hamiltonian_chain(target,dimension,report)
  list(draws=fit$draws,diagnostics=fit$diagnostics)
}
normal_sbc <- sbc_record(function() {
  theta <- rnorm(1,0,2)
  list(truth=c(theta=theta),data=rnorm(5,theta,1))
},function(y) one_chain(list(value=function(u)dnorm(u,0,2,log=TRUE)+sum(dnorm(y,u,1,log=TRUE)),
  gradient=function(u)-u/4+sum(y-u)),1L,function(u)c(theta=u)),200L)
sbc_factor_data <- list(N=30L,loading_sd=prior$loading_sd,shape=prior$shape,rate=prior$rate)
calibration_names <- c(paste0("loading",1:4),paste0("variance",1:4))
factor_parameters <- function(s) setNames(c(s$loading,s$variance),calibration_names)
factor_sbc <- sbc_record(function() {
  loading <- c(abs(rnorm(1,0,prior$loading_sd)),rnorm(3,0,prior$loading_sd))
  variance <- 1/rgamma(4,prior$shape,prior$rate)
  Y <- t(vapply(seq_len(sbc_factor_data$N),function(i) rnorm(4,rnorm(1)*loading,sqrt(variance)),numeric(4)))
  list(truth=setNames(c(loading,variance),calibration_names),data=Y)
},function(Y) one_chain(bayes4_target(Y,prior,TRUE,TRUE),8L,
  function(u)factor_parameters(bayes4_unpack(u))),200L)

For each experiment, calibration_seeds() spaces the 200 seeds evenly over the integer range from zero to the largest positive R integer, with integer conversion.

1
calibration_seeds <- function(datasets) as.integer(seq(0, .Machine$integer.max, length.out = datasets))

The generating values come first: the normal mean, or the four loadings with a positive first loading followed by the four unique variances. Each of the 30 people then receives a factor and four responses. The saved replication_map links each attempted dataset to its seed and result column; failed fits retain their original dataset numbers, and data contains every simulated dataset.

Ranks count the indicators in above over selected draws.

1
2
3
4
5
sbc_ranks <- function(record,thin=3L) {
  kept <- seq(1L,nrow(record$above[[1]]),by=thin)
  do.call(rbind,lapply(record$above,function(r)1L+colSums(r[kept,,drop=FALSE])))
}
sbc_divergences <- function(record) apply(record$diagnostics,3L,function(s)sum(s[,"divergent"]))

Adding the indicators at iterations 1, 4 and so on through 1,000 counts 334 comparisons. Adding one gives ranks from 1 through 335. Thus rank 1 places the generating value above all the selected draws when there are no ties. Spacing the draws can reduce their dependence. A chain confined to one region still supplies draws from that region at any spacing. The independent normal calculation below uses the opposite ordering and starts its count at zero. Neither a spacing of three nor a spacing of ten establishes independence of the retained values.

Constructing and reading calibration ranks

A calibration plot needs a reference that accounts for the finite number of possible ranks. Let $x$ be the zero-based rank plotted on the horizontal axis and $K$ the number of possible ranks. Under the uniform reference, $F(x)=(x+1)/K$. At each grid point, subtract this value from the fraction of datasets with rank at or below $x$. A positive difference means there are more low ranks than expected. For a ten-bin histogram, count how many grid points fall in each bin. When $K=335$, the first bin has 34 points and the second has 33. They have different expected counts even under exact uniformity. For a single bin of probability $p$, the count from 200 independent datasets has the binomial distribution with size 200 and probability $p$. Figure 16.2 uses its central 95 percent limits for each bin. For the cumulative distribution function (CDF), simulate 1,000 sets of uniform ranks and take the largest absolute CDF difference within each set. The 950th ordered maximum estimates a simultaneous 95 percent reference band across the rank grid for that one quantity. The simulations start at seed 16101 and continue in panel order. Discrete binomial quantiles generally give coverage of at least the nominal level. The CDF band concerns one quantity’s rank grid; it is not a simultaneous band for every parameter or panel.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
rank_table <- function(r,support) {
  # Equal-width plotted bins can hold different numbers of possible ranks.
  labels <- pmin(10L,1L+floor(10*r/support))
  pr <- tabulate(pmin(10L,1L+floor(10*(0:(support-1L))/support)),10L)/support
  data.frame(bin=1:10,observed=tabulate(labels,10L),expected=length(r)*pr,
    lower=qbinom(.025,length(r),pr),upper=qbinom(.975,length(r),pr))
}
rank_figures <- function(series) {
  r <- series[[1]]; support <- series[[2]]
  probabilities <- seq_len(support)/support
  N <- length(r)
  envelope <- replicate(1000L,{
    counts <- tabulate(sample.int(support,N,replace=TRUE),support)
    max(abs(cumsum(counts)/N-probabilities))
  })
  list(table=rank_table(r,support),
    cdf_difference=cumsum(tabulate(r+1L,support))/N-probabilities,
    band=unname(quantile(envelope,.95,type=1)),replications=N,support=support)
}

In the independent normal check, the rank is the number of 100 draws below the generating mean, so zero and 100 are both possible. For each dataset, use the same 100 standard normal variates twice. First scale them by the analytic posterior SD and add its mean. Then halve that SD about the same mean, reducing the variance to one quarter. The supplied quarter_variance_rank() performs this second transformation using the same standard normal draws and counts how many results lie below the generating value.

1
2
3
quarter_variance_rank <- function(mean, variance, standard_draws, truth) {
  sum(mean+.5*sqrt(variance)*standard_draws<truth)
}

Pairing the draws makes the source of the change explicit. Use separate random number streams for the 200 datasets.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
source("code/lib/boundary_test.R")
source("code/checks/ch16_sbc_variance.R")
RNGkind("L'Ecuyer-CMRG","Inversion","Rejection")
set.seed(101610)
sbc_streams <- replicate_streams(200L,.Random.seed)
posterior_normal <- function(y,prior_variance=4) {
  v <- 1/(1/prior_variance+length(y))
  c(mean=v*sum(y),variance=v)
}
exact_ranks <- function(streams) {
  lapply(streams,function(stream) {
    assign(".Random.seed",stream,envir=.GlobalEnv)
    theta <- rnorm(1,sd=2)
    y <- rnorm(5,theta)
    cond <- posterior_normal(y)
    z <- rnorm(100)
    sampled <- cond[1]+sqrt(cond[2])*z
    list(rank=sum(sampled<theta),
         second_rank=quarter_variance_rank(cond[1],cond[2],z,theta))
  })
}
normal_exact <- exact_ranks(sbc_streams)
extremes <- function(r) {
  tail <- r<=4L | r>=96L
  c(extreme_fraction=mean(tail),
    MCSE=sqrt(mean(tail)*(1-mean(tail))/length(tail)),B=length(r))
}
print(rbind(correct=extremes(vapply(normal_exact,function(s)s$rank,0.0)),
  quarter_variance=extremes(vapply(normal_exact,function(s)s$second_rank,0.0))))
1
2
3
                 extreme_fraction       MCSE   B
correct                     0.075 0.01862458 200
quarter_variance            0.385 0.03440748 200

Ranks 0 through 4 and 96 through 100 cover ten of the 101 possible values. The observed fraction in both tails together was 0.075 with MCSE 0.019 under exact sampling. The MCSE uses the variation of a tail indicator across independent datasets. Narrowing the posterior raised the fraction to 0.385 with MCSE 0.034. Generating values fall beyond either end of the shortened intervals too often, giving the U-shaped histogram. Calculate a separate reference band for each series in figure order. The same five results are available in rank_displays in data/derived/ch16/analysis.rds.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
normal_nuts_ranks <- sbc_ranks(normal_sbc)
factor_nuts_ranks <- sbc_ranks(factor_sbc)
rank_support <- 1L+length(seq(1L,nrow(normal_sbc$above[[1]]),by=3L))
rank_series <- list(normal_exact=list(vapply(normal_exact,function(r)r$rank,0.0),101L),
  normal_quarter_variance=list(vapply(normal_exact,function(r)r$second_rank,0.0),101L),
  normal_NUTS=list(normal_nuts_ranks[,1]-1,rank_support),
  first_loading=list(factor_nuts_ranks[,1]-1,rank_support),
  first_unique_variance=list(factor_nuts_ranks[,5]-1,rank_support))
set.seed(16101)
rank_displays <- lapply(rank_series,rank_figures)
print(t(vapply(rank_displays,function(d)
  c(largest_cdf_difference=max(abs(d$cdf_difference)),
    band=d$band,
    bins_outside=sum(d$table$observed<d$table$lower|d$table$observed>d$table$upper)),
  numeric(3))))
1
2
3
4
5
6
                        largest_cdf_difference       band bins_outside
normal_exact                        0.06866337 0.09074257            1
normal_quarter_variance             0.21148515 0.09306931            6
normal_NUTS                         0.03664179 0.09365672            1
first_loading                       0.20201493 0.09164179            2
first_unique_variance               0.19164179 0.09500000            2

Rank bins and cumulative deviations for three normal calculations, the first loading and the first unique variance.

Figure 16.2. Each row summarizes 200 datasets. On the left, bars count datasets and circles mark the expected counts. On the right, dashed horizontal lines bound the maximum absolute deviation over ranks for that row. The narrowed normal posterior produces excess rank counts at both ends. The first loading has a large excess at the low end and the first unique variance at the high end.

The exact-normal deviation of 0.0687 is inside its band of 0.0907, although one bin is outside its pointwise limits. The normal NUTS run gives 0.0366 against 0.0937, also with one bin outside. For the quarter-variance draws, the deviation of 0.2115 exceeds 0.0931 and six bins are outside. These data show how an accurately located posterior mean can coexist with poorly calibrated uncertainty.

Investigating the factor calibration failure

For the first factor loading, 41 of the 200 generating values exceeded every selected NUTS draw. The first bin contains 58 datasets against an expected 20.3 and an upper pointwise limit of 29. Indeed, at stored rank 1 alone the cumulative difference is $41/200-1/335=0.2020$. This is also the largest difference across ranks, well beyond the simultaneous band of 0.0916. Compare this rank evidence with the divergence records from the normal and factor fits.

1
2
3
4
5
6
print(rbind(normal=c(fits=length(normal_sbc$above),
  with_divergences=sum(sbc_divergences(normal_sbc)>0),
  divergences=sum(sbc_divergences(normal_sbc))),
  factor=c(fits=length(factor_sbc$above),
  with_divergences=sum(sbc_divergences(factor_sbc)>0),
  divergences=sum(sbc_divergences(factor_sbc)))))
1
2
3
       fits with_divergences divergences
normal  200                0           0
factor  200                0           0

Counting divergent transitions finds none in either the normal or the factor fits. That count alone would miss the discrepancy in the loading ranks entirely.

Select the first completed dataset with rank 1 and recover its original number and seed from replication_map. The record saves the simulated response matrix itself. Pass this fixed matrix to the marginal factor model for all four chains of the book’s NUTS sampler, seeded with the dataset’s calibration seed. The generating parameters remain those saved with the same result column. Compare the chain means of the loadings and of the log density in sampling coordinates.

1
2
3
4
5
6
7
8
factor_nuts_ranks <- sbc_ranks(factor_sbc)
column <- which(factor_nuts_ranks[,1]==1L)[1L]
run_info <- subset(factor_sbc$replication_map, !is.na(result_column) & result_column==column)
observed <- factor_sbc$data[[run_info$replication]]
stopifnot(identical(dim(observed),c(30L,4L)))
fit <- hamiltonian_chains(bayes4_target(observed,prior,TRUE,TRUE),8L,bayes4_report,run_info$seed)
cols <- c(paste0("loading[",1:4,"]"),"log_density")
print(rbind(truth=c(factor_sbc$truth[1:4,column],log_density=NA),apply(fit$draws[,,cols],c(2,3),mean)))
1
2
3
4
5
6
         loading1  loading2  loading3   loading4 log_density
truth  2.20146861  3.600754  1.905094 -0.4911934          NA
chain1 1.86091600  3.262962  1.968003 -0.4971295   -201.8447
chain2 0.07141015 -3.250009 -2.042737  0.4823404   -235.8487
chain3 0.07274891 -3.264673 -2.050579  0.4833662   -235.9553
chain4 1.85825082  3.263166  1.960950 -0.4932177   -201.6316

The generating first loading was 2.201. Chains one and four averaged about 1.861 and 1.858. In chains two and three it averaged about 0.071 and 0.073, with the other three loadings reversed in sign relative to their generating values. Those two chains had mean log densities near $-235.9$, about 34 below the $-201.84$ and $-201.63$ in chains one and four. These observations locate a region visited by two chains. Establishing a second local maximum would require information about the density near a candidate maximum, and estimating regional posterior probabilities would require sampling their relative probabilities. The ranks have already identified a failure of this fitting procedure for these simulated data.

Comparing rank patterns at different draw spacings

Does the choice of spacing account for the pattern? Read the indicators for all 200 factor datasets and the 200 assigned Gibbs records from calibration-pairs.rds. Form the NUTS ranks at both spacings before restricting the data to pairs of completed fits. Every tenth draw gives 100 comparisons instead of 334, so recompute each bin’s reference probability on the corresponding grid.

1
2
3
4
5
6
7
8
9
10
11
12
calibration <- readRDS("data/derived/ch16/calibration-pairs.rds")
sbc <- calibration$sbc
records <- calibration$gibbs
parameters <- c(paste0("loading", 1:4), paste0("variance", 1:4))
ranks_at_spacing <- function(spacing) {
  keep <- seq.int(1L, nrow(sbc$above[[1L]]), by = spacing)
  successful <- do.call(rbind, lapply(sbc$above, function(r) 1L + colSums(r[keep, , drop = FALSE])))
  ranks <- matrix(NA_real_, nrow(sbc$replication_map), ncol(successful))
  ids <- which(sbc$replication_map$completed)
  ranks[ids, ] <- successful[sbc$replication_map$result_column[ids], , drop = FALSE]
  ranks
}

Summarize extreme rank counts, histogram departures and cumulative discrepancies for each parameter. To compare the two spacings, count the outlying bins separately for each parameter and sum those counts.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
rank_summary <- function(ranks, support) {
  ranks <- ranks[is.finite(ranks)]
  n <- length(ranks)
  if (!n) return(c(rank_one = NA_real_, bins_outside = NA_real_, largest_cdf_gap = NA_real_))
  bin <- function(rank) 1L + floor(10 * (rank - 1L) / support)
  probability <- tabulate(bin(seq_len(support)), 10L) / support
  observed <- tabulate(bin(ranks), 10L)
  outside <- observed < qbinom(.025, n, probability) |
    observed > qbinom(.975, n, probability)
  difference <- cumsum(tabulate(ranks, support)) / n - seq_len(support) / support
  c(rank_one = sum(ranks == 1L), bins_outside = sum(outside), 
    largest_cdf_gap = max(abs(difference)))
}
# First examine spacing in all 200 datasets, preserving the discrete uniform reference.
spacing_check <- vapply(c(3L, 10L), function(spacing) {
  ranks <- ranks_at_spacing(spacing)
  support <- 1L + length(seq.int(1L, nrow(sbc$above[[1L]]), by = spacing))
  sum(apply(ranks, 2L, rank_summary, support = support)["bins_outside", ])
}, numeric(1))
print(setNames(spacing_check, c("every_third", "every_tenth")))
1
2
every_third every_tenth 
         17          14 

The function rank_summary() takes one parameter’s ranks, numbered from one through support, and removes unavailable ranks before setting the dataset count for its binomial reference. It returns the number of ranks equal to one, the number of bins outside their pointwise limits and the largest absolute CDF discrepancy. The two displayed totals sum these bin counts across parameters.

Every third draw, with a high first bin for loading one and a low cumulative curve for variance one at upper ranks.

Every tenth draw, with a similar excess in the first loading bin on a shorter rank grid.

Figure 16.3. The upper and lower panels use every third and every tenth draw, respectively. Each parameter has a histogram of dataset counts and a curve of cumulative probability differences against rank minus one. Both sets of dotted limits are pointwise 95 percent binomial limits. They bound individual counts or cumulative probabilities at a specified rank.

The supplied draw_factor_ranks() draws one page of figures/ch16/factor-calibration-ranks.pdf per spacing. Of the 80 bins across eight parameters in Figure 16.3, 17 are outside at spacing three and 14 at spacing ten. The count of outlying bins across eight parameters is descriptive; the pointwise limits do not make it a single 5 percent test.

Comparing NUTS and Gibbs on the same datasets

To compare samplers, give each the very same observations and the same number of draws for ranking. The record saves each simulated 30-by-four response matrix in data. The function below describes how each saved Gibbs fit was obtained, including the record retained if the constrained loading could not be drawn within the allowed number of attempts.

1
2
3
4
5
6
7
8
9
source("code/lib/factor_gibbs.R")
source("code/lib/bayes_factor.R")
mapping <- sbc$replication_map
truth <- matrix(NA_real_,8L,nrow(mapping))
truth[,mapping$replication[mapping$completed]] <- sbc$truth
N <- 30L
prior <- bayes4_prior()
seeds <- as.integer(seq(0,.Machine$integer.max,length.out=200L))
stopifnot(identical(seeds,mapping$seed))
1
2
3
4
5
6
7
8
9
10
11
12
13
14
fit_dataset <- function(id) {
  column <- mapping$result_column[id]
  if (is.na(column)) return(list(id=id, stopped="calibration_fit_failed",
    rank=rep(NA_integer_,8L),kept=334L,mean=rep(NA_real_,8L),sd=rep(NA_real_,8L)))
  Y <- sbc$data[[id]]
  stopifnot(identical(dim(Y),c(N,4L)))
  fit <- tryCatch(bayes4_gibbs(Y,prior,seeds[id],max_redraws=1e6),error=conditionMessage)
  if(is.character(fit)) return(list(id=id,stopped=fit,rank=rep(NA_integer_,8L),kept=334L,
    mean=rep(NA_real_,8L),sd=rep(NA_real_,8L)))
  draws <- fit$draws
  kept <- draws[seq(1L,nrow(draws),by=60L),,drop=FALSE]
  list(id=id,stopped="",rank=1L+colSums(sweep(kept,2,truth[,id],">")),kept=nrow(kept),
    mean=colMeans(draws),sd=apply(draws,2,sd))
}

The Gibbs fit uses 1,000 burn-in sweeps and 20,000 retained sweeps. Taking draws 1, 61 and so on through 19,981 gives 334. Datasets 10, 159 and 197 stopped at sweeps 9, 7 and 8 after a million attempts to draw the first loading. Their records identify the stop and have missing ranks. These Gibbs runs are already stored in records, read above from calibration-pairs.rds. The next calculation summarizes those records and applies one completion indicator to both rank matrices after checking their supports.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
finished <- sbc$replication_map$completed & !vapply(records, function(r) nzchar(r$stopped), logical(1))
print(table(finished))
print(which(!finished))
nuts_rank <- ranks_at_spacing(3L)
gibbs_rank <- do.call(rbind, lapply(records, function(r) r$rank))
support <- records[[1L]]$kept + 1L
stopifnot(all(vapply(records, function(r) r$kept == support - 1L, logical(1))),
          support == length(seq.int(1L, nrow(sbc$above[[1L]]), by = 3L)) + 1L)
nuts_summary <- apply(nuts_rank[finished, , drop = FALSE], 2L, rank_summary, support = support)
gibbs <- apply(gibbs_rank[finished, , drop = FALSE], 2L, rank_summary, support = support)
paired <- data.frame(parameter = parameters, NUTS_rank_1 = nuts_summary["rank_one", ],
  Gibbs_rank_1 = gibbs["rank_one", ], NUTS_bins_outside = nuts_summary["bins_outside", ],
  Gibbs_bins_outside = gibbs["bins_outside", ],
  NUTS_largest_cdf_gap = nuts_summary["largest_cdf_gap", ],
  Gibbs_largest_cdf_gap = gibbs["largest_cdf_gap", ], datasets = sum(finished))
print(paired, row.names = FALSE)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
finished
FALSE  TRUE 
    3   197 
[1]  10 159 197
 parameter NUTS_rank_1 Gibbs_rank_1 NUTS_bins_outside Gibbs_bins_outside
  loading1          40            3                 2                  0
  loading2          23            5                 4                  1
  loading3          23            4                 4                  0
  loading4          27            4                 3                  2
 variance1           1            1                 3                  0
 variance2           1            1                 0                  0
 variance3           2            0                 0                  0
 variance4           0            0                 0                  0
 NUTS_largest_cdf_gap Gibbs_largest_cdf_gap datasets
           0.20006061            0.06294416      197
           0.13949542            0.08215774      197
           0.12093340            0.04800364      197
           0.14602621            0.05094325      197
           0.19143875            0.06770210      197
           0.05845897            0.05697401      197
           0.05591333            0.05567088      197
           0.02636563            0.04024547      197

Among the 197 completed pairs, Gibbs had three first-loading ranks of one, zero bins outside their limits and a maximum CDF difference of 0.06294. NUTS had 40, two and 0.20006 on the same datasets. For the first unique variance NUTS has three bins outside and Gibbs none; for the other three unique variances neither method has a bin outside. This comparison conditions on both fits finishing; it does not establish calibration over all 200 assigned fits. The spacing plots also include the NUTS fits to datasets 10, 159 and 197.

Prior sensitivity in the simulated factor sample

Calibration generates new populations under a specified prior. Prior sensitivity poses a different question for the 150 people in BAYES4. Fit the same response model with loading priors $N(0,100)$, restricted to positive values for the first loading, and independent $IG(0.1,0.1)$ priors for the unique variances. This is an alternative prior specification, not a generally less informative one. The loading prior is wider, but $IG(0.1,0.1)$ changes both the behavior near zero and the upper tail and has no finite mean. Whether that change weakens relevant prior information depends on the response scale and the quantities being estimated. Compare the two posterior means with the unpenalized likelihood estimate.

Write $T=Y^\top Y$ and $P=\Sigma^{-1}$, where $\Sigma=\lambda\lambda^\top+\operatorname{diag}(\psi)$. Differentiating the negative log likelihood as a function of the covariance matrix gives $K=(NP-PTP)/2$. This gives derivatives $2K\lambda$ for the loadings and $\operatorname{diag}(K)$ for the variances. The diagonal matrix $J$ converts changes in the eight optimization coordinates to changes on the reporting scale. Its entries are one for an untransformed loading and the corresponding parameter for a log coordinate. Differentiating $P$ gives $dP=-P(d\Sigma)P$. Differentiate both $K$ and $J$ to obtain each column of the Hessian $H$ in optimization coordinates. On the original scale, $JH^{-1}J^\top$ gives a local large-sample covariance approximation. Take the square root of each diagonal element to obtain its standard error. Evaluate these quantities at the saved optimizer endpoint.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
Y <- readRDS("data/source/ch16/BAYES4.rds")
old <- readRDS("data/derived/ch16/analysis.rds")$ML
N <- nrow(Y)
T <- crossprod(Y)
evaluate <- function(u) {
  b <- bayes4_unpack(u)
  l <- b$loading
  v <- b$variance
  S <- tcrossprod(l)+diag(v)
  P <- chol2inv(chol(S))
  K <- (N*P-P%*%T%*%P)/2
  J <- diag(c(l[1],1,1,1,v))
  g <- c(2*K%*%l,diag(K))
  H <- sapply(1:8,function(k) {
    dl <- J[1:4,k]
    dv <- J[5:8,k]
    dS <- tcrossprod(dl,l)+tcrossprod(l,dl)+diag(dv)
    dP <- -P%*%dS%*%P
    dK <- (N*dP-dP%*%T%*%P-P%*%T%*%dP)/2
    dJ <- if(k %in% c(1,5:8)) J[,k]*g else numeric(8)
    drop(J%*%c(2*(dK%*%l+K%*%dl),diag(dK)))+dJ
  })
  list(g=drop(J%*%g),H=H,is_free=c(l,v),se=sqrt(diag(J%*%solve(H)%*%J)),
       loglik=-.5*(N*(4*log(2*pi)+2*sum(log(diag(chol(S)))))+sum(P*T)))
}
b <- evaluate(old$par)
print(c(loglik=b$loglik,finite_difference=max(abs(old$gradient)),
        analytic=max(abs(b$g)),min_information=min(eigen(b$H,symmetric=TRUE)$values)))

The function evaluate() returns the gradient g and Hessian H in optimization coordinates, together with the marginal loglik and the standard errors se on the reporting scales. Its field is_free contains the four loadings followed by the four unique variances on those scales, despite its name. Table 16.2 collects these endpoint checks with the prior comparison.

Use four independently seeded Gibbs chains to estimate the posterior means under the alternative prior specification.

1
2
3
4
5
main <- readRDS("data/derived/ch16/factor-gibbs-chains.rds")
weak_prior <- bayes4_prior(10,.1,.1)
weak <- lapply(1016200L+1:4,function(seed) bayes4_gibbs(Y,weak_prior,seed)$draws)
print(cbind(ML=b$is_free,ML_SE=b$se,main=colMeans(do.call(rbind,main)[,1:8]),
            weak=colMeans(do.call(rbind,weak))))

Table 16.2. Likelihood derivatives at the saved endpoint and first-loading estimates for the simulated factor sample.

QuantityValue
Marginal log likelihood at the ML estimate−718.30981
Largest absolute finite-difference gradient component0.007321932
Largest absolute analytic gradient component0.007343356
Smallest observed-information eigenvalue4.02829
First loading, ML estimate and SE0.75136, 0.07225
First loading, posterior mean under the main prior0.78006
First loading, posterior mean under the weaker prior0.76864

In Table 16.2, the positive minimum eigenvalue describes local curvature at the reported endpoint. Both gradient evaluations use that same point. The largest absolute analytic gradient component is about 0.00734. The saved refinement reduces that component to 0.00023247 while increasing the log likelihood by only about $2.18\times10^{-7}$. The first loading changes from 0.7513593 to 0.7513742, about 0.00021 of its original standard error. Across the eight parameters the largest absolute change is less than 0.00040 of its original standard error (results/completion/16.10-ML-precision-parameters.csv). These comparisons show that the residual gradient has little effect on the reported estimates at their displayed precision.

For the first loading, the alternative prior moved the posterior mean toward that endpoint. The table’s label “weaker” identifies this prior comparison and does not establish that the prior is generally less informative. At an adequately estimated likelihood maximum, the information-based standard error estimates repeated-sampling variability of the estimator. It serves a different purpose from the MCSE attached to either posterior mean.

Prior sensitivity in the observed growth experiment

The two ChickWeight fits change only the scales of the between-chick and residual variance priors. Their shapes remain two, the fixed-effect prior remains $N_9(0,25I_9)$, and both fits use the identical responses, covariates and observation schedule. The comparison therefore isolates this specified prior change within the model.

Subtract the main-prior posterior mean from the alternative-prior posterior mean for each quantity. Because the two sets of chains use separate random streams, the estimated Monte Carlo standard error of the difference is the square root of the sum of their squared MCSEs.

1
2
3
4
5
6
7
8
9
10
11
chick_main_summary <- chick_summaries[chick_summaries$prior == "main", ]
chick_other_summary <- chick_summaries[chick_summaries$prior == "larger_variances", ]
stopifnot(identical(chick_main_summary$parameter, chick_other_summary$parameter))
chick_sensitivity <- data.frame(parameter = chick_main_summary$parameter,
  main_mean = chick_main_summary$mean, alternative_mean = chick_other_summary$mean,
  difference = chick_other_summary$mean - chick_main_summary$mean,
  main_posterior_SD = chick_main_summary$sd,
  difference_MCSE = sqrt(chick_main_summary$MCSE^2 + chick_other_summary$MCSE^2))
print(chick_sensitivity, row.names = FALSE)
write.csv(chick_sensitivity, file.path("data/derived/ch16", "ch16-prior-sensitivity.csv"),
           row.names = FALSE)
1
2
3
4
5
6
7
8
9
10
11
12
13
                     parameter     main_mean alternative_mean    difference main_posterior_SD difference_MCSE
                   (Intercept)  0.4101259119      0.410897216  7.713038e-04       0.062891847    5.079520e-04
                         day10  0.3634247017      0.362902403 -5.222984e-04       0.060970938    4.823938e-04
                         Diet2 -0.0231117916     -0.023306380 -1.945888e-04       0.103847801    8.436419e-04
                         Diet3 -0.1266555694     -0.127243076 -5.875065e-04       0.103964089    8.340518e-04
                         Diet4 -0.0008830581     -0.000223907  6.591510e-04       0.103574927    8.465444e-04
                    I(day10^2)  0.1455944340      0.145689949  9.551456e-05       0.026198953    2.070453e-04
                   day10:Diet2  0.1849515643      0.185024878  7.331324e-05       0.041676410    3.324175e-04
                   day10:Diet3  0.4660819982      0.466360491  2.784929e-04       0.041840982    3.326649e-04
                   day10:Diet4  0.2934074183      0.293399187 -8.231095e-06       0.042026440    3.367479e-04
        between_chick_variance  0.0534126406      0.059332858  5.920217e-03       0.012183222    1.007864e-04
             residual_variance  0.0608516207      0.061263667  4.120464e-04       0.003785773    2.999598e-05
 diet4_minus_diet1_day21_grams 61.5272520396     61.591438614  6.418657e-02      10.362327822    8.485404e-02

difference_MCSE measures the simulation uncertainty in the estimated difference between posterior means. main_posterior_SD describes posterior uncertainty about the parameter under the main prior. A shift can be large relative to its MCSE and still be small relative to the parameter’s posterior spread. Read both columns before describing the practical influence of the prior. The diet contrast retains its gram units, so its shift can also be judged directly on the response scale.

The between-chick variance mean increases from 0.05341 to 0.05933 in squared 100-gram units, a difference of 0.00592. This difference is about half its main-prior posterior SD of 0.01218 and much larger than its MCSE of about 0.000101. The day-21 diet contrast changes much less: its mean increases from 61.53 to 61.59 grams. That 0.064-gram difference is smaller than its estimated MCSE of 0.085 gram and small relative to the posterior SD of 10.36 grams. The variance component and the population mean contrast therefore show different sensitivities to this specified prior change.

This is sensitivity to a fourfold increase in two prior mean variances, rather than an exhaustive comparison of prior families. It does not assess alternatives to the Gaussian response distribution, the random-intercept covariance or the treatment of the observed measurement schedule. Those questions remain visible in the posterior predictive checks. Convergence diagnostics concern whether the chains adequately represent the specified posterior; they do not resolve these modeling choices.

What the checks establish

Uniform ranks check the computation under the joint distribution specified by the prior and the sampling model. An algorithm could discard every observation and return independent draws from the prior. Across simulated datasets, each generating value is itself a prior draw. Its unconditional rank among the returned values would then be uniform. The normal example offers a further check. Five observations should reduce the variance of the mean from four to $(5+1/4)^{-1}$ and should shift its posterior mean when the sample mean changes. The algorithm that discards the observations would do neither. Examine this contraction, or rank a quantity that also depends on the observed data, alongside the parameter ranks. Whether a fitted model reproduces observed item associations calls for a predictive check.

For the first of the 150 observed respondents, all four answers fell below zero. On the factor scale oriented by a positive first loading, the four Gibbs chains placed that person’s mean at $-1.7064$, with posterior SD 0.3568. The mean’s MCSE of 0.00164 and split $\widehat R$ close to one support the simulation precision of that estimate.

For a new respondent, integrate over a fresh population factor and draw all four answers together. The observed first-item mean and variance and the covariance of items one and two fell within the replicated sample intervals. Leaving out the respondent with the largest Pareto shape gave predictive log densities differing by about 0.00689 under reweighting and direct refitting, with no MCSE reported for that difference. These checks address specific features of the observed fit.

Across fresh samples of 30 people from the prior predictive model, a single marginal NUTS chain frequently underestimated the generating first loading in the sense that all its selected draws fell below it. That finding limits the use of this one-chain procedure for new samples of that size. The supplied calibration functions follow the design of sbc() of rstan (code/NOTICE.md), which provides simulation-based calibration in R.

This post is licensed under CC BY-NC 4.0 by the author.