Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

A MCMC implementation for a non-standard normal

A MCMC implementation for a non-standard normal

This algorithm samples from the posterior distribution of the mean (μ\mu) and precision (τ=1/σ2\tau = 1/\sigma^2) for a normal model, given a set of observed data and conjugate priors.

Model Setup

  • Likelihood:
    For data x1,…,xnx_1, \dots, x_n assumed iid normal:

    xi∼N(μ,τ−1)x_i \sim \mathcal{N}(\mu, \tau^{-1})

    The likelihood (joint density) is:

    p(x∣μ,τ)=∏i=1n[τ2πexp⁡(−τ2(xi−μ)2)]p(\mathbf{x} | \mu, \tau) = \prod_{i=1}^n \left[ \sqrt{\frac{\tau}{2\pi}} \exp\left(-\frac{\tau}{2}(x_i - \mu)^2\right) \right]
  • Priors:

    • For μ\mu:

      μ∼N(μ0,τ0−1)\mu \sim \mathcal{N}(\mu_0, \tau_0^{-1})
      p(μ)=τ02πexp⁡(−τ02(μ−μ0)2)p(\mu) = \sqrt{\frac{\tau_0}{2\pi}} \exp\left(-\frac{\tau_0}{2}(\mu - \mu_0)^2\right)
    • For τ\tau (precision):

      τ∼Gamma(a,b)\tau \sim \text{Gamma}(a, b)
      p(τ)=baΓ(a)τa−1exp⁡(−bτ)p(\tau) = \frac{b^a}{\Gamma(a)} \tau^{a-1} \exp(-b\tau)
  • Posterior:

    p(μ,τ∣x)∝p(x∣μ,τ) p(μ) p(τ)p(\mu, \tau | \mathbf{x}) \propto p(\mathbf{x} | \mu, \tau)\, p(\mu)\, p(\tau)

Algorithm Steps and Equations

  1. Update μ\mu (Metropolis-Hastings step):

    • Proposal: Sample μ∗∼N(μ,δ2)\mu^* \sim \mathcal{N}(\mu, \delta^2)

    • Acceptance ratio:
      Compute the log-acceptance ratio:

      log⁡R=[log⁡p(x∣μ∗,τ)+log⁡p(μ∗)]−[log⁡p(x∣μ,τ)+log⁡p(μ)]\log R = \left[ \log p(\mathbf{x}|\mu^*,\tau) + \log p(\mu^*) \right] - \left[ \log p(\mathbf{x}|\mu,\tau) + \log p(\mu) \right]

      Where

      log⁡p(x∣μ,τ)=∑i=1n(−12log⁡(2π/τ)−τ2(xi−μ)2)\log p(\mathbf{x}|\mu,\tau) = \sum_{i=1}^n \left( -\frac{1}{2}\log(2\pi/\tau) - \frac{\tau}{2}(x_i-\mu)^2 \right)
      log⁡p(μ)=−12log⁡(2π/τ0)−τ02(μ−μ0)2\log p(\mu) = -\frac{1}{2}\log(2\pi/\tau_0) - \frac{\tau_0}{2}(\mu - \mu_0)^2

      The code implements these terms using exponentials and logs for numerical stability.

    • Decision:
      Accept μ∗\mu^* if log⁡U≤log⁡R\log U \leq \log R, where U∼Uniform(0,1)U \sim \text{Uniform}(0,1).

  2. Update τ\tau (Gibbs step):

    • The conditional posterior for τ\tau is:

      τ∣μ,x∼Gamma(a+n2, b+12∑i=1n(xi−μ)2)\tau | \mu, \mathbf{x} \sim \text{Gamma} \left(a + \frac{n}{2},\ b + \frac{1}{2} \sum_{i=1}^n (x_i - \mu)^2 \right)
    • The code samples τ\tau from this gamma distribution at each iteration.

<Figure size 1000x800 with 4 Axes>