21 Bayesian Computation
21.1 Prerequisites
Answer the following questions to see if you can bypass this chapter. You can find the answers at the end of the chapter in Section 21.20.
- State Bayes’ theorem for posterior inference on a parameter \(\theta\) given data \(y\), identifying the prior, likelihood, posterior, and normalizing constant.
- What is the difference between a Metropolis-Hastings step and a Gibbs step? Under what conditions is Gibbs sampling possible?
- After running an MCMC chain, what diagnostics would you use to decide whether the chain has converged, and what does the Gelman-Rubin \(\hat R\) statistic measure?
21.2 Learning objectives
By the end of this chapter you should be able to:
- State Bayes’ theorem and apply it to a simple conjugate example by hand (beta-binomial, normal-normal).
- Implement a Metropolis-Hastings sampler from scratch for a one-parameter problem and verify convergence.
- Fit a Bayesian GLM with
rstanarm::stan_glm()and interpret its output: posterior means, credible intervals, posterior predictive checks. - Fit a Bayesian hierarchical model with
brms::brm()and recognize the equivalence tolme4::lmer()under weakly informative priors. - Run
posterior::summarise_draws()and read the ESS, \(\hat R\), and MCSE columns. - Diagnose a chain that has not converged: trace plots, divergences, \(\hat R > 1.01\), low ESS, low E-BFMI.
- Conduct a prior sensitivity analysis when priors might matter.
21.3 Orientation
Bayesian inference answers the question: given these data and what I believed before I saw them, what should I believe now? Frequentist inference answers a different question: under repeated sampling, how would my procedure behave? For instance, how often would its intervals cover the truth, or its tests reject a true null? Neither approach is universally correct. Both are useful, and a biostatistician encounters both.
The computational tools to fit Bayesian models became accessible to non-specialists with the Stan ecosystem (2012-) and the tidy-Bayes R packages: rstanarm, brms, bayestestR, and posterior. For most common models (linear regression, GLMs, mixed-effects, survival), a Bayesian fit is now a one-liner. It takes a minute or two to run and produces output as easy to read as summary(lm).
This chapter is concerned with computation rather than philosophy. For the philosophy, Gelman et al.’s Bayesian Data Analysis (Gelman et al., 2013) and McElreath’s Statistical Rethinking (McElreath, 2020) are the canonical references. For the computation, Stan is the lingua franca, and rstanarm and brms are the R wrappers that turn most common models into one-liners.
In this chapter we shall proceed as follows. We begin with Bayes’ theorem and a conjugate example, and then build a Metropolis-Hastings sampler from scratch. After a brief account of Hamiltonian Monte Carlo, we fit a Bayesian GLM with rstanarm and a hierarchical model with brms. We then turn to posterior summaries, posterior predictive checks, convergence diagnostics, and the choice of priors.
A note on Stan backends is in order. rstan is the original R interface. It is the default for rstanarm and was, for many years, the default for brms. cmdstanr is the contemporary alternative. It talks directly to the Stan command-line cmdstan and exposes new Stan features faster than rstan does. We would switch to cmdstanr (via brms::brm(..., backend = "cmdstanr")) when a recent Stan feature is needed, or when shorter build times matter. For this chapter’s coverage, the default rstan backend is adequate.
21.4 The statistician’s contribution
Software supports Bayesian computation well. It does not, however, make the judgments that matter: which prior, which model, whether the chain converged, and what the posterior actually says.
Choose priors deliberately. A weakly informative default prior is adequate for many applications, and it gives results numerically similar to a maximum-likelihood fit. (rstanarm’s default for regression coefficients is normal(0, 2.5) on the standardized scale.) Priors are not neutral, however, since they encode what was believed before the data arrived. For small samples, or for parameters with little information in the data, the prior dominates the posterior. The statistician’s job is to choose priors deliberately, usually weakly informative and occasionally genuinely informative. It is also to carry out a sensitivity analysis when the priors might matter.
Establish convergence; do not assume it. \(\hat R\) near 1.00 and adequate ESS are necessary but not sufficient. Trace plots, divergences (HMC), E-BFMI, and posterior predictive checks together build the case that the chain has converged to the right distribution. Any one of these failing is a problem. Ignoring them and reporting the posterior mean as the answer is irresponsible.
Credible intervals are not confidence intervals. A 95% credible interval is a probability statement about the parameter: ‘given the data and prior, the parameter has 0.95 probability of being in this range’. A 95% confidence interval is a probability statement about the procedure: ‘in repeated sampling, this method captures the parameter 95% of the time’. The two have different interpretations and sometimes different numerical values. Reporting a credible interval as a ‘CI’ without qualification is a common error.
Posterior predictive checks are not optional. A model that fits its training data perfectly may still generate data that look nothing like the observed data on substantively important features (zero counts, extreme values, autocorrelation). pp_check(fit) overlays the observed data on simulated draws from the posterior predictive distribution. Failures here flag model misspecification, and no diagnostic of the parameters alone will catch them.
21.5 Bayes’ theorem
We begin with the theorem itself. For a parameter \(\theta\) and data \(y\),
\[ p(\theta \mid y) = \frac{p(y \mid \theta) \, p(\theta)}{p(y)} \quad \propto \quad p(y \mid \theta) \, p(\theta). \]
where the pieces are as follows.
- \(p(\theta)\): the prior, what you believe about \(\theta\) before seeing the data.
- \(p(y \mid \theta)\): the likelihood, the probability of the observed data given the parameter.
- \(p(\theta \mid y)\): the posterior, what you believe about \(\theta\) after seeing the data.
- \(p(y) = \int p(y \mid \theta) p(\theta) \, d\theta\): the normalizing constant (marginal likelihood). MCMC samples from the unnormalized posterior, so this integral is rarely computed in practice.
The proportionality is the workable form. When prior and likelihood are conjugate, the posterior has a known distributional form. In general, however, posterior sampling is the route.
21.5.1 A conjugate example: beta-binomial
To illustrate, consider \(y \sim \mathrm{Binomial}(n, \theta)\) with prior \(\theta \sim \mathrm{Beta}(\alpha, \beta)\). Then
\[ \theta \mid y \sim \mathrm{Beta}(\alpha + y, \beta + n - y). \]
The posterior mean is \((\alpha + y) / (\alpha + \beta + n)\). With a uniform prior \(\mathrm{Beta}(1, 1)\) and data \(y = 60\) successes out of \(n = 100\), the posterior is \(\mathrm{Beta}(61, 41)\). Its mean is \(61/102 \approx 0.598\), shrunk only slightly from the MLE of \(0.6\) by the prior.
n <- 100
y <- 60
alpha <- beta <- 1 # uniform prior
post <- function(theta) dbeta(theta, alpha + y, beta + n - y)
curve(post, from = 0, to = 1)
abline(v = 0.6, col = "red") # MLE
qbeta(c(0.025, 0.975), alpha + y, beta + n - y)
#> [1] 0.501 0.689The 95% credible interval for \(\theta\) comes directly from the beta quantile function. The Wald 95% CI for the same data is \(0.6 \pm 1.96 \sqrt{0.6 \cdot 0.4 / 100} \approx (0.504, 0.696)\), which is nearly identical. With informative priors or smaller samples, the agreement weakens.
21.6 A Metropolis-Hastings sampler from scratch
Consider a one-dimensional posterior \(\pi(\theta) \propto p(y \mid \theta) p(\theta)\). A Metropolis-Hastings sampler for it may be written as follows.
mh_sampler <- function(log_posterior, theta0, n_iter = 10000,
proposal_sd = 1) {
theta <- numeric(n_iter)
theta[1] <- theta0
accept <- 0
for (i in 2:n_iter) {
theta_prop <- rnorm(1, theta[i - 1], proposal_sd)
log_a <- log_posterior(theta_prop) - log_posterior(theta[i - 1])
if (log(runif(1)) < log_a) {
theta[i] <- theta_prop
accept <- accept + 1
} else {
theta[i] <- theta[i - 1]
}
}
list(samples = theta, accept_rate = accept / (n_iter - 1))
}
# example: beta-binomial posterior
log_post <- function(theta) {
if (theta <= 0 || theta >= 1) return(-Inf)
dbinom(60, 100, theta, log = TRUE) + dbeta(theta, 1, 1, log = TRUE)
}
set.seed(1)
res <- mh_sampler(log_post, theta0 = 0.5, n_iter = 10000,
proposal_sd = 0.1)
res$accept_rate
#> [1] 0.31
# discard burn-in, summarize
samples <- res$samples[1001:10000]
mean(samples)
quantile(samples, c(0.025, 0.975))Three things matter for getting MH right.
- Proposal distribution. A symmetric proposal (e.g., normal) is the simplest case, and the acceptance probability becomes \(\min(1, \pi(\theta_\text{prop})/\pi(\theta_\text{current}))\). Asymmetric proposals require the Metropolis-Hastings correction.
- Tuning the proposal scale. Too small a scale gives high acceptance but slow exploration. Too large a scale gives low acceptance and many rejections. The classic target is an acceptance rate of around 0.234 in high dimensions and roughly 0.4 to 0.5 for one-dimensional problems.
- Burn-in and thinning. The first samples depend on the starting value, so we discard them. Thinning (keeping every \(k\)th sample) is rarely useful with modern diagnostics, since ESS captures the relevant autocorrelation.
Unfortunately, raw MH scales poorly to high-dimensional posteriors. Acceptance rates collapse, and chains move slowly through the posterior. Hamiltonian Monte Carlo (the engine in Stan) addresses this with momentum variables and gradient information. In this way it achieves much better mixing in high dimensions.
21.7 Hamiltonian Monte Carlo, in one paragraph
HMC augments the parameter space with momentum variables. It then uses the gradient of the log-posterior to propose correlated steps that follow approximate Hamiltonian dynamics. As a result, proposals are far from the current state but still in regions of high posterior density. That is, acceptance is high, and the effective sample size per iteration is much higher than for MH. Stan implements an adaptive HMC variant called the No-U-Turn Sampler (NUTS), which tunes the trajectory length automatically. On the minus side, the cost per iteration is high, since each iteration requires multiple gradient evaluations. On the plus side, the cost per effective sample is far lower than for MH in problems with more than a handful of parameters. This is why rstanarm and brms work as well as they do on realistic models. NUTS can fit a hierarchical model in seconds when MH would take hours.
We shall not implement HMC by hand in this course. It is enough to understand why it dominates MH.
21.8 Fitting a Bayesian GLM with rstanarm
rstanarm mirrors base R’s modeling functions. It offers stan_lm for linear regression, stan_glm for GLMs, stan_lmer and stan_glmer for mixed-effects models, stan_polr for ordinal regression, stan_betareg for beta regression, and several others. The default priors are weakly informative on the standardized scale, which works for most regression problems without adjustment.
library(rstanarm)
data(penguins, package = "palmerpenguins")
penguins <- na.omit(penguins)
fit <- stan_glm(
body_mass_g ~ flipper_length_mm + species,
data = penguins,
family = gaussian(),
prior = normal(0, 100, autoscale = TRUE),
prior_intercept = normal(4000, 500),
chains = 4,
cores = 4,
seed = 47,
refresh = 0 # silence sampling progress
)
summary(fit)
broom.mixed::tidy(fit, conf.int = TRUE)The argument prior controls the prior on the slope coefficients, prior_intercept the prior on the intercept, and prior_aux the prior on the residual standard deviation. The autoscale = TRUE flag rescales the prior to the standard deviation of each predictor. This makes the default priors sensible across covariate scales.
The output contains the following quantities.
- Median posterior estimate per coefficient (the default; mean is also available).
- MAD_SD: the median absolute deviation of the posterior, scaled to be comparable to a frequentist SE.
- Sample sizes: ESS for each parameter. It should be at least several hundred for reliable quantile-based summaries.
- \(\hat R\): should be < 1.01 for every parameter.
We may compare the fit to lm() as follows.
fit_lm <- lm(body_mass_g ~ flipper_length_mm + species, data = penguins)
cbind(
bayes = coef(fit),
freq = coef(fit_lm)
)Under weakly informative priors, the posterior medians should agree closely with the OLS coefficients, and the MAD_SDs with the SEs. The remaining differences are of the order of the Monte Carlo error, which for a few thousand posterior draws is a small fraction of a standard error. The match becomes worse as priors become more informative, sample sizes shrink, or the model becomes more hierarchical.
21.9 Fitting a Bayesian hierarchical model with brms
brms translates a lme4-style formula into a Stan model and fits it. Its interface is more flexible than that of rstanarm, accommodating custom likelihoods, censored outcomes, splines, and mixture models. The cost of this flexibility is slower compile times.
library(brms)
data(sleepstudy, package = "lme4")
fit <- brm(
Reaction ~ Days + (Days | Subject),
data = sleepstudy,
family = gaussian(),
chains = 4,
cores = 4,
seed = 47,
refresh = 0
)
summary(fit)
plot(fit)
posterior::summarise_draws(fit, default_summary_measures())We may compare this fit to lme4::lmer(Reaction ~ Days + (Days | Subject), data = sleepstudy). Under weakly informative priors, the fixed-effect estimates should agree closely, and so should the random-effect variance components. The BLUPs from lmer and the posterior means of the subject-specific deviations from brm should also agree. We would expect brm to produce slightly more shrinkage when the data for a subject are sparse.
In a Bayesian model, random effects are parameters with a hierarchical prior. The variance of that prior (the random-effects SD) is itself estimated. There is no philosophical distinction between fixed and random effects in a Bayesian model. Both are parameters, and it is the hierarchical prior on the latter that produces the shrinkage.
21.10 cmdstanr for advanced Stan use
cmdstanr is the recommended interface to Stan for advanced users. It talks directly to the cmdstan executable and supports the latest Stan features soonest. It is also one of the two backends that brms can use. We run cmdstanr::install_cmdstan() once, and subsequent brms::brm(... backend = "cmdstanr") calls will use it. For most users, brms with the default rstan backend is adequate. We would switch to cmdstanr when we need a Stan feature that rstan does not yet expose, or when build time matters.
21.11 Posterior summaries
Once the chain has converged, the draws are a sample from the posterior, and every summary is computed from them.
library(posterior)
draws <- as_draws_df(fit)
summarise_draws(draws,
mean,
~ quantile(.x, probs = c(0.025, 0.5, 0.975)),
rhat,
ess_bulk,
ess_tail)The columns are as follows.
mean,2.5%,50%,97.5%: posterior summaries. The 95% credible interval runs from the 2.5th to the 97.5th percentile of the posterior. The median is often more robust than the mean for skewed posteriors.rhat: \(\hat R\). We want values < 1.01.ess_bulk,ess_tail: bulk and tail effective sample sizes. We want at least a few hundred each for reliable posterior quantile summaries.
tidybayes provides similar functionality with a more ggplot-friendly API. bayesplot produces standardized diagnostic plots, including trace plots, autocorrelation plots, and posterior interval plots.
21.12 Posterior predictive checks
pp_check(fit) overlays the observed data on draws from the posterior predictive distribution, so that misfit becomes visible.
pp_check(fit, ndraws = 100)The default plot shows the observed outcome density against the posterior predictive draws. Suppose the draws differ systematically from the observed data, in mode, variance, range, or proportion of zeros. Then the model is misspecified on some feature to which the data are sensitive.
Unfortunately, PP checks are routinely overlooked. A posterior with \(\hat R = 1.000\) and tight credible intervals can still come from a model that does not describe the data, and the parameter diagnostics will not reveal it.
21.13 Convergence diagnostics
Three diagnostics are required for every fit.
- Trace plots. Visual check for stationarity (no drift) and mixing (chains overlap, look like white noise).
- \(\hat R\). We want values < 1.01 for every parameter. \(\hat R\) compares within-chain variance to between-chain variance. Values near 1 mean that the chains have all converged to the same distribution.
- Effective sample size. We want at least 400 in
ess_bulkandess_tailper parameter. A lower ESS means that the chain is autocorrelated, and quantile-based summaries are then noisy.
For HMC (Stan-based fits, including rstanarm and brms), two further diagnostics apply.
- Divergences. These should be zero, or nearly so. A divergent transition is HMC failing to integrate the dynamics faithfully. Even one divergence flags a problem. Many divergences typically mean that the model is not as identifiable as we thought, or that the parameterization is poor. The standard remedy is a non-centered parameterization (especially for hierarchical scale parameters) together with
adapt_delta = 0.99(the default is 0.8). - E-BFMI. This is the energy-based fraction of missing information, and it should be > 0.3. A low E-BFMI suggests that the posterior has a funnel-like shape that HMC struggles with. This is usually a reparameterization problem.
library(bayesplot)
mcmc_trace(fit)
mcmc_acf(fit, regex_pars = "b_")21.14 Priors
rstanarm and brms use weakly informative defaults. For most regression problems with reasonable sample sizes, these are adequate. But when are they not?
- Very small samples. With \(n = 20\), the prior may shape the posterior more than the data do, and the choice of prior must be deliberate.
- Strong prior knowledge. When external evidence genuinely informs the parameter (e.g., a meta-analysis has pinned the treatment effect to a narrow range), using that information via the prior is appropriate.
- Identifiability problems. A weakly identified parameter (e.g., the scale of a latent variable in a factor model) needs a prior that the data cannot fully overrule.
For a sensitivity analysis, we refit with two alternative priors and report whether the conclusions change. If they do, we disclose the dependence. If they do not, the analysis is robust to the choice of prior.
fit_default <- stan_glm(y ~ x, data = d)
fit_skeptical <- stan_glm(y ~ x, data = d, prior = normal(0, 0.5))
fit_optimistic <- stan_glm(y ~ x, data = d, prior = normal(2, 1))
# compare posterior means and CIs across priors21.15 Collaborating with an LLM on Bayesian computation
LLMs handle the syntax of stan_glm and brm reasonably well. They handle the diagnostics and the choice of priors much less reliably.
Prompt 1: translating a frequentist fit. Paste the output of glm(...) and ask: ‘fit the equivalent Bayesian model with rstanarm, using weakly informative priors. Compare the coefficients to the frequentist estimates and explain any differences.’
What to watch for. The LLM should produce a fit with similar coefficients, since under weakly informative priors they will agree on most data up to Monte Carlo error. If the LLM produces wildly different estimates, we should suspect that the priors are too informative or that the chain has not converged.
Verification. Run both fits and print the coefficients side by side. Check \(\hat R\) and ESS for the Bayesian fit. If either is poor, the comparison is meaningless.
Prompt 2: diagnosing a non-converged chain. Paste the warning (‘There were N divergent transitions…’) and the relevant trace plots, and ask: ‘what is happening, and what should I try?’
What to watch for. The standard remedies for divergences are a non-centered parameterization for hierarchical scales, adapt_delta = 0.99, and more informative priors on problematic parameters. The LLM should know these. If it suggests ‘just ignore the warning’, we should push back.
Verification. Implement the suggested fix and verify that the divergences disappear. If they do not, the problem should be escalated, since it presumably needs a reparameterization that LLMs do not always identify.
Prompt 3: posterior predictive check interpretation. Paste the pp_check plot description and ask: ‘what does this say about the model?’
What to watch for. LLMs can usually identify obvious mismatches, such as a mode in the wrong place, missing tail behavior, or zero-inflation. They are weaker on subtle mismatches that require subject-matter knowledge. We may trust the LLM’s pattern-matching, but we should verify the substantive judgment against our own understanding of the data.
21.16 Principle in use
Three habits define defensible Bayesian computation:
- Always check convergence. \(\hat R\), ESS, divergences, E-BFMI. Do not report results from a chain that has not converged.
- Always do a posterior predictive check. A converged chain on a misspecified model produces a precise wrong answer.
- Be deliberate about priors. Defaults are fine for many applications but not for all. Sensitivity analysis disclosing prior dependence is the polite minimum.
21.17 Exercises
- Using
palmerpenguins::penguins, fit a Bayesian linear regression ofbody_mass_gonflipper_length_mmwithrstanarm::stan_glm()under weakly informative priors. Extract the 95% credible interval for the slope. Compare it to the 95% CI fromlm(). - Implement a Metropolis-Hastings sampler from scratch for the posterior of a binomial proportion with a
beta(1, 1)prior. Run 10,000 iterations and compare the sample mean and SD to the analytic posterior mean and SD. What proposal SD gives an acceptance rate near 0.4? - Fit the
sleepstudyrandom-slope model with bothlme4::lmer()andbrms::brm(). Compare the fixed effects, the variance components, and the subject-specific intercepts and slopes (BLUPs from lmer vs. posterior means from brm). Under what conditions would you expect them to disagree? - Run a
stan_glm()fit with three different priors on the slope:normal(0, 1000)(weak),normal(0, 1)(moderate), andnormal(2, 0.1)(strongly informative). Document how the posterior shifts. - Fit a model that diverges (a hierarchical model with a tight, identical prior on every random-effect group often does the trick). Diagnose using
bayesplot::mcmc_pairs()and apply a non-centered parameterization. Verify the divergences vanish.
21.18 Further reading
- (Gelman et al., 2013), Bayesian Data Analysis, 3rd ed., Chapman and Hall/CRC, the canonical reference.
- (McElreath, 2020), Statistical Rethinking, 2nd ed., accessible introduction paired with
brmscode. - Stan Development Team documentation at
mc-stan.org/docs, the ecosystem reference. - (Vehtari et al., 2021), ‘Rank-normalization, folding, and localization: an improved \(\hat R\) for assessing convergence of MCMC’, Bayesian Analysis, the modern guideline for \(\hat R\) and ESS thresholds.
- (Bürkner, 2017), ‘brms: An R package for Bayesian multilevel models using Stan’, JSS, the brms paper.
21.19 Practice test
The following multiple-choice questions exercise the chapter’s content. Attempt each question before expanding the answer.
21.19.1 Question 1
Bayes’ theorem expresses the posterior \(p(\theta \mid y)\) as proportional to:
- The likelihood \(p(y \mid \theta)\).
- The prior \(p(\theta)\).
- The product \(p(y \mid \theta) \, p(\theta)\).
- The marginal likelihood \(p(y)\).
C. The proportionality avoids computing the normalizing constant \(p(y)\), which is the high-dimensional integral that motivates MCMC in the first place.
21.19.2 Question 2
A 95% credible interval for a parameter \(\theta\) is:
- The set of values for which a frequentist test would not reject the null at \(\alpha = 0.05\).
- The set of values such that, given the prior and data, the posterior probability that \(\theta\) is in the set is 0.95.
- The set of \(\theta\) values containing the MLE.
- Equivalent in interpretation to a frequentist confidence interval.
B. Credible intervals are probability statements about the parameter; confidence intervals are probability statements about the procedure. Numerically, they often agree under weakly informative priors with moderate samples.
21.19.3 Question 3
In the Metropolis-Hastings algorithm, the acceptance probability for a symmetric proposal is:
- \(\min(1, p(\theta_\text{prop}) / p(\theta_\text{current}))\), where \(p\) is the posterior density (or any function proportional to it).
- \(\min(1, p(\theta_\text{current}) / p(\theta_\text{prop}))\).
- Always 1.
- The acceptance rate of the chain.
A. A proposal that is more likely than the current value is always accepted; one that is less likely is accepted with probability equal to the ratio.
21.19.4 Question 4
You run an HMC chain in Stan and see 12 divergent transitions reported. The most appropriate response is:
- Ignore them; small numbers of divergences are cosmetic.
- Increase
adapt_delta(e.g., to 0.99), consider a non-centered parameterization, and possibly tighten priors.
- Increase
- Switch to Metropolis-Hastings.
- Take the posterior at face value if \(\hat R\) is near 1.
B. Even a few divergences flag a region of the posterior the sampler cannot traverse, biasing the posterior toward easier-to-sample regions. The standard remedies are reparameterization and adapt_delta.
21.19.5 Question 5
Posterior predictive checks (pp_check(fit)) primarily detect:
- Convergence failures of the chain.
- Insufficient ESS.
- Model misspecification: features of the data the model fails to reproduce in posterior simulations.
- Choice of prior.
C. PP checks compare observed data to posterior predictive draws and are essential for detecting misspecification that no diagnostic of the parameters alone catches.
21.20 Prerequisites answers
- Bayes’ theorem: \(p(\theta \mid y) = p(y \mid \theta) p(\theta) / p(y)\), where \(p(\theta)\) is the prior, \(p(y \mid \theta)\) is the likelihood, \(p(\theta \mid y)\) is the posterior, and \(p(y) = \int p(y \mid \theta) p(\theta) \, d\theta\) is the normalizing constant (marginal likelihood). In practice, MCMC samples from the unnormalized posterior \(p(y \mid \theta) p(\theta)\), so the normalizing constant need not be computed explicitly.
- A Metropolis-Hastings step proposes a new value from a proposal distribution and accepts it with a probability based on the ratio of posterior densities. It requires only the ability to evaluate the posterior up to a constant. A Gibbs step samples each parameter (or block of parameters) from its full conditional distribution. Gibbs is possible whenever each full conditional can be sampled. This is simplest when the full conditionals have closed forms, typically via conjugacy; otherwise a step such as slice sampling or an MH step within Gibbs is needed. MH applies more generally; Gibbs is more efficient when available.
- Trace plots (visual check for stationarity and mixing), the Gelman-Rubin statistic \(\hat R\) (want < 1.01), effective sample size (ESS; want more than several hundred per parameter for reliable quantile-based summaries), and, for HMC, the divergence count (ideally zero) and E-BFMI (ideally > 0.3). \(\hat R\) compares within-chain and between-chain variance after discarding burn-in; values near 1 indicate that multiple chains have converged to the same target distribution, values substantially above 1 indicate that the chains are still exploring different regions.