The user is asking for a comprehensive Bayesian inference primer covering multiple core topics. Let me organize this into a well-structured educational document with numeric examples for each concept.
Let me plan the structure:
Introduction to Bayesian Inference - The fundamental philosophy and Bayes' theorem
Priors - Types (informative, uninformative, conjugate, hierarchical), how to choose them, examples
Likelihood - The data generating process, likelihood functions for common distributions
Posteriors - How priors and likelihood combine, posterior computation
Conjugacy - Conjugate prior families, examples (Beta-Binomial, Normal-Normal, Gamma-Poisson, etc.)
Credible Intervals - Equal-tailed, HPD intervals, comparison to frequentist confidence intervals
Computational Methods - MCMC (Metropolis-Hastings, Gibbs), Variational Inference
Model Checking - Posterior predictive checks, Bayes factors, information criteria (WAIC, LOO-CV)
Decision Theory - Loss functions, Bayes estimators, decision rules
Let me develop each section with clear explanations and numeric examples.
1. Foundational Concepts - Bayes' Theorem
P(θ|D) = P(D|θ) × P(θ) / P(D)
Where:
P(θ|D) is the posterior
P(D|θ) is the likelihood
P(θ) is the prior
P(D) is the marginal likelihood (evidence)
Simple example: Disease testing
Prior: P(disease) = 0.01
Likelihood: P(positive|disease) = 0.95, P(positive|no disease) = 0.05
What's P(disease|positive)?
Calculation reveals a posterior probability of about 16.1%, showing how Bayes' theorem updates our initial belief based on new evidence
2. Priors
I'll explore different prior types and their implications for probabilistic reasoning. Priors represent our initial knowledge or beliefs before observing data, ranging from completely uninformative to highly specific domain-informed distributions. The choice of prior can significantly impact posterior inference, balancing between mathematical convenience and meaningful domain representation.
3. Likelihood
I'm examining how likelihood functions capture the probability of observing data given specific parameter values. For binomial scenarios, this means quantifying success probabilities across trials. In normal distributions, likelihood integrates individual data point deviations from a proposed mean and variance.
4. Posteriors
Posterior probability reflects the updated belief after incorporating new evidence, proportionally combining prior knowledge with observed data.
In the Beta-Binomial example, I start with a symmetric Beta(2, 2) prior, representing a balanced initial expectation. After observing 7 successes in 10 trials, my posterior shifts to Beta(9, 5), concentrating probability around 0.643. This differs slightly from the maximum likelihood estimate of 0.7, demonstrating how prior information subtly influences parameter estimation.
5. Conjugacy
Conjugate relationships elegantly transform probabilistic inference by ensuring posterior distributions maintain the same parametric family as the prior. Key pairs like Beta-Binomial and Gamma-Poisson enable computational tractability, allowing straightforward Bayesian updates across various statistical domains.
6. Credible Intervals
Credible intervals quantify parameter uncertainty by capturing probability mass. The equal-tailed approach symmetrically cuts off 2.5% from each distribution tail, while Highest Posterior Density (HPD) intervals provide the most compact region representing a specified probability level.
For the Beta(9, 5) distribution, the 95% interval spans approximately (0.41, 0.85), with a mean near 0.643 and mode around 0.667. Skewed distributions reveal nuanced differences between equal-tailed and HPD intervals.
7. Computational Methods
Markov Chain Monte Carlo (MCMC) enables sampling from complex posterior distributions through iterative proposals and acceptance mechanisms. The Metropolis-Hastings algorithm generates candidate parameter values, evaluating their likelihood and prior probability to determine acceptance.
The core steps involve proposing a new parameter, calculating an acceptance ratio based on relative probabilities, and probabilistically transitioning between parameter states to explore the posterior distribution.
Sampling techniques like Gibbs sampling systematically cycle through parameters, drawing each from its full conditional distribution. A simple implementation demonstrates this approach, generating parameter samples by proposing values and accepting them based on posterior probability comparisons.
Variational inference provides an alternative computational strategy, approximating the posterior distribution with a simpler, tractable form. By minimizing the Kullback-Leibler divergence and maximizing the evidence lower bound (ELBO), researchers can efficiently estimate parameter distributions.
Posterior predictive checks validate model performance by generating replicated data from the posterior distribution. This approach allows comparing simulated data with observed data using statistical test statistics, helping assess model fit and reliability.
Bayes factors offer a powerful model comparison technique, quantifying evidence for competing models through likelihood ratios. Researchers can interpret these factors on a scale ranging from barely noteworthy to decisive evidence, providing nuanced insights into model selection.
Decision theory introduces a systematic framework for evaluating actions under uncertainty by defining loss functions. Different loss functions - squared error, absolute error, and 0-1 loss - guide parameter estimation strategies, with the Bayes estimator adapting based on the chosen loss function's characteristics.
The expected posterior loss quantifies the average cost of an action, integrating the loss function with the posterior probability distribution. This allows decision-makers to mathematically assess potential outcomes and select optimal actions.
In a practical drug approval scenario, the loss function captures asymmetric risks: rejecting an effective drug carries different consequences than approving an ineffective one. By computing expected losses for each potential action, decision-makers can rationally choose the minimally costly approach.
The Bayesian framework enables precise risk quantification by combining prior beliefs, observed data, and potential action consequences into a coherent decision-making strategy. # A Comprehensive Bayesian Inference Primer
Table of Contents
Foundational Framework & Bayes' Theorem
Prior Distributions
Likelihood Functions
Posterior Distributions
Conjugate Families
Credible Intervals
Computational Methods (MCMC & VI)
Model Checking & Comparison
Bayesian Decision Theory
1. Foundational Framework & Bayes' Theorem
The Core Philosophy
Bayesian inference treats parameters as random variables with probability distributions reflecting uncertainty. As data arrives, we update our beliefs systematically.
Bayes' Theorem
P ( θ ∣ D ) = P ( D ∣ θ ) ⋅ P ( θ ) P ( D ) P(\theta | D) = \frac{P(D | \theta) \cdot P(\theta)}{P(D)} P ( θ ∣ D ) = P ( D ) P ( D ∣ θ ) ⋅ P
Component Name Interpretation P ( θ ) P(\theta) P ( θ ) Prior Belief about θ before seeing data P ( D ∥ θ ) P(D \| \theta) P ( D ∥ θ ) Likelihood Probability of data given parameter P ( θ ∥ D ) P(\theta \| D) P ( θ ∥ D ) Posterior Updated belief after seeing data
Since P ( D ) P(D) P ( D ) is constant with respect to θ:
P ( θ ∣ D ) ⏟ Posterior ∝ P ( D ∣ θ ) ⏟ Likelihood × P ( θ ) ⏟ Prior \underbrace{P(\theta | D)}_{\text{Posterior}} \propto \underbrace{P(D | \theta)}_{\text{Likelihood}} \times \underbrace{P(\theta)}_{\text{Prior}} Posterior
Numeric Example: Medical Diagnosis
Setup:
Disease prevalence: P ( disease ) = 0.01 P(\text{disease}) = 0.01 P ( disease ) = 0.01
Test sensitivity: P ( positive ∣ disease ) = 0.95 P(\text{positive} | \text{disease}) = 0.95 P ( positive ∣ disease ) = 0.95
False positive rate: P ( positive ∣ healthy ) = 0.05 P(\text{positive} | \text{healthy}) = 0.05
Question: What is P ( disease ∣ positive ) P(\text{disease} | \text{positive}) P ( disease ∣ positive ) ?
P(disease | positive) = P(positive | disease) × P(disease)
───────────────────────────────────
P(positive)
P(positive) = P(pos | disease)×P(disease) + P(pos | healthy)×P(healthy)
= 0.95 × 0.01 + 0.05 × 0.99
= 0.0095 + 0.0495 = 0.059
P(disease | positive) = (0.95 × 0.01) / 0.059
= 0.0095 / 0.059
≈ 0.161 (16.1%)
Insight: Despite a "good" test (95% sensitivity, 5% FPR), a positive result only yields 16% probability of disease due to low base rate.
2. Prior Distributions
Types of Priors
┌─────────────────────────────────────────────────────────────────────┐
│ PRIOR TAXONOMY │
├─────────────────────────────────────────────────────────────────────┤
│ │
│ Informativeness Mathematical Properties │
│ ─────────────── ────────────────────── │
│ │
│ ┌─────────────┐ ┌─────────────┐ │
│ │ Informative │ ←── Domain │ Conjugate │ ←── Closed-form │
│ │ Priors │ knowledge │ Priors │ posteriors │
│ └─────────────┘ └─────────────┘ │
│ ↓ ↓ │
│ ┌─────────────┐ ┌─────────────┐ │
│ │ Weakly │ ←── Mild │ Reference │ ←── Objective/ │
│ │ Informative │ regularization│ Priors │ Jeffreys │
│ └─────────────┘ └─────────────┘ │
│ ↓ ↓ │
│ ┌─────────────┐ ┌─────────────┐ │
│ │ Flat/ │ ←── Maximum │Hierarchical │ ←── Parameters │
│ │ Uniform │ entropy │ Priors │ have priors │
│ └─────────────┘ └─────────────┘ │
│ │
└─────────────────────────────────────────────────────────────────────┘
Examples for Binomial Proportion θ ∈ [0,1]
Prior Parameters Shape Use Case Beta(1, 1) α=1, β=1 Uniform Non-informative Beta(0.5, 0.5) α=β=0.5 U-shaped Jeffreys prior Beta(2, 2) α=β=2 Symmetric hump Weakly informative Beta(10, 2) α=10, β=2 Right-skewed Prior belief θ ≈ 0.83
Beta Distribution Shapes:
Beta(1,1) - Uniform Beta(0.5,0.5) - Jeffreys Beta(2,2) - Symmetric
___ │ │ ∧
| | │ │ / \
| | ╱ ╲ / \
────┴───┴──── ────┘ └──── ──/─────\──
0 1 0 1 0 1
Beta(10,2) - Informative Beta(2,10) - Informative
∧ ∧
/│ │\
/ │ │ \
/ │ │ \
───/───┴─── ───┴───\───
0 1 0 1
Numeric Example: Effect of Prior Strength
Data: 7 successes in 10 trials (MLE = 0.70)
Prior Posterior Posterior Mean Prior Weight Beta(1, 1) Beta(8, 4) 0.667 Minimal Beta(5, 5) Beta(12, 8) 0.600 Moderate Beta(50, 50) Beta(57, 53) 0.518 Strong
Posterior mean formula: (α + successes) / (α + β + n)
Beta(1,1): (1+7)/(1+1+10) = 8/12 = 0.667
Beta(5,5): (5+7)/(5+5+10) = 12/20 = 0.600
Beta(50,50): (50+7)/(50+50+10)= 57/110= 0.518
3. Likelihood Functions
Definition
The likelihood function L ( θ ; D ) \mathcal{L}(\theta; D) L ( θ ; D ) gives the probability of observed data as a function of parameter θ:
L ( θ ; D ) = P ( D ∣ θ ) \mathcal{L}(\theta; D) = P(D | \theta) L ( θ ; D ) = P ( D ∣ θ )
For independent observations:
L ( θ ; x 1 , . . . , x n ) = ∏ i = 1 n P ( x i ∣ θ ) \mathcal{L}(\theta; x_1, ..., x_n) = \prod_{i=1}^{n} P(x_i | \theta) L ( θ ; x 1 , ... , x n )
Common Likelihood Functions
Binomial Likelihood:
L ( θ ; k , n ) = ( n k ) θ k ( 1 − θ ) n − k \mathcal{L}(\theta; k, n) = \binom{n}{k} \theta^k (1-\theta)^{n-k} L ( θ ; k , n ) = ( k n ) θ
Normal Likelihood (known σ):
L ( μ ; x 1 , . . . , x n ) = ∏ i = 1 n 1 2 π σ 2 exp ( − ( x i − μ ) 2 2 σ 2 ) \mathcal{L}(\mu; x_1,...,x_n) = \prod_{i=1}^{n} \frac{1}{\sqrt{2\pi\sigma^2}} \exp\left(-\frac{(x_i - \mu)^2}{2\sigma^2}\right) L ( μ ; x 1 , ... , x
Poisson Likelihood:
L ( λ ; x 1 , . . . , x n ) = ∏ i = 1 n λ x i e − λ x i ! \mathcal{L}(\lambda; x_1,...,x_n) = \prod_{i=1}^{n} \frac{\lambda^{x_i} e^{-\lambda}}{x_i!} L ( λ ; x 1 , ... , x n
Numeric Example: Binomial Likelihood
Data: k = 7 successes in n = 10 trials
# Likelihood at different θ values:
θ = 0.3: L = C(10,7) × 0.3^7 × 0.7^3 = 120 × 0.000219 × 0.343 = 0.009
θ = 0.5: L = C(10,7) × 0.5^7 × 0.5^3 = 120 × 0.0078 × 0.125 = 0.117
θ = 0.7: L = C(10,7) × 0.7^7 × 0.3^3 = 120 × 0.0824 × 0.027 = 0.267 ← Maximum
θ = 0.9: L = C(10,7) × 0.9^7 × 0.1^3 = 120 × 0.478 × 0.001 = 0.057
Likelihood Function (k=7, n=10)
L(θ)
│
│ ●
0.25 ╱ ╲
│ ╱ ╲
│ ╱ ╲
0.15 ╱ ╲
│ ● ●
0.10 ╱ ╲
│ ╱ ╲
0.05 ╱ ╲
│ ● ●
│ ▪ ▪
└───┴─────┴─────┴─────┴─────┴─────┴─────▸ θ
0.1 0.3 0.5 0.7 0.9 1.0
↑
MLE
4. Posterior Distributions
Computing the Posterior
┌────────────────────────────────────────────────────────────┐
│ │
│ Prior × Likelihood = Posterior │
│ │
│ P(θ) P(D|θ) P(θ|D) │
│ │
│ "What we "What data "Updated │
│ believed" tells us" belief" │
│ │
└────────────────────────────────────────────────────────────┘
Numeric Example: Beta-Binomial Model
Setup:
Prior: θ ∼ Beta ( 2 , 2 ) \theta \sim \text{Beta}(2, 2) θ ∼ Beta ( 2 , 2 )
Data: 7 successes in 10 trials
Calculation:
Prior: P(θ) ∝ θ^(2-1) × (1-θ)^(2-1) = θ^1 × (1-θ)^1
Likelihood: L(θ) ∝ θ^7 × (1-θ)^3
Posterior: P(θ|D) ∝ θ^1 × (1-θ)^1 × θ^7 × (1-θ)^3
= θ^8 × (1-θ)^4
This is proportional to Beta(9, 5)
Summary Statistics:
Quantity Prior Beta(2,2) Posterior Beta(9,5) Mean 0.500 0.643 Mode 0.500 0.667 Variance 0.050 0.015 95% CI [0.094, 0.906] [0.387, 0.857]
Prior vs Posterior:
P(θ)
│ Prior Beta(2,2) Posterior Beta(9,5)
│
3.0│ ●
│ ╱ ╲
2.5│ ╱ ╲
│ ╱ ╲
2.0│ ● ╲
│ ●───────● ╱ ●
1.5│ ╱ ╲ ╱
│ ╱ ╲ ╱ ╲
1.0│ ╱ ╲ ● ╲
│ ● ● ╱ ●
0.5│ ╱ ╲ ● ╲
│● ● ╱ ●
└┴─────┴─────┴─────┴─┴─┴─────┴─────┴─────┴─────▸ θ
0 0.2 0.4 0.6 0.8 1.0
↑
7/10 = 0.7 (MLE)
Sequential Updating
Bayesian inference naturally handles streaming data:
Day 1: Prior Beta(2,2), observe 3/5 successes → Posterior Beta(5,4)
Day 2: Prior Beta(5,4), observe 4/5 successes → Posterior Beta(9,5)
Day 3: Prior Beta(9,5), observe 2/5 successes → Posterior Beta(11,8)
Equivalently: Beta(2,2) + 9/15 total → Beta(11,8)
5. Conjugate Prior Families
Definition
A prior is conjugate to a likelihood if the posterior belongs to the same distributional family as the prior.
Major Conjugate Families
┌─────────────────────────────────────────────────────────────────────────┐
│ CONJUGATE PRIOR TABLE │
├────────────────┬────────────────┬────────────────┬──────────────────────┤
│ Likelihood │ Prior │ Posterior │ Posterior Params │
├────────────────┼────────────────┼────────────────┼──────────────────────┤
│ Binomial(n,θ) │ Beta(α,β) │ Beta(α',β') │ α'=α+k, β'=β+n-k │
├────────────────┼────────────────┼────────────────┼──────────────────────┤
│ Poisson(λ) │ Gamma(α,β) │ Gamma(α',β') │ α'=α+Σxᵢ, β'=β+n │
├────────────────┼────────────────┼────────────────┼──────────────────────┤
│ Normal(μ,σ²) │ Normal(μ₀,σ₀²) │ Normal(μ',σ'²) │ Precision-weighted │
│ (σ² known) │ │ │ average (see below) │
├────────────────┼────────────────┼────────────────┼──────────────────────┤
│ Normal(μ,σ²) │ Inv-Gamma(α,β) │ Inv-Gamma(α',β')│ α'=α+n/2 │
│ (μ known) │ │ │ β'=β+Σ(xᵢ-μ)²/2 │
├────────────────┼────────────────┼────────────────┼──────────────────────┤
│ Multinomial │ Dirichlet(α) │ Dirichlet(α') │ α'ₖ = αₖ + nₖ │
├────────────────┼────────────────┼────────────────┼──────────────────────┤
│ Exponential(λ) │ Gamma(α,β) │ Gamma(α',β') │ α'=α+n, β'=β+Σxᵢ │
└────────────────┴────────────────┴────────────────┴──────────────────────┘
Numeric Example 1: Poisson-Gamma
Modeling website visits per hour:
Prior belief: λ ∼ Gamma ( 10 , 2 ) \lambda \sim \text{Gamma}(10, 2) λ ∼ Gamma ( 10 , 2 ) (mean = 5 visits/hour)
Observed data: [4, 7, 6, 3, 5, 8, 6, 4, 5, 7] over 10 hours
Posterior: λ | data ~ Gamma(α + Σx, β + n)
= Gamma(10 + 55, 2 + 10)
= Gamma(65, 12)
Prior mean: 10/2 = 5.0 visits/hour
MLE: 55/10 = 5.5 visits/hour
Posterior mean: 65/12 ≈ 5.42 visits/hour
Numeric Example 2: Normal-Normal (Known Variance)
Estimating true weight μ, with σ² = 4 known:
Prior: μ ∼ N ( μ 0 = 150 , σ 0 2 = 25 ) \mu \sim N(\mu_0 = 150, \sigma_0^2 = 25) μ ∼ N ( μ 0 = 150 , σ 0 2
Data: x = [148, 152, 149, 151, 150] (n=5, x̄=150)
Posterior formulas:
σ ′ 2 = ( 1 σ 0 2 + n σ 2 ) − 1 \sigma'^2 = \left(\frac{1}{\sigma_0^2} + \frac{n}{\sigma^2}\right)^{-1} σ ′2 = ( σ 0
μ ′ = σ ′ 2 ( μ 0 σ 0 2 + n x ˉ σ 2 ) \mu' = \sigma'^2 \left(\frac{\mu_0}{\sigma_0^2} + \frac{n\bar{x}}{\sigma^2}\right) μ ′ = σ ′2 (
Calculation:
Prior precision: 1/σ₀² = 1/25 = 0.04
Data precision: n/σ² = 5/4 = 1.25
Posterior precision: 0.04 + 1.25 = 1.29
Posterior variance: σ'² = 1/1.29 ≈ 0.775
Posterior mean: μ' = 0.775 × (150/25 + 5×150/4)
= 0.775 × (6 + 187.5)
= 0.775 × 193.5
≈ 150.0
Posterior: μ | data ~ N(150.0, 0.775)
95% CI: 150 ± 1.96×√0.775 = [148.3, 151.7]
6. Credible Intervals
Types of Credible Intervals
┌──────────────────────────────────────────────────────────────────┐
│ │
│ Equal-Tailed Interval (ETI) Highest Density Interval (HDI)│
│ ──────────────────────── ───────────────────────── │
│ │
│ • 2.5% in each tail • Shortest interval with │
│ • Easy to compute given probability │
│ • May not be shortest • All points inside have │
│ higher density than outside │
│ │
│ ┌─────────────┐ ┌─────────────┐ │
│ ╱│ │╲ │ │ │
│ ╱ │ │ ╲ │ │ │
│ ╱ │ │ ╲ │ │ │
│ ╱ │ │ ╲ │ │ │
│ ▓▓▓▓▓│█████████████│▓▓▓▓▓ │█████████████████████│ │
│ 2.5% │ 95% │2.5% │ 95% │ │
│ ↑ ↑ ↑ ↑ │
│ q.025 q.975 HDI_low HDI_high │
│ │
└──────────────────────────────────────────────────────────────────┘
Numeric Example: Skewed Posterior
Posterior: θ ∼ Gamma ( 3 , 1 ) \theta \sim \text{Gamma}(3, 1) θ ∼ Gamma ( 3 , 1 )
Summary Statistics:
Mean: 3.0
Median: 2.67
Mode: 2.0
Variance: 3.0
95% Equal-Tailed Interval:
Lower (2.5%): 0.619
Upper (97.5%): 7.224
Width: 6.605
95% Highest Density Interval:
Lower: 0.355
Upper: 6.296
Width: 5.941 ← Shorter!
Gamma(3,1) with Intervals:
p(θ)
│
│ ●
0.2│ ╱╲
│╱ ╲
│ ╲
0.1 ╲●
│ ╲───●────●────●
│
└─┬──┬──────────────┬──┬───▸ θ
│ │ │ │
│ └──────────────┘ │
│ 95% ETI │
└────────────────────┘
95% HDI (shorter)
Comparison with Frequentist Confidence Intervals
Aspect Credible Interval Confidence Interval Interpretation "95% probability θ is in interval" "95% of such intervals contain true θ" Fixed quantity Interval Parameter θ Random quantity Neither (posterior is fixed) Interval endpoints Single experiment Direct probability statement Cannot make probability statement
7. Computational Methods
Why Computation?
Most posteriors lack closed-form solutions. We need numerical methods.
┌─────────────────────────────────────────────────────────────────┐
│ COMPUTATIONAL METHODS │
├─────────────────────────────────────────────────────────────────┤
│ │
│ ┌──────────────────────┐ │
│ │ Target: P(θ|D) │ │
│ └──────────┬───────────┘ │
│ │ │
│ ┌─────────────┴─────────────┐ │
│ ↓ ↓ │
│ ┌───────────────┐ ┌───────────────┐ │
│ │ MCMC │ │ Variational │ │
│ │ (Sampling) │ │ Inference │ │
│ └───────┬───────┘ └───────┬───────┘ │
│ │ │ │
│ ┌───────┴───────┐ ┌───────┴───────┐ │
│ │ • Exact │ │ • Approximate │ │
│ │ • Slow │ │ • Fast │ │
│ │ • Convergence │ │ • Scalable │ │
│ │ diagnostics │ │ • Local optima│ │
│ └───────────────┘ └───────────────┘ │
│ │
└─────────────────────────────────────────────────────────────────┘
MCMC: Markov Chain Monte Carlo
Metropolis-Hastings Algorithm
Algorithm: Metropolis-Hastings
─────────────────────────────────────────────────────────
Input: Initial θ₀, proposal distribution q(θ'|θ), iterations N
Output: Samples {θ₁, θ₂, ..., θₙ}
1. Set t = 0, start at θ₀
2. For t = 1 to N:
a. Propose: θ' ~ q(θ'|θₜ₋₁)
b. Compute acceptance ratio:
P(θ'|D) × q(θₜ₋₁|θ')
α = ─────────────────────────
P(θₜ₋₁|D) × q(θ'|θₜ₋₁)
c. Accept with probability min(1, α):
- Draw u ~ Uniform(0,1)
- If u < α: θₜ = θ' (accept)
- Else: θₜ = θₜ₋₁ (reject)
3. Return {θ₁, θ₂, ..., θₙ} (discard burn-in)
─────────────────────────────────────────────────────────
Numeric Example: MH for Beta Posterior
Target: θ ∣ data ∝ θ 8 ( 1 − θ ) 4 \theta | \text{data} \propto \theta^8(1-\theta)^4 θ ∣ data ∝ θ 8 ( 1 − θ ) 4 (Beta(9,5))
import numpy as np
def log_posterior(theta):
if theta <= 0 or theta >= 1:
return -np.inf
return 8 * np.log(theta) + 4 * np.log(1 - theta)
# Metropolis-Hastings
np.random.seed(42)
n_samples = 10000
samples = np.zeros(n_samples)
theta = 0.5 # Initial value
accepted = 0
for i in range(n_samples):
# Propose from normal centered at current (random walk)
theta_prop = theta + np.random.normal(0, 0.1)
# Log acceptance ratio
log_alpha = log_posterior(theta_prop) - log_posterior(theta)
# Accept/reject
if np.log(np.random.uniform()) < log_alpha:
theta = theta_prop
accepted += 1
samples[i] = theta
# Results (after burn-in of 1000)
samples = samples[1000:]
print(f"Acceptance rate: {accepted/n_samples:.2%}")
print(f"Posterior mean: {np.mean(samples):.3f}") # True: 0.643
print(f"Posterior std: {np.std(samples):.3f}") # True: 0.124
Output:
Acceptance rate: 52.3%
Posterior mean: 0.641
Posterior std: 0.122
95% CI: [0.393, 0.854]
Gibbs Sampling
Special case of MH where we sample each parameter from its full conditional .
Algorithm: Gibbs Sampling
─────────────────────────────────────────────────────────
For parameters θ = (θ₁, θ₂, ..., θₖ):
1. Initialize θ₁⁰, θ₂⁰, ..., θₖ⁰
2. For t = 1 to N:
θ₁ᵗ ~ P(θ₁ | θ₂ᵗ⁻¹, θ₃ᵗ⁻¹, ..., θₖᵗ⁻¹, data)
θ₂ᵗ ~ P(θ₂ | θ₁ᵗ, θ₃ᵗ⁻¹, ..., θₖᵗ⁻¹, data)
...
θₖᵗ ~ P(θₖ | θ₁ᵗ, θ₂ᵗ, ..., θₖ₋₁ᵗ, data)
3. Return samples
─────────────────────────────────────────────────────────
Example: Normal Model (unknown μ and σ²)
Full conditionals:
μ | σ², data ~ Normal(...)
σ² | μ, data ~ Inverse-Gamma(...)
Cycle:
Step 1: Draw μ from Normal given current σ²
Step 2: Draw σ² from Inv-Gamma given just-drawn μ
Repeat
Variational Inference
Approximate the posterior p ( θ ∣ D ) p(\theta|D) p ( θ ∣ D ) with a simpler distribution q ( θ ) q(\theta) q ( θ ) by minimizing KL divergence.
┌─────────────────────────────────────────────────────────────────┐
│ VARIATIONAL INFERENCE │
├─────────────────────────────────────────────────────────────────┤
│ │
│ Objective: Minimize KL(q(θ) || p(θ|D)) │
│ │
│ Equivalent to maximizing ELBO: │
│ │
│ ELBO(q) = 𝔼_q[log p(D,θ)] - 𝔼_q[log q(θ)] │
│ = 𝔼_q[log p(D|θ)] - KL(q(θ) || p(θ)) │
│ └────┬────┘ └─────┬─────┘ │
│ Expected log Complexity penalty │
│ likelihood │
│ │
│ Mean-Field Approximation: │
│ q(θ) = q(θ₁)q(θ₂)...q(θₖ) (independence assumption) │
│ │
└─────────────────────────────────────────────────────────────────┘
MCMC vs VI Comparison:
Aspect MCMC VI Accuracy Exact (asymptotically) Approximate Speed Slower Faster Scalability O(n) per iteration Can use mini-batches Convergence Diagnostic tools Monitor ELBO Uncertainty Full posterior May underestimate Best for Final inference Exploration, big data
8. Model Checking & Comparison
Posterior Predictive Checks
Idea: If model is good, simulated data should look like observed data.
┌────────────────────────────────────────────────────────────────┐
│ POSTERIOR PREDICTIVE CHECK │
├────────────────────────────────────────────────────────────────┤
│ │
│ 1. Draw θ⁽ˢ⁾ from posterior p(θ|D) │
│ 2. Simulate y_rep from p(y|θ⁽ˢ⁾) │
│ 3. Compute test statistic T(y_rep) │
│ 4. Repeat many times │
│ 5. Compare distribution of T(y_rep) to T(y_observed) │
│ │
│ │
│ Distribution of T(y_rep) │
│ ┌───┐ │
│ ╱│ │╲ │
│ ╱ │ │ ╲ │
│ ╱ │ │ ╲ │
│ ╱ │ │ ╲ │ │
│ ───────╱────┴───┴────╲───────────▲─────── │
│ │ │
│ T(y_observed) │
│ │
│ Bayesian p-value = P(T(y_rep) ≥ T(y_obs)) │
│ Values near 0 or 1 indicate model misfit │
│ │
└────────────────────────────────────────────────────────────────┘
Numeric Example: Checking Poisson Assumption
Model: y i ∼ Poisson ( λ ) y_i \sim \text{Poisson}(\lambda) y i ∼ Poisson ( λ ) , posterior λ ∼ Gamma ( 65 , 12 ) \lambda \sim \text{Gamma}(65, 12) λ ∼ Gamma ( 65 , 12 )
Observed data: [4, 7, 6, 3, 5, 8, 6, 4, 5, 7]
Mean = 5.5
Variance = 2.5 ← Much smaller than mean (under-dispersed)
For Poisson: variance should equal mean
# Posterior predictive check
n_sim = 5000
y_obs = [4, 7, 6, 3, 5, 8, 6, 4, 5, 7]
variance_obs = np.var(y_obs, ddof=0)
ppc_variances = []
for _ in range(n_sim):
# Draw lambda from posterior
lam = np.random.gamma(65, 1/12)
# Simulate data
y_rep = np.random.poisson(lam, size=10)
ppc_variances.append(np.var(y_rep, ddof=0))
# Bayesian p-value
p_value = np.mean(np.array(ppc_variances) <= variance_obs)
print(f"Bayesian p-value: {p_value:.3f}")
# Output: ~0.02 → Evidence against Poisson model
Bayes Factors
Definition: Ratio of marginal likelihoods
B F 12 = P ( D ∣ M 1 ) P ( D ∣ M 2 ) = ∫ P ( D ∣ θ , M 1 ) P ( θ ∣ M 1 ) d θ ∫ P ( D ∣ ϕ , M 2 ) P ( ϕ ∣ M 2 ) d ϕ BF_{12} = \frac{P(D|M_1)}{P(D|M_2)} = \frac{\int P(D|\theta, M_1)P(\theta|M_1)d\theta}{\int P(D|\phi, M_2)P(\phi|M_2)d\phi} B F 12 =
Interpretation Scale:
log 10 ( B F 12 ) \log_{10}(BF_{12}) log 10 ( B F 12 ) B F 12 BF_{12} B F
Numeric Example: Bayes Factor
Comparing: M 1 M_1 M 1 : θ = 0.5 vs M 2 M_2 M 2 : θ ~ Beta(1,1)
Data: 7 successes in 10 trials
M₁ (point null): P(D|M₁) = C(10,7) × 0.5^7 × 0.5^3
= 120 × 0.0078 × 0.125
= 0.117
M₂ (Beta prior): P(D|M₂) = ∫ C(10,7) × θ^7 × (1-θ)^3 × 1 dθ
= 120 × B(8,4) / B(1,1)
= 120 × [Γ(8)Γ(4)/Γ(12)] / 1
= 120 × [7! × 3!] / 11!
= 120 / 495
= 0.242
BF₁₂ = 0.117 / 0.242 = 0.48
Evidence ratio favors M₂ by factor of ~2
Information Criteria
WAIC (Widely Applicable Information Criterion):
WAIC = − 2 ( lppd − p WAIC ) \text{WAIC} = -2(\text{lppd} - p_{\text{WAIC}}) WAIC = − 2 ( lppd − p WAIC )
Where:
lppd = log pointwise predictive density
p WAIC p_{\text{WAIC}} p WAIC = effective number of parameters
LOO-CV (Leave-One-Out Cross-Validation):
LOO = − 2 ∑ i = 1 n log P ( y i ∣ y − i ) \text{LOO} = -2 \sum_{i=1}^{n} \log P(y_i | y_{-i}) LOO = − 2 ∑ i = 1 n log P ( y
Efficiently computed using Pareto-smoothed importance sampling (PSIS).
9. Bayesian Decision Theory
Framework
┌─────────────────────────────────────────────────────────────────┐
│ DECISION THEORY FRAMEWORK │
├─────────────────────────────────────────────────────────────────┤
│ │
│ Components: │
│ ─────────── │
│ • State space Θ: possible values of unknown parameter │
│ • Action space 𝒜: possible decisions │
│ • Loss function L(θ, a): cost of action a when true state is θ │
│ │
│ Bayes Risk (Expected Posterior Loss): │
│ ───────────────────────────────────── │
│ │
│ ρ(a|D) = 𝔼[L(θ,a)|D] = ∫ L(θ,a) p(θ|D) dθ │
│ │
│ Bayes Action: │
│ ───────────── │
│ │
│ a* = argmin ρ(a|D) │
│ a∈𝒜 │
│ │
└─────────────────────────────────────────────────────────────────┘
Common Loss Functions and Bayes Estimators
Loss Function Formula Bayes Estimator Squared Error (L2) ( θ − a ) 2 (θ - a)^2 ( θ − a ) 2 Posterior Mean Absolute Error (L1) $ θ - a 0-1 Loss 1 ( θ ≠ a ) \mathbb{1}(θ ≠ a) 1 ( θ =
Numeric Example 1: Point Estimation
Posterior: θ ∼ Gamma ( 3 , 1 ) \theta \sim \text{Gamma}(3, 1) θ ∼ Gamma ( 3 , 1 )
Statistics:
Mean: 3.0
Median: 2.67
Mode: 2.0
Under squared error loss: choose â = 3.0 (mean)
Under absolute error loss: choose â = 2.67 (median)
Under 0-1 loss: choose â = 2.0 (mode)
Numeric Example 2: Binary Decision
Context: Decide whether to launch a product based on estimated market share θ
Posterior: θ ∼ Beta ( 9 , 5 ) \theta \sim \text{Beta}(9, 5) θ ∼ Beta ( 9 , 5 )
Actions:
a = 1 a = 1 a = 1 : Launch product
a = 0 a = 0 a = 0 : Don't launch
Loss function:
θ < 0.5 (fail) θ ≥ 0.5 (success) Launch (a=1) 100 (big loss) 0 Don't launch (a=0) 0 20 (missed opportunity)
Expected loss calculations:
P(θ < 0.5 | data) = P(Beta(9,5) < 0.5) ≈ 0.133
P(θ ≥ 0.5 | data) ≈ 0.867
E[Loss | Launch] = 100 × P(θ < 0.5) + 0 × P(θ ≥ 0.5)
= 100 × 0.133 + 0
= 13.3
E[Loss | Don't Launch] = 0 × P(θ < 0.5) + 20 × P(θ ≥ 0.5)
= 0 + 20 × 0.867
= 17.3
Decision: Launch (lower expected loss: 13.3 < 17.3)
Numeric Example 3: Optimal Threshold
Find θ such that: Launch if posterior mean > θ **
Expected loss as function of threshold:
E[Loss](θ*) = 100 × P(θ < θ*) × I(launch)
+ 20 × P(θ ≥ θ*) × I(don't launch)
At break-even point:
100 × P(θ < θ*) = 20 × P(θ ≥ θ*)
100 × F(θ*) = 20 × (1 - F(θ*))
120 × F(θ*) = 20
F(θ*) = 1/6 ≈ 0.167
For Beta(9,5): θ* ≈ 0.48
Rule: Launch if P(θ > 0.48 | data) > 5/6
Summary: The Bayesian Workflow
┌─────────────────────────────────────────────────────────────────────┐
│ THE BAYESIAN WORKFLOW │
├─────────────────────────────────────────────────────────────────────┤
│ │
│ ┌──────────────┐ │
│ │ 1. SPECIFY │ • Choose likelihood for data-generating process │
│ │ MODEL │ • Choose prior distributions │
│ └──────┬───────┘ • Encode domain knowledge │
│ ↓ │
│ ┌──────────────┐ │
│ │ 2. COMPUTE │ • Analytical (conjugate priors) │
│ │ POSTERIOR │ • MCMC (Stan, PyMC, JAGS) │
│ └──────┬───────┘ • Variational inference │
│ ↓ │
│ ┌──────────────┐ │
│ │ 3. CHECK │ • MCMC diagnostics (R-hat, ESS, trace plots) │
│ │ COMPUTATION │ • Convergence assessment │
│ └──────┬───────┘ • VI: ELBO monitoring │
│ ↓ │
│ ┌──────────────┐ │
│ │ 4. VALIDATE │ • Posterior predictive checks │
│ │ MODEL │ • Cross-validation (LOO-CV) │
│ └──────┬───────┘ • Prior sensitivity analysis │
│ ↓ │
│ ┌──────────────┐ │
│ │ 5. COMPARE │ • Bayes factors │
│ │ MODELS │ • Information criteria (WAIC, LOO) │
│ └──────┬───────┘ • Stacking/model averaging │
│ ↓ │
│ ┌──────────────┐ │
│ │ 6. DECIDE │ • Summarize posterior (mean, credible intervals)│
│ │ & REPORT │ • Apply decision theory │
│ └──────────────┘ • Communicate uncertainty │
│ │
└─────────────────────────────────────────────────────────────────────┘
Quick Reference Card
┌─────────────────────────────────────────────────────────────────────┐
│ BAYESIAN QUICK REFERENCE │
├─────────────────────────────────────────────────────────────────────┤
│ │
│ BAYES' THEOREM: P(θ|D) ∝ P(D|θ) × P(θ) │
│ │
│ KEY CONJUGATE PAIRS: │
│ ────────────────────── │
│ Binomial + Beta(α,β) → Beta(α+k, β+n-k) │
│ Poisson + Gamma(α,β) → Gamma(α+Σx, β+n) │
│ Normal + Normal → Normal (precision-weighted) │
│ │
│ BETA DISTRIBUTION FACTS: │
│ ──────────────────────── │
│ Mean = α/(α+β) Mode = (α-1)/(α+β-2) │
│ Var = αβ/[(α+β)²(α+β+1)] │
│ │
│ GAMMA DISTRIBUTION FACTS: │
│ ───────────────────────── │
│ Mean = α/β Mode = (α-1)/β (α≥1) │
│ Var = α/β² │
│ │
│ LOSS FUNCTIONS → ESTIMATORS: │
│ ──────────────────────────── │
│ Squared error → Posterior mean │
│ Absolute error → Posterior median │
│ 0-1 loss → Posterior mode (MAP) │
│ │
│ MCMC DIAGNOSTICS: │
│ ───────────────── │
│ R-hat < 1.01: Good convergence │
│ ESS > 400: Sufficient effective samples │
│ Trace plots: Should look like "fuzzy caterpillars" │
│ │
│ BAYES FACTOR INTERPRETATION: │
│ ──────────────────────────── │
│ BF > 100: Decisive evidence │
│ BF 10-100: Strong evidence │
│ BF 3-10: Moderate evidence │
│ BF 1-3: Weak evidence │
│ │
└─────────────────────────────────────────────────────────────────────┘
This primer covers the essential concepts needed to understand and apply Bayesian inference. The key insight is that Bayesian methods provide a coherent framework for updating beliefs with data and making decisions under uncertainty—all while properly quantifying that uncertainty throughout the analysis.