For retained Markov chain Monte Carlo draws , calculate both the parameter average and the average deviance . Two estimates are
The first uses the approximate equality of the posterior mean and maximum-likelihood estimator. The second subtracts the mean of the chi-squared distribution deviance excess. These are different operations: evaluation after averaging versus averaging after evaluation. Both rely on a well-mixed chain and the regular locally flat-prior approximation. The smallest sampled deviance is an upper bound on the true minimum, but merely taking that minimum can be inefficient in high dimension because few draws approach the mode closely.
Center the log-time predictor and the baseline log measurement near their sample means, so the intercept describes a typical predictor configuration. This reduces intercept-slope posterior correlation and can improve Markov chain Monte Carlo mixing. If exactly the original model is required, transform the intercept prior consistently when changing coordinates rather than silently assigning a different independent prior.
For weakly informed child effects, a non-centered Gaussian random-effect parameterization can also help:
This retains the same conditional prior distribution for but removes its prior-scale dependence from the sampled . It can reduce strong dependence between the effects and . A centered parameterization can be better when each child's effect is very accurately observed, so improvement is not automatic. Blocking strongly correlated coefficients is another option. Check the resulting chains with Markov chain Monte Carlo convergence diagnostics and effective sample size of a Markov chain, rather than judging convergence from the number of iterations alone.
For the Box-Muller transform, draw independent from the uniform distribution on and set
The radial density is for , with an independent uniform angle. The polar-to-Cartesian Jacobian determinant is , so the joint density of is
This factorization proves that both outputs have the standard normal distribution and are independent. Repeating the Box-Muller transform with fresh independent uniform pairs gives independent normal outputs; discard one extra output if the desired sample size is odd.
For the prescribed binary probabilities, generate independent standard normal values in this way and use
The standard normal distribution function gives , and independence is preserved because each threshold uses a different independent normal value.
For the probit regression posterior, introduce latent variables
Given , these are independent variables, and normal symmetry gives . Thus this data augmentation has exactly the observed binary likelihood. With the specified normal prior distribution, the augmented joint posterior is proportional to
The latent-normal Gibbs sampler for probit regression alternates two blocks. First, given the current , draw each independently from its truncated normal distribution, namely restricted to the sign fixed by . One exact method is to use the Box-Muller transform for , form , and reject until the sign is correct. The probability of success is positive at every finite parameter value, so the method is valid, although it can be slow for a rare sign.
For direct sign-truncated normal sampling, let , and draw . An inverse transform sampling implementation is
Use suitable tail or survival-function evaluations when floating-point probabilities approach zero or one; the rejection construction remains a valid alternative.
Second, completing the square in yields its full conditional distribution:
Generate a fresh standard normal value by the Box-Muller transform, multiply by the conditional standard deviation, and add the conditional mean. Start from any finite , alternate these steps, discard an initial transient and use the retained values to approximate its posterior distribution. These are dependent Markov chain Monte Carlo samples, rather than independent posterior draws. Each block is an exact Gibbs sampling update for the augmented posterior, whose marginal in is the requested posterior.
Fit two hierarchical Bayesian models to the same observations, one with the bounded uniform distribution sampling density and the other with an exponential distribution density. Specify rate versus mean in the exponential model and assign appropriate, scientifically comparable proper prior distributions; that parameter is no longer a literal maximum size. Obtain posterior distributions, for example by Markov chain Monte Carlo, and check convergence.
At the same observational level in both models use the Bayesian deviance , excluding prior densities. Retain the same likelihood constants and consistently either condition on breed effects or integrate them out. Estimate , evaluate at the posterior mean, and compute the effective parameter count in DIC:
Smaller DIC favours the fit–complexity tradeoff. Supplement it with posterior predictive checks; the uniform model's parameter-dependent support and the hierarchical structure make the criterion a diagnostic rather than an automatic definitive decision.
A uniform prior on makes the posterior density proportional to the Poisson change-point posterior likelihood above. The zeros trick introduces an observed zero with Poisson distribution mean , making its likelihood function equal to . Choose ; since , this mean is strictly positive. Rough BUGS code, with zero=0 supplied as data, is
model {
  theta ~ dunif(0,T)
  for (i in 1:n) {
    before[i] <- step(theta-time[i])
  }
  j <- sum(before[])
  logL <- theta-2*T+(n-j)*log(2)
  zero ~ dpois(K-logL)
}
For , omit the array and set j <- 0. Monitor the sampled theta to obtain its posterior mean, credible interval and interval probabilities.
There is also an exact sampling method. On the posterior density is proportional to , so choose the interval with weights
Then draw from a uniform distribution on and set . These weighted interval draws sample the posterior directly, without asking a local Markov chain Monte Carlo update to cross its discontinuities.
In Markov chain Monte Carlo, retain the derived quantity at every iteration. Rough BUGS code using the actual observations is
model {
  pM ~ dbeta(0.5,0.5)
  pT ~ dbeta(0.5,0.5)
  milkAnswers ~ dbin(pM,4)
  teaAnswers ~ dbin(pT,4)
  delta <- pM-pT
  positive <- step(delta)
}
Supply milkAnswers=3 and teaAnswers=1. Summarize delta by its posterior mean, empirical quantiles and credible interval; the average of positive estimates . Here . Check Markov chain Monte Carlo convergence diagnostics before interpreting the simulation. Since both Bayesian posteriors are independent known beta distributions, direct independent sampling is an equally valid, simpler way to obtain the same summaries.
Write
Multiplying the likelihood by the improper prior gives the Bayesian posterior kernel
Since
the first full conditional is
Holding fixed and comparing powers and exponential rates gives
The assumed parity of makes a positive integer.
Initialize arbitrarily. At iteration , put
Draw independent uniform variables and set
By sampling an integer-shape gamma distribution, this has the required law. Next draw independently and set
These are exactly the two full-conditional updates of the normal mean-precision Gibbs sampler. After discarding burn-in, the pairs are approximate samples from the posterior by Markov chain Monte Carlo.
Variational inference replaces exact Bayesian inference by an optimization problem over a tractable family . A guide program samples from this approximating family. Optimizing an evidence lower bound is equivalent to minimizing . Its appeal is that a fitted approximation can be cheap to sample and may scale well when an exact posterior distribution is inaccessible. A restricted family, such as mean-field variational inference, can miss dependence or entire modes; a local optimum can add further error. More optimization cannot remove approximation error caused by an inadequate family.
Monte Carlo method inference instead estimates posterior expectations using simulated values or weighted values. Examples include rejection sampling, importance sampling and Markov chain Monte Carlo. Under their respective support and convergence assumptions, increasing computation can yield consistent estimates without choosing a finite-dimensional posterior family. Their uncertainty includes simulation error; an inefficient proposal or slow mixing time can make that error large. Markov chain Monte Carlo additionally requires convergence and dependence diagnostics.
The central trade-off is optimization within an approximate family versus simulation under a target probability distribution. It is not an absolute distinction between deterministic and random computation: variational inference often uses Monte Carlo method estimates of its gradient, while Monte Carlo method inference may use fitted proposals. Neither method automatically guarantees accurate uncertainty estimates or superiority at a fixed computational budget.
Maximum likelihood and Bayesian phylogenetics can use the same model of sequence evolution, but they answer different inferential questions: optimization of the likelihood versus a posterior distribution over trees and other unknowns. Let be a sequence alignment, a phylogenetic tree topology, its branch lengths in expected substitutions per site, and the parameters of a nucleotide substitution model. Both methods can use
The likelihood function sums over unobserved ancestral states, rather than choosing one ancestral sequence and treating it as observed. For conditionally independent sites it is a product of site likelihoods; transitions along a branch can be described by the matrix exponential of a continuous-time Markov chain rate matrix . The phylogenetic pruning algorithm computes the ancestral sums efficiently.[ref]
With maximum likelihood estimation, one seeks
In practice, the enormous discrete tree space requires searches and repeated optimization of continuous parameters; heuristic failure to find the best tree is a computational error distinct from statistical uncertainty. A tree's optimized likelihood is not the probability that it is correct. bootstrap analyses resample alignment columns and repeat inference to assess support under the resampling procedure; their frequencies are not automatically posterior probabilities. Independence assumptions matter, because linked sites and heterogeneous loci can make simple column resampling an imperfect representation of replication.
In Bayesian phylogenetic inference,
The prior distribution supplies weights on topologies, branch lengths and model parameters. Integrating over nuisance parameters gives
Thus a very narrow likelihood peak can lose posterior support to a broader region with a slightly lower maximum. maximum a posteriori estimation is another optimization and does not replace this integration. Markov chain Monte Carlo provides dependent samples approximating the posterior distribution; a clade's posterior probability is the posterior mass of trees containing that clade. The early likelihood-based Bayesian formulation explicitly distinguished these probabilities from bootstrap support.[ref]
Neither approach is protected against systematic error. Poor sequence alignment, incorrect orthology assignments, compositionally heterogeneous sequences, and an inadequate substitution process can support a wrong tree with high apparent confidence. A gene tree can differ from a species tree because of incomplete lineage sorting or introgression; extra sequence from that gene does not automatically fix the mismatch. Model comparison, biological examination of the data and sensitivity to locus sampling are needed in both approaches. In Bayesian analyses, agreement among short chains is not proof of convergence: independent runs, adequate mixing between topologies and an appropriate effective sample size of a Markov chain should be checked. A credible interval and a confidence interval also have different interpretations even if their numerical endpoints happen to resemble one another.
Time inference adds a particularly strong role for assumptions. If a branch spans , with mean rate , its expected length is . Without an external absolute-time anchor, scaling every time by and every rate by leaves the sequence likelihood unchanged. Even a very long alignment can identify branch lengths accurately without identifying an absolute calendar scale. For example, a lineage length substitutions per site is compatible with per site per million years and million years, or twice that rate and half that duration. This is an identifiability issue, not merely a shortage of sampled bases.
In Bayesian divergence-time inference, a schematic joint analysis is
where is fossil information already used to construct the conditional prior. An alternative generative analysis includes a fossil-sampling likelihood explicitly; the same fossil evidence must not be counted twice. A strict molecular clock equates rates across branches; a relaxed molecular clock allows variation, whose distribution and correlations also require specification. A narrow rate prior favors particular absolute ages, and a strong rate-smoothing assumption can redistribute inferred time among branches. A birth-death process prior on the tree encodes assumptions about lineage origination, extinction and sampling; it is not a neutral choice just because it is mathematically convenient.
fossil calibration must separate a fossil's geological age from the age of the lineage split it constrains. A confidently placed crown fossil gives a minimum age for the relevant crown, whereas a stem fossil does not automatically set that crown minimum. Uncertain placement and the incompleteness of the record complicate upper bounds. hard calibration bounds assign zero probability outside the permitted range; enough sequence cannot overcome a zero prior. soft calibration bounds allow small tail probabilities, exposing rather than eliminating the possibility of conflict. Multiple-calibration analyses demonstrate that changing the treatment of bounds changes inferred times and uncertainty.[ref]
Furthermore, separately specified calibration densities are not necessarily the marginal priors the program uses. The rule that an ancestor must be older than its descendant truncates their joint possibilities. If two ages are initially independent uniform variables on , conditioning on gives marginal densities and , respectively. Neither remains uniform. Combining tree-process priors, calibration densities and ordering constraints can therefore introduce substantial information unintentionally.[ref]
The practical response is to run the analysis without sequence information to inspect the effective prior distribution, then compare it with the posterior distribution. Repeat under defensible calibration tails, rate models, tree priors and fossil placements; report which ages change and whether the data sharpen relative ages more than absolute ages. Examine prior predictive checks and posterior predictive checks, and keep numerical mixing diagnostics separate from biological model adequacy. Priors can legitimately supply the time information missing from sequences, but narrow posterior ages are persuasive only when that information and its sensitivity are explicit.
TODO: Complete the data-specific numerical results and diagnostics when the original Iris_data.csv is available.
Use the random-walk Metropolis algorithm with proposal , where . The proposal is symmetric, so for a nonnegative proposal the acceptance probability is
Negative proposals are rejected. They are not redrawn until positive, since that would change the proposal kernel and require a different acceptance ratio. On rejection, store the current state again; keeping accepted moves alone would bias the empirical posterior distribution.
This R continuation makes exactly 10,000 proposals, starting at :
set.seed(20240528)
B <- 10000L
mu <- numeric(B + 1L)
mu[1L] <- 4
logpost <- function(u) {
  if (!is.finite(u) || u < 0) return(-Inf)
  loglik(u) - u/3
}
lp <- logpost(mu[1L])
accepted <- 0L
for (i in seq_len(B)) {
  proposal <- rnorm(1L, mean = mu[i], sd = 1)
  lp_new <- logpost(proposal)
  if (log(runif(1L)) < min(0, lp_new - lp)) {
    mu[i + 1L] <- proposal
    lp <- lp_new
    accepted <- accepted + 1L
  } else {
    mu[i + 1L] <- mu[i]
  }
}
cat("Acceptance fraction =", accepted/B, "\n")
# A provisional discard; assess it with the trace in part (e).
burn <- 1000L
post <- mu[(burn + 2L):(B + 1L)]
m <- xbar - 1/(3*n)
s <- 1/sqrt(n)
posterior_density <- function(u) {
  ans <- numeric(length(u))
  ok <- u >= 0
  ans[ok] <- exp(dnorm(u[ok], m, s, log = TRUE) -
                   pnorm(m/s, log.p = TRUE))
  ans
}
png("q2-posterior.png", width = 900, height = 600)
hist(post, breaks = 40, probability = TRUE, xlab = expression(mu),
     main = "Retained Metropolis draws and exact posterior")
u <- seq(0, max(post) + 3*s, length.out = 4001L)
lines(u, posterior_density(u), col = "firebrick", lwd = 2)
dev.off()
The exact truncated normal distribution density overlays the histogram as a check; it does not replace the requested Markov chain Monte Carlo procedure. The 9,000 retained states exclude the initial state and the first 1,000 transitions. The particular histogram and acceptance fraction remain dependent on the missing measurements.
Probabilistic programming Created 2026-10-24 Updated 2026-10-31
Probabilistic programming expresses a probability model as an executable program with random choices and observations. Executing the generative part induces a probability distribution; observations then restrict or weight executions, and inference computes the resulting conditional distribution. Program syntax and inference algorithm are separate choices: the same model can be evaluated by rejection sampling, importance sampling or Markov chain Monte Carlo.
Trace plot Created 2026-10-14 Updated 2026-10-20
A trace plot displays an observable along successive iterations of a Markov chain Monte Carlo algorithm. Its horizontal axis is iteration and its vertical axis is the observed parameter or function value. Trends suggest an initial transient or slow exploration, separated regimes suggest transitions between posterior regions, and exact plateaus show repeated states. The plot should be read with acceptance statistics, autocorrelation and multiple starting states; its visual appearance alone cannot prove stationarity or identify the unique cause of poor mixing.
WinBUGS 2026-10-14
Software for Bayesian inference through Markov chain Monte Carlo in directed statistical models. Its model language uses dnorm(mean, precision), so the second argument is inverse variance; dcat indexes a supplied probability vector, and dbern introduces a binary latent variable. The model is declarative, so the order of deterministic node definitions does not impose procedural evaluation order.