Bayesian inference: priors, posteriors, MAP and prediction
Before this lesson: lesson 01 (Bayes' rule), lesson 03 (the beta, gamma and Poisson distributions), lesson 05 (Gaussian conditioning, completing the square) and lesson 08 (likelihood, MLE, bias–variance, the exponential family). Lesson 09 helps: the data precision of a Gaussian mean is . Time: about 75 minutes, plus the notebook.
Why this matters #
- Decisions need uncertainty. Is variant B better than A? How wide is a forecast band? Where should active learning or Bayesian optimisation sample next? All need a distribution over the unknowns, not only a point.
- Regularisation is a prior. Ridge regression and weight decay are MAP estimates with a Gaussian prior; the lasso uses a Laplace prior. Add-one smoothing of counts is a posterior mean.
- Exploration. Thompson sampling draws a parameter from each arm's Beta posterior and plays the best draw (reinforcement learning 03).
- Science. The analysis step of a Kalman filter in weather forecasting is a Gaussian–Gaussian update (ML for science 06); Gaussian processes are Bayesian regression (ML for science 07).
- Ground truth for approximate methods. Conjugate models have exact posteriors, so they are the test cases for MCMC (lesson 15) and variational inference.
1. Predict first #
2. The picture #
Bayes' rule for a parameter #
Treat the unknown parameter as a random variable with a prior density . After the data , Bayes' rule (lesson 01) gives
- The likelihood is the same function as in lesson 08.
- The evidence (or marginal likelihood) does not depend on . It only rescales the product so that the posterior integrates to 1. So we often write .
- In logs, + const. The prior is one term, and each data point adds one more.
On a grid. For one parameter you can do this with a computer and nothing else: put 1000 grid points on , multiply the prior and the likelihood at each point, and divide by the sum (times the grid step). The result is the posterior, up to the grid error. A coin with 7 heads in 10 flips and a uniform prior: the product is , and after normalisation it is the Beta(8, 4) density.
The coin: pseudo-counts #
A Beta prior on a probability has density , mean , and acts like earlier heads and earlier tails. Observing heads in flips just adds counts: the posterior is Beta.
Flip the coin (or click Heads and Tails) and watch the posterior. The violet curve is the prior Beta(), the orange curve the likelihood (rescaled to area 1), and the aqua curve the posterior, with its 95% credible interval shaded. The markers show the MLE, the MAP and the posterior mean. The posterior always lies between the prior and the likelihood. Make the prior strong ( large) and see how many flips it takes to move it. Set (uniform prior): then the MAP equals the MLE.
Sequential = batch. Today's posterior is tomorrow's prior. Update Beta() with heads in flips, then with in : you get Beta(), the same as one update with all the data, in any order. A running A/B dashboard and a Kalman filter work this way.
A coin shows 3 heads in 3 flips. With a uniform prior Beta(1, 1), what are the posterior, the posterior mean and the MLE?
Add the counts: , . The posterior mean is , which is also the probability that the next flip is heads (Laplace's rule of succession, ). The MLE claims that tails are impossible.
The Gaussian mean: precisions add #
For a Gaussian mean with known noise, the prior and the data each contribute a precision (inverse variance). The posterior precision is their sum, and the posterior mean is the precision-weighted average of the prior mean and : the more precise source gets more weight.
Move the sliders and compare the three curves. Violet: the prior . Orange: the likelihood of , which has the shape . Aqua: the posterior. The bar below shows the precisions: prior plus data equals posterior. Increase : the data precision grows and the posterior moves to . Make the prior wide: it stops mattering.
3. Definitions and main results #
A prior family is conjugate to a likelihood if a prior in always gives a posterior in . Then the update is a rule for the parameters of the prior (the hyperparameters).
Beta–Bernoulli #
Data: i.i.d. Bernoulli(), with . Prior: with .
- Likelihood: .
- Posterior .
- This is the kernel of a Beta density, so with , .
Summaries of the posterior:
- Posterior mean with : a weighted average of the prior mean and the MLE. The prior counts like observations.
- MAP (the mode) , for . With it equals the MLE .
- Credible interval: the 2.5% and 97.5% quantiles of Beta() (no closed form;
scipy.stats.beta.ppf).
Point estimates: posterior mean, MAP and the regularised MLE #
The maximum a posteriori (MAP) estimate is the mode of the posterior. Take logs of Bayes' rule; the evidence does not depend on , so
L2 = Gaussian prior. Linear regression with noise and prior :
Multiply by : this is ridge regression, with . A Laplace prior gives the lasso, with . Weight decay in plain SGD is an L2 penalty; with Adam the two differ, which is why AdamW decouples them (optimization 06).
Which summary? Each point estimate is the best answer to a different loss: the posterior mean minimises the expected squared error, the posterior median the expected absolute error, and the MAP is the limit for a 0–1 loss. For a Gaussian posterior all three coincide.
The MAP depends on the parametrisation. A density changes with a Jacobian (lesson 05); a likelihood does not. So the MLE is invariant (lesson 08), but the MAP is not. Example: a help desk records 5 waiting times between calls with sum minutes; model Exponential(); flat prior on the rate .
- In : the posterior is , with mode , equal to the MLE.
- In the mean waiting time : , so the same prior becomes . The posterior is .
- Set the derivative of to zero: , so minutes, not minutes.
A "flat prior" is not neutral: flat in is not flat in . Posterior quantiles (such as the median) move correctly under a monotone change of variable; the mode and the mean in general do not.
You train with the loss . Which prior on makes the minimiser a MAP estimate, if the noise variance is ?
The negative log-posterior is . Multiply by : the penalty weight is , so . A larger means a narrower prior. A Laplace prior gives the L1 penalty (lasso).
Shrinkage: when a prior beats the MLE #
The posterior mean and the MAP pull the MLE toward the prior: they are shrinkage estimators. Judge them as estimators, with the bias–variance decomposition of lesson 08, at a fixed true .
Gaussian mean. Data , known; prior . The posterior mean is with (derived below).
- , so the bias is .
- , smaller than the variance of .
- , while for every .
- Solving gives exactly .
So the prior helps when its guess is roughly right and hurts when it is far off. It trades a little bias for a larger cut in variance.
Compare three estimators of a coin's at every true . The curves are exact MSEs (sums over all outcomes ): the orange MLE , the aqua MAP and the dashed aqua posterior mean . The violet line marks the prior mean. Where the shading is aqua, the MAP beats the MLE. Press Simulate to check the three MSEs at the yellow with 4000 experiments (blue dots). A strong prior wins big near its mean and loses far from it; a larger makes all curves agree.
Gaussian–Gaussian (known variance) #
Data: i.i.d. with known. Prior: .
- .
- Collect the powers of : .
- Complete the square: , the log-density of a Gaussian with precision and mean .
- So with
Posterior precision = prior precision + data precision. The data precision is , the Fisher information of lesson 09. The prior is worth observations. The posterior is Gaussian, so its mean, median and mode (the MAP) coincide.
Conjugate priors and the exponential family #
Every exponential family has a conjugate prior. As a function of , the likelihood of observations is with (lesson 08). Take a prior of the same form, with hyperparameters and : . The posterior is , the same family with the update , . The prior acts like pseudo-observations.
Gamma–Poisson. Counts Poisson(), prior Gamma() (shape , rate ). The posterior is with , that is Gamma(): mean , MAP . The prior is worth observation periods with events in total.
Sign-ups per hour are Poisson(). Prior Gamma(3, 1) (shape 3, rate 1). In 5 hours you see sign-ups. What is the posterior mean of ?
and , so the posterior is Gamma() = Gamma(28, 6), with mean . It is a weighted average: (prior mean 3, worth one hour). is the MAP, lower than the mean because the gamma posterior is right-skewed.
The posterior predictive distribution #
To predict a new observation , average the model over the posterior:
It has two sources of spread: the noise of for a fixed , and the remaining uncertainty about . By the law of total variance (lesson 04),
A plug-in prediction keeps only the first term, so it is too narrow.
- Gaussian. with and independent noise . A sum of independent Gaussians is Gaussian: .
- One coin flip. , the posterior mean.
- future flips. The number of heads is beta-binomial, with mean and variance , where . The last factor is above 1 for : all flips share the same unknown , so their errors do not cancel.
Predict the number of successes in the next trials. You saw successes in trials; the prior is Beta(1, 1). The aqua bars are the posterior predictive (beta-binomial), the orange bars the plug-in Binomial(). With little data the predictive is much wider. Increase (with the same rate ) and the two distributions become the same; increase and the gap grows.
Credible intervals and confidence intervals #
- A 95% credible interval satisfies : a probability statement about , given the observed data and the prior.
- A 95% confidence interval is a random interval with for every (lesson 06): a statement about the procedure over repeated data sets. For one realised interval, is either in it or not.
They can agree numerically (a flat prior on a Gaussian mean gives for both), but they answer different questions. Averaged over drawn from the prior, a credible interval covers exactly 95% of the time. At a fixed far from the prior it can cover much less: with the prior Beta(1, 19) (mean 0.05) and a true rate of 0.12, the 95% credible interval covers the truth with probability at , at and at (exact sums over ).
The prior's influence vanishes (usually). The log-likelihood is a sum of terms and grows like ; the log-prior stays fixed. In the conjugate formulas, the prior weights and both go to 0.
The Bernstein–von Mises theorem
In a regular model (the conditions of lesson 09) with a fixed number of parameters, and a prior with a continuous, positive density at the true value , the posterior approaches in total variation as . So credible intervals become Wald confidence intervals, and Bayesian and frequentist answers agree for large . The simplest case: the variance of Beta() is . The theorem fails when the prior gives zero density near the truth (no data can fix that), when the number of parameters grows with , or when the model is not identifiable.
Answers to section 1. (1) The prior precision is and the data precision is . The posterior precision is 3, so the variance is and the mean is : two thirds of the way from 0 to 3, because the data are twice as precise as the prior. (2) Wider: , against the plug-in variance . The plug-in drops the parameter-uncertainty term . Here , so the gap vanishes as grows.
4. Worked example #
A/B test with a historical prior. Past experiments put conversion rates near 5%, so the team uses the prior Beta(1, 19): mean , worth 20 users. Variant B converts of users; the control A converts 8 of 100.
- Posterior of B. Beta() = Beta(13, 107).
- Posterior mean. . Check with the weights: on the prior, and ✓.
- MAP and MLE. MAP . MLE .
- Credible interval. The 2.5% and 97.5% quantiles of Beta(13, 107) are and . The Wald interval of lesson 09 is : centred on the MLE, with no pull toward the prior.
- Predictive. The next user converts with probability . For the next 50 users, the beta-binomial variance is ; the plug-in Binomial(50, 0.12) has variance .
- Is B better than A? The posterior of A is Beta() = Beta(9, 111). Draw many pairs from the two posteriors and count how often : about . (Numerical integration of , with the density and the CDF , gives .) The posterior mean of the lift is .
- Expected loss. If you ship B and B is worse, you lose . The expected loss is about (0.4 percentage points); for shipping A it is about . A common rule: ship when the expected loss is below a threshold you accept.
Run a Bayesian A/B test. Set the visitors and conversions of each variant. The top panel shows the posteriors of (blue) and (aqua) with a uniform prior; the bottom panel the histogram of from 4000 posterior draws, aqua where B wins and magenta where A wins. The readout gives by sampling (with its Monte Carlo error) and by numerical integration, and the expected loss of each choice. Multiply both sample sizes by 10 with the same rates and see the decision become clear.
5. In code #
SciPy checks the conjugate update on a grid, the worked example and the A/B probability. The notebook has these cells and the exercises.
import numpy as np
from scipy import stats, integrate
a, b = 1, 19 # prior Beta(1, 19): mean 0.05, worth 20 users
k, n = 12, 100 # variant B: 12 conversions in 100 users
# grid posterior = normalised prior x likelihood; compare with the conjugate Beta(a + k, b + n - k)
p = np.linspace(1e-6, 1 - 1e-6, 200_001)
unnorm = stats.beta.pdf(p, a, b) * stats.binom.pmf(k, n, p)
grid_post = unnorm / (unnorm.sum() * (p[1] - p[0]))
print(np.abs(grid_post - stats.beta.pdf(p, a + k, b + n - k)).max() < 1e-6) # True
post_B = stats.beta(a + k, b + n - k) # Beta(13, 107)
print(round(post_B.mean(), 4), post_B.ppf([0.025, 0.975]).round(4)) # 0.1083 [0.0595 0.1695]
print(round(stats.betabinom(50, a + k, b + n - k).var(), 2), round(stats.binom(50, k / n).var(), 2)) # 6.79 5.28
# Bayesian A/B: control A had 8 conversions in 100 users, same prior
post_A = stats.beta(a + 8, b + 92)
rng = np.random.default_rng(0)
pA, pB = post_A.rvs(1_000_000, random_state=rng), post_B.rvs(1_000_000, random_state=rng)
print(round((pB > pA).mean(), 3), round(np.maximum(pA - pB, 0).mean(), 4)) # 0.82 0.0036
exact = integrate.quad(lambda q: post_B.pdf(q) * post_A.cdf(q), 0, 1)[0]
print(round(exact, 3)) # 0.819
# Gaussian-Gaussian: prior N(0, 1), 8 readings with variance 4 and mean 3
prec = 1 / 1 + 8 / 4
print(round(1 / prec, 3), (0 / 1 + 8 * 3 / 4) / prec, round(4 + 1 / prec, 3)) # 0.333 2.0 4.333
The Monte Carlo probability has a standard error of about .
6. Where it shows up #
- Regularisation. Ridge regression and weight decay are MAP estimates under a Gaussian prior (); the lasso is the MAP under a Laplace prior (its posterior mean is not sparse). Add-one (Laplace) smoothing of counts in n-gram language models and naive Bayes is the posterior mean under a uniform Dirichlet prior.
- Bandits and recommender systems. Thompson sampling keeps a Beta posterior per arm (ad, article, variant), draws one from each, and shows the arm with the largest draw. Arms with uncertain posteriors get explored automatically.
- Empirical Bayes for many small groups. Click rates of thousands of small segments, batting averages, ratings of products with few reviews: fit one Beta prior to all groups, then shrink each raw rate toward the overall rate. The shrunk rates have a lower total MSE than the raw MLEs (the James–Stein effect).
- Data assimilation and Kalman filters. Forecast = prior, observations = likelihood, analysis = posterior; with Gaussians, the update is the precision-weighted average above, in many dimensions (ML for science 06).
- Uncertainty in deep learning. Laplace approximations, Bayesian last layers and deep ensembles approximate a posterior predictive; Gaussian processes give it exactly (ML for science 07). Bayesian linear regression is in lesson 13.
- Bayesian A/B tests. Report , the posterior of the lift, and the expected loss. Caution: a rule like "stop when ", checked every day, still declares a winner more often than 5% of the time when A and B are equal (lesson 12).
7. Common mistakes #
- Plug-in predictions. ignores the parameter uncertainty and gives prediction intervals that are too narrow, most of all with little data.
- Adding variances instead of precisions. Posterior precision = prior precision + data precision.
- The wrong ridge constant. (noise variance over prior variance), not .
- Treating the MAP as "the Bayesian answer". It is one point: it ignores the posterior width, it depends on the parametrisation, and it can sit on the boundary (a Beta() prior and zero successes give ).
- "There is a 95% probability that is in this confidence interval." That is the credible-interval statement, and it needs a prior.
- A prior that excludes the truth. Zero prior density can never be repaired by data. A prior centred far from the truth dominates small samples (coverage 0.72 at above).
- A "non-informative" flat prior. Flat in one parametrisation is not flat in another ( vs ), so it still carries information.
8. Check yourself #
- Uniform prior Beta(1, 1); a new variant has 0 conversions in 30 users. Give the posterior, its mean and MAP, and the 95% upper
credible bound.
Answer
Beta(1, 31). Mean ; MAP 0. The CDF of Beta(1, ) is , so the upper bound solves : . Unlike the Wald interval of lesson 09, it does not collapse to a point. - Show that updating a Gaussian mean with batch 1 and then batch 2 gives the same posterior as one update with both batches.
Answer
Each update adds to the precision and to "precision times mean". Sums do not depend on order or grouping, so in both cases the final precision is and the final precision times mean is . - For the kitchen scale of lesson 08 ( readings with , noise variance ) and the prior , compute the
posterior mean and variance. For which true offsets does the posterior mean have a smaller MSE than ?
Answer
Data precision , prior precision 1, so : posterior mean , variance . MSE of the posterior mean: ; MSE of : . It wins when , that is , in agreement with . - Does the MAP of the mean waiting time equal ? Explain with the example of section 3.
Answer
No. With a flat prior on , , so . In the prior picks up the Jacobian , and the posterior has its mode at . Densities change with a Jacobian; the mode moves. The MLE has no Jacobian and is invariant. - For one future binary outcome the posterior predictive is Bernoulli(). In what sense is the Bayesian predictive "wider" than
the plug-in Bernoulli()?
Answer
For a single trial both are Bernoulli distributions; they differ only in the probability ( is pulled toward the prior mean), and a Bernoulli's variance is fixed by its mean. The extra spread appears for future trials: the beta-binomial variance is larger than the binomial , because all trials share the same unknown . - "The 95% credible interval for the conversion rate is [0.059, 0.170]." Write one correct sentence that explains it to a product
manager, and one sentence that a confidence interval would justify instead.
Answer
Credible: "Given our prior and these data, there is a 95% probability that the true rate is between 5.9% and 17.0%." Confidence: "If we repeated this experiment many times, intervals built this way would contain the true rate in 95% of the repetitions."
Write Bayes' rule for a parameter and name the terms.
: posterior = likelihood × prior / evidence.
Posterior of a coin's with prior Beta() after heads in flips?
Beta().
Posterior precision and mean for a Gaussian mean with prior and known noise ?
and .
MAP of a Bernoulli with prior Beta()?
(for and ).
Which prior turns an L2 penalty on a squared-error loss into a MAP estimate?
A Gaussian prior with .
What is the posterior predictive distribution?
: the model averaged over the posterior.
Why is the posterior predictive wider than a plug-in prediction?
Law of total variance: it adds , the parameter uncertainty, to the noise. Gaussian: instead of .
What does a 95% credible interval mean, compared with a confidence interval?
Credible: , given the prior. Confidence: the procedure covers the true in 95% of repeated data sets.
What is a conjugate prior?
A prior family whose posterior stays in the same family for a given likelihood; every exponential family has one.
Is the MAP invariant under a change of parameter?
No: the posterior density picks up a Jacobian, which moves the mode. The MLE is invariant.
9. Interview angle #
- "A coin shows 3 heads in 3 tosses. What is P(heads next)?" — The MLE says 1. With a uniform prior, the posterior is Beta(4, 1) and Laplace's rule gives .
- "Derive ridge regression from a Bayesian view." — Gaussian likelihood and Gaussian prior; the negative log-posterior is , so .
- "MLE, MAP, full Bayes: what is the difference?" — Maximise the likelihood; maximise the posterior (a regularised MLE, still one point); keep the whole posterior and average predictions over it.
- "How do you compute ?" — Sample both Beta posteriors and count, or compute .
- "When does the prior still matter with lots of data?" — When it excludes the truth, when the number of parameters grows with (hierarchical models, many small groups), and in directions the data do not inform.
- "Credible vs confidence interval?" — A probability about given the data and prior, vs a coverage property of a procedure.
10. Practice #
The notebook for this lesson has five exercises, each with a check cell and a folded solution:
- A grid posterior for a coin, compared with the conjugate Beta posterior (maximum absolute difference).
map_gaussian_meanand the Gaussian–Gaussian posterior, checked against the precision formula and a numerical optimiser.- MSE of the MLE and of the MAP for a coin, by simulation over a grid of true , against the exact sums.
- The beta-binomial predictive for the next 50 users against the plug-in binomial.
- A Bayesian A/B test: by Monte Carlo and by numerical integration, and the expected loss.
11. Watch and read #
- Kevin Murphy, Probabilistic Machine Learning: An Introduction, free PDF: §4.5 (MAP estimation and regularisation), §4.6 (Bayesian statistics: conjugate priors, beta-binomial, Gaussian, credible intervals) and §4.7.5 (confidence intervals are not credible).
- Allen Downey, Think Bayes 2 (free online, with code): grid posteriors, conjugate priors and Bayesian A/B tests.
- Kevin Murphy, Probabilistic Machine Learning: Advanced Topics, free PDF: §3.4 (conjugate priors, including the exponential family).
Runs in your browser with nothing to install. The notebook repeats the key demos and has exercises with checks; solutions are inside, folded.
No Google account needed: Python runs inside your browser. The first start downloads about 40 MB; your changes are saved in this browser only.