flowchart TD
A["Prior"] --> B["Likelihood from data"]
B --> C["Posterior"]
C --> D["Parameter draws"]
D --> E["Replicated observations"]
E --> F["Compare model and data"]
14 Bayesian inference
Frequentist procedures describe the repeated-sampling behavior of estimators and tests when the parameter is fixed. Bayesian inference describes uncertainty about unknown quantities by placing a probability model on them. Both frameworks use the likelihood, but they interpret the result differently.
14.1 From prior to posterior
Let \(\theta\) be an unknown parameter and \(x\) the observed data. Specify a prior distribution \(\pi(\theta)\) and likelihood \(f(x\mid\theta)\). The joint density is \(\pi(\theta)f(x\mid\theta)\). Bayes’ theorem gives
\[ \boxed{\pi(\theta\mid x)=\frac{f(x\mid\theta)\pi(\theta)} {m(x)}},\qquad m(x)=\int_\Theta f(x\mid u)\pi(u)\,du. \]
For discrete parameters, replace the integral by a sum. The normalizing constant \(m(x)\) is the marginal likelihood, also called the evidence or prior predictive density. A posterior is a genuine probability distribution on the parameter space under the specified joint model. Thus a common computational shortcut writes \(\pi(\theta\mid x)\propto f(x\mid\theta)\pi(\theta)\) and retains only factors involving \(\theta\).
The likelihood is not a prior or a posterior by itself. For example, a flat prior in \(\theta\) is not flat in \(\theta^2\); densities transform with a Jacobian. Prior choices and parameterizations are part of the modeling assumptions.
A proper prior integrates to one. Some theoretical procedures use improper priors (formal nonintegrable measures); their posterior must be checked for integrability separately, and ordinary marginal-likelihood comparisons then become problematic.
14.1.1 Example: competing equipment modes
A device operates in one of two unknown persistent modes \(A\) and \(B\), with prior probabilities .7 and .3. The probability of a positive diagnostic reading is .2 in mode \(A\) and .8 in mode \(B\). After two conditionally independent positive readings,
\[ P(B\mid++)=\frac{.3(.8)^2}{.7(.2)^2+.3(.8)^2} =\frac{.192}{.22}\approx.873. \]
The same observation updates every competing hypothesis by its likelihood. This is the finite version of the posterior-density formula.
14.2 Conjugate models
A prior family is conjugate to a likelihood family if the posterior remains within that prior family. Conjugacy gives useful closed-form calculations and intuition. It is a computational property, not a requirement of Bayesian reasoning.
14.2.1 Beta–binomial
Suppose \(X_i\mid p\overset{\rm iid}{\sim}\operatorname{Bernoulli}(p)\) and \(p\sim\operatorname{Beta}(a,b)\) with \(a,b>0\). The prior density on \((0,1)\) is
\[ \pi(p)=\frac{p^{a-1}(1-p)^{b-1}}{B(a,b)}. \]
Given \(s=\sum_i x_i\), the likelihood is proportional to \(p^s(1-p)^{n-s}\). Multiplying,
\[ \pi(p\mid x)\propto p^{a+s-1}(1-p)^{b+n-s-1}. \]
This is the kernel of another beta density, so after normalizing,
\[ p\mid x\sim\operatorname{Beta}(a+s,b+n-s). \]
The posterior mean is
\[ \frac{a+s}{a+b+n} =\frac{a+b}{a+b+n}\frac{a}{a+b} +\frac{n}{a+b+n}\frac{s}{n}. \]
It is a weighted average of the prior mean and the observed proportion. The sum \(a+b\) controls the prior concentration at a fixed mean; it behaves algebraically like a prior sample weight. For \(a,b>1\) the posterior mode (if interior) is \((a+s-1)/(a+b+n-2)\).
For \(a=3,b=3\), observing 16 successes in 20 trials yields \(\operatorname{Beta}(19,7)\) and posterior mean \(19/26\approx.731\) rather than the MLE .8. The prior shrinks the estimate toward .5. With the same prior and many more trials, the likelihood normally dominates this weight.
14.2.2 Gamma–Poisson
Suppose \(X_i\mid\lambda\sim\operatorname{Poisson}(\lambda)\) independently, and place a \(\operatorname{Gamma}(a,b)\) prior (shape-rate) on \(\lambda\). The likelihood kernel is \(\lambda^{s}e^{-n\lambda}\). Multiplying by the prior kernel \(\lambda^{a-1}e^{-b\lambda}\) yields
\[ \lambda\mid x\sim\operatorname{Gamma}(a+s,b+n). \]
Its mean \((a+s)/(b+n)\) is a weighted average of \(a/b\) and \(s/n\), with weights proportional to \(b\) and \(n\). For count windows of unequal known exposures \(t_i>0\), replacing \(n\) by \(\sum_i t_i\) gives the same derivation from \(X_i\sim\operatorname{Poisson}(\lambda t_i)\).
14.2.3 Normal–normal
Let \(X_i\mid\mu\sim N(\mu,\sigma^2)\) independently with known \(\sigma^2\), and \(\mu\sim N(m_0,v_0)\). The log posterior, ignoring constants in \(\mu\), is
\[ -\frac{(\mu-m_0)^2}{2v_0} -\frac{\sum_i(x_i-\mu)^2}{2\sigma^2}. \]
Collect the quadratic and linear terms:
\[ -\frac12\left(\frac1{v_0}+\frac n{\sigma^2}\right)\mu^2 +\left(\frac{m_0}{v_0}+\frac{n\bar x}{\sigma^2}\right)\mu. \]
Completing the square gives
\[ v_n=\left(\frac1{v_0}+\frac n{\sigma^2}\right)^{-1}, \qquad m_n=v_n\left(\frac{m_0}{v_0}+\frac{n\bar x}{\sigma^2}\right) \]
and \(\mu\mid x\sim N(m_n,v_n)\). Information expressed as precision (inverse variance) adds. If prior uncertainty is high, \(1/v_0\) is small and the posterior mean approaches the sample mean.
14.3 Bayesian point and interval estimates
In Bayesian decision theory, an action \(d\) incurs loss \(L(d,\theta)\); choose \(d\) to minimize posterior expected loss. For squared-error loss,
\[ E[(d-\theta)^2\mid x]=(d-E[\theta\mid x])^2+\operatorname{Var}(\theta\mid x), \]
so the posterior mean is optimal if the second moment exists. The posterior median minimizes expected absolute loss by the same derivative sign argument used for sample medians (or by a subgradient argument for atoms). The maximum a posteriori (MAP) estimate maximizes posterior density. Unlike the posterior mean under a specified loss, a continuous MAP depends on the coordinate system used to express the density.
A \(100(1-\alpha)\%\) credible interval is a posterior interval \([l,u]\) with probability
\[ P(l\le\theta\le u\mid x)=1-\alpha. \]
An equal-tail interval uses the posterior \(\alpha/2\) and \(1-\alpha/2\) quantiles. A highest-posterior-density region includes parameter values with density above a threshold chosen to give the desired mass; it may be disconnected. Credibility is explicitly conditional on the model, prior and observed data. It is not a promise of exact frequentist coverage for every true parameter.
from scipy import stats
a,b,s,n = 3,3,16,20
posterior = stats.beta(a+s,b+n-s)
print("mean",posterior.mean(),"MAP",(a+s-1)/(a+b+n-2))
print("95% credible interval",posterior.ppf([.025,.975]))
print("P(p > .65 | x)",posterior.sf(.65))14.4 Posterior prediction
Prediction integrates uncertainty rather than plugging in one estimated parameter:
\[ f(x_{\rm new}\mid x)=\int f(x_{\rm new}\mid\theta,x)\pi(\theta\mid x)\,d\theta. \]
Under conditional independence the first factor is \(f(x_{\rm new}\mid\theta)\). For a Bernoulli future trial, the predictive success probability is \(E[p\mid x]\). For \(K\) successes in \(m\) future trials under the beta posterior with parameters \(a',b'\),
\[ \begin{aligned} P(K=k\mid x) &=\int_0^1\binom mk p^k(1-p)^{m-k} \frac{p^{a'-1}(1-p)^{b'-1}}{B(a',b')}\,dp\\ &=\binom mk\frac{B(a'+k,b'+m-k)}{B(a',b')}. \end{aligned} \]
This beta-binomial law differs from \(\operatorname{Binomial}(m,E[p\mid x])\). Conditional on \(p\) the future trials are independent, but integrating over the common \(p\) induces dependence. The predictive variance of a future count, by total variance, is
\[ \operatorname{Var}(K\mid x) =mE[p(1-p)\mid x]+m^2\operatorname{Var}(p\mid x). \]
The second term captures uncertainty in the success probability.
For the normal–normal model, a future observation is \(\mu+\epsilon\), with \(\mu\mid x\sim N(m_n,v_n)\) and independent \(\epsilon\sim N(0,\sigma^2)\). Therefore its posterior predictive distribution is \(N(m_n,v_n+\sigma^2)\).
14.5 Model checking and sensitivity
The posterior is conditional on the model. A precise estimate under a badly fitting likelihood can still be misleading. A useful check is to sample \(\theta^{(b)}\) from the posterior, then replicated data \(x_{\rm rep}^{(b)}\) from the model at that parameter. Compare features of replicated datasets to the same features of the observed sample. A systematic mismatch suggests the likelihood or prior predictive behavior deserves revision.
For example, a Poisson model has conditional variance equal to its mean. A dataset with many zeros and occasional unusually large counts may exhibit overdispersion that a single Poisson rate cannot explain. Posterior predictive checks visualize this mismatch. They are diagnostic comparisons, not ordinary uniformly calibrated classical p-values.
14.6 Practice problems
Work in your browser with Google Colab, or download the notebooks for Jupyter.
Practice notebook
Worked solutions
14.6.1 Exercise 1: Update a success probability
Begin with \(p\sim\operatorname{Beta}(2,5)\). Observe seven successes in ten trials. Find the posterior, its mean and its mode. What is the probability of success on the next trial?
The posterior is \(\operatorname{Beta}(9,8)\), with mean \(9/17\approx.5294\). Its interior mode is \(8/15\approx.5333\). The posterior predictive success probability is the posterior mean \(9/17\).
14.6.2 Exercise 2: Conjugacy with exposure
The rate of events per hour has prior \(\operatorname{Gamma}(2,1)\). Independent windows of lengths two and four hours contain counts three and nine. Derive the posterior for the common rate and its expected value.
The data likelihood kernel is \(\lambda^{3+9}e^{-(2+4)\lambda}\). Hence the posterior is \(\operatorname{Gamma}(14,7)\), with mean \(14/7=2\) events per hour. The observation-specific exposure powers and factorial terms cancel in normalization because they do not depend on \(\lambda\).
14.6.3 Exercise 3: Combining normal evidence
Suppose \(\mu\sim N(10,4)\) and \(X_i\mid\mu\sim N(\mu,9)\) with \(n=9\) and \(\bar x=13\). Find the posterior mean, variance, and predictive variance of a new observation.
The prior precision is \(1/4\) and the data precision is \(9/9=1\). The posterior variance is \(1/1.25=0.8\). Its mean is \(0.8(10/4+13)=12.4\). The predictive variance is \(0.8+9=9.8\); the future observation distribution is \(N(12.4,9.8)\).
14.6.4 Exercise 4: Visualize prior sensitivity (Python)
For six successes in eight trials, compare the posteriors arising from \(\operatorname{Beta}(1,1)\), \(\operatorname{Beta}(2,8)\), and \(\operatorname{Beta}(8,2)\) priors. Plot all densities and report 95% credible intervals and posterior means. Repeat with 60 successes in 80 trials.
import numpy as np
from scipy import stats
import matplotlib.pyplot as plt
g = np.linspace(.001,.999,500)
fig, axes = plt.subplots(1,2,figsize=(9,3.5))
for ax,s,n in zip(axes,[6,60],[8,80]):
for a,b in [(1,1),(2,8),(8,2)]:
law = stats.beta(a+s,b+n-s)
print(n,(a,b),law.mean(),law.ppf([.025,.975]))
ax.plot(g,law.pdf(g),label=f"Prior ({a}, {b})")
ax.set(title=f"{s} successes in {n}",xlabel="p")
ax.legend()
plt.tight_layout()
plt.show()The differences are larger for eight observations. At eighty observations the likelihood receives a much greater weight; the prior still contributes, but the means and intervals become more similar.
14.6.5 Exercise 5: Simulate posterior prediction (Python)
Starting from posterior \(\operatorname{Beta}(9,8)\), generate 50,000 predicted counts of successes in 20 future trials. Compare the predictive distribution to the plug-in binomial using posterior mean \(9/17\). Use SciPy to check the exact beta-binomial PMF.
import numpy as np
from scipy import stats
import matplotlib.pyplot as plt
rng = np.random.default_rng(1402)
m = 20
p = rng.beta(9,8,50_000)
k = rng.binomial(m,p)
grid = np.arange(m+1)
bb = stats.betabinom(m,9,8)
plugin = stats.binom(m,9/17)
print("Simulated predictive variance", k.var())
print("Exact predictive variance",bb.var(),"Plug-in",plugin.var())
plt.bar(grid,np.bincount(k,minlength=m+1)/k.size,alpha=.5)
plt.plot(grid,bb.pmf(grid),"o-",label="Beta-binomial")
plt.plot(grid,plugin.pmf(grid),"s--",label="Plug-in")
plt.legend()
plt.show()
assert abs(k.mean()-bb.mean())<.08The predictive count has extra variation from parameter uncertainty. Each replicated count should draw a single \(p\) and then conditionally independent trials sharing it, rather than a fresh \(p\) for every trial.
14.6.6 Exercise 6: Diagnose an overdispersed model (Python)
Generate 80 counts from an overdispersed mixture: first draw individual rates from Gamma(shape 1, rate 0.3), then draw Poisson counts conditional on those rates. Incorrectly fit a shared Poisson rate with Gamma(1,1) prior. Compare the observed variance-to-mean ratio to ratios from 4,000 posterior predictive replicated datasets of size 80. What does the comparison suggest?
import numpy as np
import matplotlib.pyplot as plt
rng = np.random.default_rng(1403)
n = 80
x = rng.poisson(rng.gamma(1,1/.3,n))
lam = rng.gamma(1+x.sum(),1/(1+n),4000)
rep = rng.poisson(lam[:,None],size=(lam.size,n))
observed = x.var(ddof=1)/x.mean()
ratio = rep.var(axis=1,ddof=1)/np.maximum(rep.mean(axis=1),1e-12)
print("Observed dispersion",observed)
print("Predictive quantiles",np.quantile(ratio,[.025,.5,.975]))
plt.hist(ratio,bins=35,density=True,alpha=.6)
plt.axvline(observed,color="black",label="Observed")
plt.legend()
plt.xlabel("Variance / mean")
plt.show()The shared-rate model generates conditionally Poisson-shaped data; replicated dispersions should concentrate near one. The mixture’s observed dispersion is substantially larger. The check identifies a structural mismatch, suggesting a model with varying rates (or another overdispersed likelihood) is worth exploring.