Every estimate you have made so far, a mean, a proportion, a regression slope, has been a single number with a confidence interval bolted on. The Bayesian view keeps the whole distribution of plausible values instead. You start with a prior, what you believed before seeing the data; you weigh it by the likelihood, how well each value explains the data; and you end with a posterior, your updated belief. Everything else, best guesses and uncertainty alike, is just a question you ask of that posterior.
p(θ | data) ∝ p(θ) × p(data | θ). A credible
interval is a range that holds the parameter with a stated probability (say 95 percent), the direct
statement a confidence interval only approximates.
A 95 percent confidence interval is a statement about the procedure: repeat the study forever and 95 percent of such intervals cover the truth. A 95 percent credible interval is a statement about this parameter: given your prior and this data, there is a 95 percent probability the value lies inside. Bayesian inference lets you say the thing everyone secretly wants to say.
Prior × Likelihood → Posterior
Start with the simplest real question: what is the true conversion rate of a landing page? Call it θ.
Before collecting data you hold a prior, a distribution over the values θ might
take. Then 40 visitors arrive and 8 convert. The likelihood scores
every candidate rate by how well it explains “8 out of 40.” Multiply the two, normalize, and you have the
posterior.
Because a Beta prior and a Binomial likelihood are a conjugate
pair, the posterior is again a Beta, no integration required: a Beta(a, b) prior plus c
successes in n trials becomes Beta(a + c, b + n − c). Here a weak Beta(2, 2)
prior and 8 of 40 give Beta(10, 34). That single object answers every question: its mean is
0.227, and the middle 95 percent, the credible interval, runs from
0.118 to 0.360. Want the chance the rate beats 30 percent? It is the posterior area above 0.30,
about 13 percent. No sampling distribution, no null hypothesis, just areas under one curve.
MLE, MAP, and the Full Posterior
People often want “the number.” The posterior offers three, and the difference between them is the whole lesson. Two are single points on the curve; the third is the curve itself.
- ●MLE (maximum likelihood): the value that best fits the data alone, ignoring the prior. Here 8/40 = 0.200, the peak of the likelihood. It is what classical statistics reports.
- ●MAP (maximum a posteriori): the peak of the posterior, the single most probable value once the prior is folded in. Here 0.214. It is a regularized MLE, the prior nudges it toward the middle.
- ●The full posterior: the whole
Beta(10, 34)curve, mean 0.227. This is the Bayesian answer, because only the full distribution carries the uncertainty that the two points throw away.
A prior is not a permanent thumb on the scale. With 8 of 40, the Beta(2, 2) prior pulled the estimate
from 0.200 up to 0.227. Feed in ten times the data at the same rate (80 of 400) and the posterior
mean is 0.203, all but identical to the MLE. More evidence overwhelms the prior; that is exactly
how it should behave. Priors matter most when data is scarce, which is also when you most need the help.
When the Math Runs Out: MCMC & HMC
Conjugate pairs like Beta-Binomial give the posterior in closed form, but they are the lucky exceptions. The moment a model has several parameters, hierarchical structure, or an awkward likelihood, the normalizing integral is impossible to do by hand. The Bayesian workhorse is to sample from the posterior instead of solving for it, and a pile of samples answers every question a formula could.
The simplest sampler, Metropolis-Hastings, is almost embarrassingly simple: propose a small random step, and accept it if the posterior there is higher, or with a matching probability if it is lower. Do that tens of thousands of times and the chain visits each region of parameter space in proportion to its posterior probability, so the collected draws are a sample from the posterior. Modern tools use a far smarter version, Hamiltonian Monte Carlo (HMC) and its self-tuning cousin NUTS, which use the gradient of the posterior to take long, efficient strides instead of a random shuffle.
In practice you never write the sampler yourself. A probabilistic programming language lets you declare the model and hands the inference to a battle-tested engine:
import pymc as pm
with pm.Model() as model:
theta = pm.Beta("theta", alpha=2, beta=2) # prior
pm.Binomial("y", n=40, p=theta, observed=8) # likelihood
idata = pm.sample(2000, tune=1000, chains=4) # NUTS does the rest
Because you are trusting a sampler rather than a formula, you must check that it converged. Two diagnostics do most of the work: the trace plot should look like a fuzzy caterpillar, the chains overlapping with no drift or stuck stretches; and R-hat compares variation within each chain to variation between chains, with values at 1.00 (below about 1.01) signaling agreement. A healthy run here recovers the same posterior the conjugate formula gave, mean near 0.227, which is the whole point: MCMC is a general-purpose route to the answer you could only sometimes get exactly.
Real-World Example: An Email A/B Test
The Bayesian payoff is clearest in an A/B test, where the question is not “is there a significant difference” but the far more useful “how likely is B better, and by how much is it worth?” The companion notebook works a full campaign end to end with conjugate posteriors and Monte Carlo.
An email marketing test of 2,000 recipients split between two subject
lines. Five columns: recipient_id, variant (A control or B new), device
(mobile or desktop), opened (0/1), and converted (0/1). The question: does variant B lift
the true conversion rate, and is the gain big enough to ship?
- ●Raw rates: A converts 120 of 1,000 (12.0%), B converts 162 of 1,000 (16.2%).
- ●Posteriors: with a uniform prior, A is
Beta(121, 881)(mean 0.121, 95% CI 0.101 to 0.142) and B isBeta(163, 839)(mean 0.163, 95% CI 0.140 to 0.186). - ●Decision: P(B > A) ≈ 99.6%, with an expected lift of +4.2 percentage points (95% credible interval +1.2 to +7.2), roughly a +36% relative gain.
Contrast the two write-ups. The frequentist test returns a two-proportion z = 2.70, p = 0.007,
“reject the null of no difference,” true but thin. The Bayesian analysis hands a stakeholder a sentence they
can act on: “There is a 99.6 percent chance B is better, and about a 92 percent chance the lift is at least 2
points.” Finally, a posterior predictive check closes the loop: simulate new campaigns from
the fitted posteriors and confirm the conversions they generate look like the data you actually saw. If the real data
sits in the fat part of that simulated distribution, the model is telling a story consistent with reality.
Bayesian Inference in Machine Learning & AI
Bayesian thinking is not a statistical backwater; it is woven through modern machine learning, usually wherever a model needs to say not just what it predicts but how sure it is. The prior-times-likelihood engine reappears under many names.
| Where it shows up | What it does | Examples |
|---|---|---|
| Bayesian optimization | Model an expensive objective with a surrogate and pick the next point by expected improvement, tuning in far fewer trials | Hyperparameter search: Optuna, scikit-optimize, Vertex AI Vizier |
| Thompson sampling | Draw from each option's posterior and play the winner, balancing explore and exploit automatically | Multi-armed bandits, ad serving, adaptive A/B tests |
| Priors as regularization | A penalty on weights is a prior: L2 is a Gaussian prior, L1 a Laplace prior | Ridge and lasso, weight decay in neural nets |
| Bayesian deep learning | Put distributions over weights and approximate the posterior, so predictions carry calibrated uncertainty | Variational inference, MC dropout, deep ensembles |
| Probabilistic programming | Declare a generative model and let a sampler do the inference | PyMC, Stan, NumPyro, Pyro, TensorFlow Probability |
| Gaussian processes | A prior over functions that returns a mean and an uncertainty band, ideal on small data | Spatial models, active learning, the engine inside Bayesian optimization |
As models are handed higher-stakes decisions, uncertainty quantification has become a central research theme: a system that knows when it does not know can defer, ask for data, or flag a prediction as unreliable. Scaling exact Bayesian inference to models with billions of parameters is the open challenge, driving work on scalable variational inference, normalizing flows, and simulation-based inference, alongside efforts to calibrate the confidence of large language models so a fluent answer and a trustworthy one stop being the same thing.
Do Bayesian inference in Python
The companion notebook builds the conjugate Beta-Binomial update from scratch and plots prior, likelihood, and posterior together; reads MLE, MAP, and the posterior mean off one curve and watches the prior fade as data grows; approximates a posterior three ways (grid, a hand-written Metropolis sampler, and the same model in PyMC when it is available); and runs the full email A/B test, posterior of the difference, P(B beats A), a credible interval on the lift, and a posterior predictive check, every step with a plot.
View opens the rendered notebook instantly.
Open in Colab runs it live (PyMC is preinstalled there). To run locally, install numpy,
scipy, pandas, matplotlib, and openpyxl; the PyMC cell is optional
and skips itself if the library is absent.
🎓 Key Takeaways
- ✓Posterior ∝ prior × likelihood: Bayesian inference updates a belief with data and keeps the whole distribution, not just a point.
- ✓Conjugate shortcut: a Beta prior with Binomial data gives a Beta posterior in closed form,
Beta(a+c, b+n−c), no integration. - ✓Three estimates, one curve: the MLE ignores the prior, the MAP is the posterior peak (a regularized MLE), and the full posterior alone carries the uncertainty.
- ✓The prior fades: with more data the posterior converges to the likelihood; priors matter most when data is scarce.
- ✓MCMC/HMC sample the posterior when no formula exists; check the trace plot and R-hat (near 1.00) before you trust the draws.
- ✓Credible intervals and direct probabilities (P(B>A), P(lift>2 points)) are the decisions stakeholders actually want.
Practice Challenges
Five exercises on the conversion and A/B examples. Full solutions are in the companion solutions notebook.
Change the prior
Redo the 8-of-40 update with a flat Beta(1,1) prior and a strong Beta(20,20) prior. How do the posterior means move, and why?
Beta(a+8, b+32).Credible vs confidence
Compute the 95% credible interval from the posterior and the 95% Wald confidence interval from the MLE. Compare their widths and interpretations.
beta.ppf([.025,.975], a, b).Grid vs conjugate
Approximate the same posterior on a 1,000-point grid and overlay it on the exact Beta curve. How fine a grid do you need to match it?
P(B > A) by simulation
Draw 100,000 samples from each variant's posterior and estimate P(B>A) and the expected lift. Confirm it matches the notebook's 99.6%.
(postB.rvs(N) > postA.rvs(N)).mean().Posterior predictive check
Simulate 1,000 replicated A/B campaigns from the posteriors and plot the distribution of B's conversion count. Does the observed 162 sit comfortably inside it?
theta, then Binomial(1000, theta).Solutions notebook
All five challenges worked in code, prior sensitivity, credible versus confidence intervals, the grid approximation, P(B>A) by simulation, and a posterior predictive check, each with a short explanation.
Quiz: Test Yourself
Eight questions on priors, posteriors, MLE/MAP, MCMC, and credible intervals. Answer them, hit Check Answers, and keep refining until you score 100%. Your progress is saved.
Bayesian inference gave you an honest way to reason about uncertain quantities. Next, Advanced & Applied Topics takes on the hardest question of all. Causal Inference moves beyond correlation to estimate what an action actually causes, even when you could never run a clean experiment.