Type at least 2 letters. Enter opens the first result, Esc closes.

    Probability and Statistics · Lesson 10 · Estimation

    Bayesian inference: priors, posteriors, MAP and prediction

    Intermediate 75 min 5 interactive figures 3 videos Colab notebook

    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 nI(μ)nI(\mu). 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 θ\theta as a random variable with a prior density p(θ)p(\theta). After the data D=(x1,…,xn)\mathcal D = (x_1, \dots, x_n), Bayes' rule (lesson 01) gives

    p(θ∣D)⏟posterior=p(D∣θ)⏞likelihood p(θ)⏞priorp(D)⏟evidence,\underbrace{p(\theta \mid \mathcal D)}_{\text{posterior}} = \frac{\overbrace{p(\mathcal D \mid \theta)}^{\text{likelihood}}\ \overbrace{p(\theta)}^{\text{prior}}}{\underbrace{p(\mathcal D)}_{\text{evidence}}},
    p(D)=∫p(D∣θ) p(θ) dθ.p(\mathcal D) = \int p(\mathcal D \mid \theta)\, p(\theta)\, d\theta .
    • The likelihood p(D∣θ)p(\mathcal D \mid \theta) is the same function as in lesson 08.
    • The evidence (or marginal likelihood) p(D)p(\mathcal D) does not depend on θ\theta. It only rescales the product so that the posterior integrates to 1. So we often write p(θ∣D)∝p(D∣θ) p(θ)p(\theta \mid \mathcal D) \propto p(\mathcal D \mid \theta)\, p(\theta).
    • In logs, log⁡p(θ∣D)=log⁡p(θ)+∑ilog⁡p(xi∣θ)\log p(\theta \mid \mathcal D) = \log p(\theta) + \sum_i \log p(x_i \mid \theta) + 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 [0,1][0, 1], 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 p7(1−p)3p^7(1-p)^3, and after normalisation it is the Beta(8, 4) density.

    The coin: pseudo-counts #

    A Beta(a,b)(a, b) prior on a probability pp has density ∝pa−1(1−p)b−1\propto p^{a-1}(1-p)^{b-1}, mean aa+b\frac{a}{a+b}, and acts like aa earlier heads and bb earlier tails. Observing kk heads in nn flips just adds counts: the posterior is Beta(a+k, b+n−k)(a + k,\ b + n - k).

    Interactive figure: loading…

    Flip the coin (or click Heads and Tails) and watch the posterior. The violet curve is the prior Beta(a,ba, b), 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 (a+ba + b large) and see how many flips it takes to move it. Set a=b=1a = b = 1 (uniform prior): then the MAP equals the MLE.

    Sequential = batch. Today's posterior is tomorrow's prior. Update Beta(a,ba, b) with k1k_1 heads in n1n_1 flips, then with k2k_2 in n2n_2: you get Beta(a+k1+k2, b+n1+n2−k1−k2a + k_1 + k_2,\ b + n_1 + n_2 - k_1 - k_2), the same as one update with all the data, in any order. A running A/B dashboard and a Kalman filter work this way.

    Quick check

    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?

    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 xˉ\bar x: the more precise source gets more weight.

    Interactive figure: loading…

    Move the sliders and compare the three curves. Violet: the prior N(μ0,τ02)\mathcal N(\mu_0, \tau_0^2). Orange: the likelihood of μ\mu, which has the shape N(xˉ,σ2/n)\mathcal N(\bar x, \sigma^2/n). Aqua: the posterior. The bar below shows the precisions: prior plus data equals posterior. Increase nn: the data precision n/σ2n/\sigma^2 grows and the posterior moves to xˉ\bar x. Make the prior wide: it stops mattering.

    3. Definitions and main results #

    A prior family F\mathcal F is conjugate to a likelihood if a prior in F\mathcal F always gives a posterior in F\mathcal F. Then the update is a rule for the parameters of the prior (the hyperparameters).

    Beta–Bernoulli #

    Data: x1,…,xn∈{0,1}x_1, \dots, x_n \in \{0, 1\} i.i.d. Bernoulli(pp), with k=∑ixik = \sum_i x_i. Prior: p∼Beta(a,b)p \sim \text{Beta}(a, b) with a,b>0a, b > 0.

    1. Likelihood: p(D∣p)=pk(1−p)n−kp(\mathcal D \mid p) = p^k (1-p)^{n-k}.
    2. Posterior ∝pk(1−p)n−k⋅pa−1(1−p)b−1=pa+k−1(1−p)b+n−k−1\propto p^k (1-p)^{n-k} \cdot p^{a-1}(1-p)^{b-1} = p^{a+k-1}(1-p)^{b+n-k-1}.
    3. This is the kernel of a Beta density, so p∣D∼Beta(a′,b′)p \mid \mathcal D \sim \text{Beta}(a', b') with a′=a+ka' = a + k, b′=b+n−kb' = b + n - k. ■\blacksquare

    Summaries of the posterior:

    • Posterior mean a′a′+b′=w aa+b+(1−w) kn\frac{a'}{a'+b'} = w\,\frac{a}{a+b} + (1-w)\,\frac{k}{n} with w=a+ba+b+nw = \frac{a+b}{a+b+n}: a weighted average of the prior mean and the MLE. The prior counts like a+ba + b observations.
    • MAP (the mode) a′−1a′+b′−2\frac{a'-1}{a'+b'-2}, for a′,b′>1a', b' > 1. With a=b=1a = b = 1 it equals the MLE k/nk/n.
    • Credible interval: the 2.5% and 97.5% quantiles of Beta(a′,b′a', b') (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 θ\theta, so

    θ^MAP=arg⁡max⁡θ[ℓ(θ)+log⁡p(θ)]=arg⁡min⁡θ[−ℓ(θ)⏟loss−log⁡p(θ)⏟regulariser].\hat\theta_{\text{MAP}} = \arg\max_\theta \big[\ell(\theta) + \log p(\theta)\big] = \arg\min_\theta \big[\underbrace{-\ell(\theta)}_{\text{loss}} \underbrace{- \log p(\theta)}_{\text{regulariser}}\big].

    L2 = Gaussian prior. Linear regression y=Xw+εy = Xw + \varepsilon with noise ε∼N(0,σ2I)\varepsilon \sim \mathcal N(0, \sigma^2 I) and prior w∼N(0,σw2I)w \sim \mathcal N(0, \sigma_w^2 I):

    −log⁡p(w∣y)=12σ2∥y−Xw∥2+12σw2∥w∥2+const.-\log p(w \mid y) = \frac{1}{2\sigma^2}\|y - Xw\|^2 + \frac{1}{2\sigma_w^2}\|w\|^2 + \text{const}.

    Multiply by 2σ22\sigma^2: this is ridge regression, ∥y−Xw∥2+λ∥w∥2\|y - Xw\|^2 + \lambda\|w\|^2 with λ=σ2/σw2\lambda = \sigma^2/\sigma_w^2. A Laplace prior p(wj)∝e−∣wj∣/bp(w_j) \propto e^{-|w_j|/b} gives the lasso, ∥y−Xw∥2+λ∥w∥1\|y - Xw\|^2 + \lambda\|w\|_1 with λ=2σ2/b\lambda = 2\sigma^2/b. 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 S=10S = 10 minutes; model Exponential(λ\lambda); flat prior on the rate λ\lambda.

    1. In λ\lambda: the posterior is ∝λ5e−10λ\propto \lambda^5 e^{-10\lambda}, with mode λMAP=5/10=0.5\lambda_{\text{MAP}} = 5/10 = 0.5, equal to the MLE.
    2. In the mean waiting time θ=1/λ\theta = 1/\lambda: ∣dλ/dθ∣=1/θ2|d\lambda/d\theta| = 1/\theta^2, so the same prior becomes p(θ)∝1/θ2p(\theta) \propto 1/\theta^2. The posterior is ∝θ−5e−10/θ⋅θ−2=θ−7e−10/θ\propto \theta^{-5}e^{-10/\theta} \cdot \theta^{-2} = \theta^{-7}e^{-10/\theta}.
    3. Set the derivative of −7log⁡θ−10/θ-7\log\theta - 10/\theta to zero: −7/θ+10/θ2=0-7/\theta + 10/\theta^2 = 0, so θMAP=10/7≈1.43\theta_{\text{MAP}} = 10/7 \approx 1.43 minutes, not 1/0.5=21/0.5 = 2 minutes.

    A "flat prior" is not neutral: flat in λ\lambda is not flat in 1/λ1/\lambda. Posterior quantiles (such as the median) move correctly under a monotone change of variable; the mode and the mean in general do not.

    Quick check

    You train with the loss ∑i(yi−w⊤xi)2+λ∥w∥2\sum_i (y_i - w^\top x_i)^2 + \lambda \|w\|^2. Which prior on ww makes the minimiser a MAP estimate, if the noise variance is σ2\sigma^2?

    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 θ\theta.

    Gaussian mean. Data xi∼N(μ,σ2)x_i \sim \mathcal N(\mu, \sigma^2), σ2\sigma^2 known; prior N(μ0,τ02)\mathcal N(\mu_0, \tau_0^2). The posterior mean is μ^B=wxˉ+(1−w)μ0\hat\mu_{\text{B}} = w\bar x + (1 - w)\mu_0 with w=nn+σ2/τ02w = \frac{n}{n + \sigma^2/\tau_0^2} (derived below).

    1. E[μ^B]=wμ+(1−w)μ0\mathbb{E}[\hat\mu_{\text{B}}] = w\mu + (1 - w)\mu_0, so the bias is (1−w)(μ0−μ)(1 - w)(\mu_0 - \mu).
    2. Var⁡(μ^B)=w2σ2/n\operatorname{Var}(\hat\mu_{\text{B}}) = w^2\sigma^2/n, smaller than the variance σ2/n\sigma^2/n of xˉ\bar x.
    3. MSE(μ^B)=w2σ2n+(1−w)2(μ−μ0)2\text{MSE}(\hat\mu_{\text{B}}) = w^2\frac{\sigma^2}{n} + (1 - w)^2(\mu - \mu_0)^2, while MSE(xˉ)=σ2/n\text{MSE}(\bar x) = \sigma^2/n for every μ\mu.
    4. Solving MSE(μ^B)<σ2/n\text{MSE}(\hat\mu_{\text{B}}) < \sigma^2/n gives exactly (μ−μ0)2<σ2n+2τ02(\mu - \mu_0)^2 < \frac{\sigma^2}{n} + 2\tau_0^2.

    So the prior helps when its guess μ0\mu_0 is roughly right and hurts when it is far off. It trades a little bias for a larger cut in variance.

    Interactive figure: loading…

    Compare three estimators of a coin's pp at every true pp. The curves are exact MSEs (sums over all outcomes kk): the orange MLE k/nk/n, the aqua MAP k+a−1n+a+b−2\frac{k + a - 1}{n + a + b - 2} and the dashed aqua posterior mean k+an+a+b\frac{k + a}{n + a + b}. 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 pp with 4000 experiments (blue dots). A strong prior wins big near its mean and loses far from it; a larger nn makes all curves agree.

    Gaussian–Gaussian (known variance) #

    Data: x1,…,xnx_1, \dots, x_n i.i.d. N(μ,σ2)\mathcal N(\mu, \sigma^2) with σ2\sigma^2 known. Prior: μ∼N(μ0,τ02)\mu \sim \mathcal N(\mu_0, \tau_0^2).

    1. log⁡p(μ∣D)=−(μ−μ0)22τ02−∑i(xi−μ)22σ2+const\log p(\mu \mid \mathcal D) = -\frac{(\mu - \mu_0)^2}{2\tau_0^2} - \sum_i \frac{(x_i - \mu)^2}{2\sigma^2} + \text{const}.
    2. Collect the powers of μ\mu: −12μ2(1τ02+nσ2)+μ(μ0τ02+nxˉσ2)+const-\tfrac12 \mu^2 \Big(\frac{1}{\tau_0^2} + \frac{n}{\sigma^2}\Big) + \mu\Big(\frac{\mu_0}{\tau_0^2} + \frac{n\bar x}{\sigma^2}\Big) + \text{const}.
    3. Complete the square: −12Aμ2+Bμ=−A2(μ−B/A)2+const-\tfrac12 A\mu^2 + B\mu = -\tfrac{A}{2}(\mu - B/A)^2 + \text{const}, the log-density of a Gaussian with precision AA and mean B/AB/A.
    4. So μ∣D∼N(μn,τn2)\mu \mid \mathcal D \sim \mathcal N(\mu_n, \tau_n^2) with
    1τn2=1τ02+nσ2,μn=τn2(μ0τ02+nxˉσ2)=w xˉ+(1−w) μ0,w=n/σ21/τ02+n/σ2.■\frac{1}{\tau_n^2} = \frac{1}{\tau_0^2} + \frac{n}{\sigma^2}, \qquad \mu_n = \tau_n^2 \Big(\frac{\mu_0}{\tau_0^2} + \frac{n\bar x}{\sigma^2}\Big) = w\,\bar x + (1 - w)\,\mu_0, \quad w = \frac{n/\sigma^2}{1/\tau_0^2 + n/\sigma^2}. \quad\blacksquare

    Posterior precision = prior precision + data precision. The data precision n/σ2n/\sigma^2 is nI(μ)nI(\mu), the Fisher information of lesson 09. The prior is worth σ2/τ02\sigma^2/\tau_0^2 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 η\eta, the likelihood of nn observations is exp⁡(η⊤s−nA(η))\exp\big(\eta^\top s - nA(\eta)\big) with s=∑iT(xi)s = \sum_i T(x_i) (lesson 08). Take a prior of the same form, with hyperparameters τ\tau and ν>0\nu > 0: p(η)∝exp⁡(η⊤τ−νA(η))p(\eta) \propto \exp\big(\eta^\top\tau - \nu A(\eta)\big). The posterior is ∝exp⁡(η⊤(τ+s)−(ν+n)A(η))\propto \exp\big(\eta^\top(\tau + s) - (\nu + n)A(\eta)\big), the same family with the update τ←τ+∑iT(xi)\tau \leftarrow \tau + \sum_i T(x_i), ν←ν+n\nu \leftarrow \nu + n. The prior acts like ν\nu pseudo-observations.

    Gamma–Poisson. Counts xi∼x_i \sim Poisson(λ\lambda), prior λ∼\lambda \sim Gamma(a,ba, b) (shape aa, rate bb). The posterior is ∝λSe−nλ⋅λa−1e−bλ\propto \lambda^{S}e^{-n\lambda} \cdot \lambda^{a-1}e^{-b\lambda} with S=∑ixiS = \sum_i x_i, that is Gamma(a+S, b+na + S,\ b + n): mean a+Sb+n\frac{a + S}{b + n}, MAP a+S−1b+n\frac{a + S - 1}{b + n}. The prior is worth bb observation periods with aa events in total.

    Quick check

    Sign-ups per hour are Poisson(λ\lambda). Prior Gamma(3, 1) (shape 3, rate 1). In 5 hours you see 5,7,4,6,35, 7, 4, 6, 3 sign-ups. What is the posterior mean of λ\lambda?

    The posterior predictive distribution #

    To predict a new observation x∗x^*, average the model over the posterior:

    p(x∗∣D)=∫p(x∗∣θ) p(θ∣D) dθ.p(x^* \mid \mathcal D) = \int p(x^* \mid \theta)\, p(\theta \mid \mathcal D)\, d\theta .

    It has two sources of spread: the noise of x∗x^* for a fixed θ\theta, and the remaining uncertainty about θ\theta. By the law of total variance (lesson 04),

    Var⁡(x∗∣D)=E[Var⁡(x∗∣θ)∣D]⏟noise+Var⁡(E[x∗∣θ]∣D)⏟parameter uncertainty.\operatorname{Var}(x^* \mid \mathcal D) = \underbrace{\mathbb{E}\big[\operatorname{Var}(x^* \mid \theta) \mid \mathcal D\big]}_{\text{noise}} + \underbrace{\operatorname{Var}\big(\mathbb{E}[x^* \mid \theta] \mid \mathcal D\big)}_{\text{parameter uncertainty}} .

    A plug-in prediction p(x∗∣θ^)p(x^* \mid \hat\theta) keeps only the first term, so it is too narrow.

    • Gaussian. x∗=μ+ε∗x^* = \mu + \varepsilon^* with μ∣D∼N(μn,τn2)\mu \mid \mathcal D \sim \mathcal N(\mu_n, \tau_n^2) and independent noise ε∗∼N(0,σ2)\varepsilon^* \sim \mathcal N(0, \sigma^2). A sum of independent Gaussians is Gaussian: x∗∣D∼N(μn, σ2+τn2)x^* \mid \mathcal D \sim \mathcal N(\mu_n,\ \sigma^2 + \tau_n^2).
    • One coin flip. P(x∗=1∣D)=∫01p  Beta(p;a′,b′) dp=a′a′+b′P(x^* = 1 \mid \mathcal D) = \int_0^1 p\; \text{Beta}(p; a', b')\, dp = \frac{a'}{a'+b'}, the posterior mean.
    • mm future flips. The number of heads is beta-binomial, with mean mpˉm\bar p and variance mpˉ(1−pˉ) a′+b′+ma′+b′+1m\bar p(1-\bar p)\,\frac{a'+b'+m}{a'+b'+1}, where pˉ=a′a′+b′\bar p = \frac{a'}{a'+b'}. The last factor is above 1 for m>1m > 1: all mm flips share the same unknown pp, so their errors do not cancel.
    Interactive figure: loading…

    Predict the number of successes in the next mm trials. You saw kk successes in nn trials; the prior is Beta(1, 1). The aqua bars are the posterior predictive (beta-binomial), the orange bars the plug-in Binomial(m,p^m, \hat p). With little data the predictive is much wider. Increase nn (with the same rate k/nk/n) and the two distributions become the same; increase mm and the gap grows.

    Credible intervals and confidence intervals #

    • A 95% credible interval CC satisfies P(θ∈C∣D)=0.95P(\theta \in C \mid \mathcal D) = 0.95: a probability statement about θ\theta, given the observed data and the prior.
    • A 95% confidence interval is a random interval C(X)C(X) with Pθ(θ∈C(X))=0.95P_\theta(\theta \in C(X)) = 0.95 for every θ\theta (lesson 06): a statement about the procedure over repeated data sets. For one realised interval, θ\theta is either in it or not.

    They can agree numerically (a flat prior on a Gaussian mean gives xˉ±1.96σ/n\bar x \pm 1.96\sigma/\sqrt n for both), but they answer different questions. Averaged over θ\theta drawn from the prior, a credible interval covers θ\theta exactly 95% of the time. At a fixed θ\theta 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 0.720.72 at n=10n = 10, 0.920.92 at n=100n = 100 and 0.950.95 at n=1000n = 1000 (exact sums over kk).

    The prior's influence vanishes (usually). The log-likelihood is a sum of nn terms and grows like nn; the log-prior stays fixed. In the conjugate formulas, the prior weights a+ba+b+n\frac{a+b}{a+b+n} and 1/τ021/τ02+n/σ2\frac{1/\tau_0^2}{1/\tau_0^2 + n/\sigma^2} 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 θ0\theta_0, the posterior approaches N(θ^MLE, (nI(θ0))−1)\mathcal N\big(\hat\theta_{\text{MLE}},\ (nI(\theta_0))^{-1}\big) in total variation as n→∞n \to \infty. So credible intervals become Wald confidence intervals, and Bayesian and frequentist answers agree for large nn. The simplest case: the variance of Beta(a+k,b+n−ka + k, b + n - k) is a′b′(a′+b′)2(a′+b′+1)≈p^(1−p^)n=1nI(p^)\frac{a'b'}{(a'+b')^2(a'+b'+1)} \approx \frac{\hat p(1 - \hat p)}{n} = \frac{1}{nI(\hat p)}. The theorem fails when the prior gives zero density near the truth (no data can fix that), when the number of parameters grows with nn, or when the model is not identifiable.

    Answers to section 1. (1) The prior precision is 1/1=11/1 = 1 and the data precision is n/σ2=8/4=2n/\sigma^2 = 8/4 = 2. The posterior precision is 3, so the variance is 1/31/3 and the mean is 1⋅0+2⋅33=2\frac{1 \cdot 0 + 2 \cdot 3}{3} = 2: two thirds of the way from 0 to 3, because the data are twice as precise as the prior. (2) Wider: N(μn,σ2+τn2)=N(2,4+1/3)=N(2,13/3)\mathcal N(\mu_n, \sigma^2 + \tau_n^2) = \mathcal N(2, 4 + 1/3) = \mathcal N(2, 13/3), against the plug-in variance σ2=4\sigma^2 = 4. The plug-in drops the parameter-uncertainty term τn2\tau_n^2. Here τn2≈σ2/n→0\tau_n^2 \approx \sigma^2/n \to 0, so the gap vanishes as nn 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 0.050.05, worth 20 users. Variant B converts k=12k = 12 of n=100n = 100 users; the control A converts 8 of 100.

    1. Posterior of B. Beta(1+12, 19+881 + 12,\ 19 + 88) = Beta(13, 107).
    2. Posterior mean. 13/120≈0.10813/120 \approx 0.108. Check with the weights: w=20/120=1/6w = 20/120 = 1/6 on the prior, and 16⋅0.05+56⋅0.12=0.0083+0.1≈0.108\frac16 \cdot 0.05 + \frac56 \cdot 0.12 = 0.0083 + 0.1 \approx 0.108 ✓.
    3. MAP and MLE. MAP =13−1120−2=12/118≈0.102= \frac{13 - 1}{120 - 2} = 12/118 \approx 0.102. MLE =0.12= 0.12.
    4. Credible interval. The 2.5% and 97.5% quantiles of Beta(13, 107) are 0.0590.059 and 0.1700.170. The Wald interval of lesson 09 is 0.12±1.960.12⋅0.88/100=[0.056, 0.184]0.12 \pm 1.96\sqrt{0.12 \cdot 0.88/100} = [0.056,\ 0.184]: centred on the MLE, with no pull toward the prior.
    5. Predictive. The next user converts with probability 13/120≈0.10813/120 \approx 0.108. For the next 50 users, the beta-binomial variance is 50⋅0.108⋅0.892⋅170121≈6.7950 \cdot 0.108 \cdot 0.892 \cdot \frac{170}{121} \approx 6.79; the plug-in Binomial(50, 0.12) has variance 50⋅0.12⋅0.88=5.2850 \cdot 0.12 \cdot 0.88 = 5.28.
    6. Is B better than A? The posterior of A is Beta(1+8, 19+921 + 8,\ 19 + 92) = Beta(9, 111). Draw many pairs (pA,pB)(p_A, p_B) from the two posteriors and count how often pB>pAp_B > p_A: about 0.820.82. (Numerical integration of ∫fB(p) FA(p) dp\int f_B(p)\,F_A(p)\,dp, with the density fBf_B and the CDF FAF_A, gives 0.8190.819.) The posterior mean of the lift pB−pAp_B - p_A is 13120−9120≈0.033\frac{13}{120} - \frac{9}{120} \approx 0.033.
    7. Expected loss. If you ship B and B is worse, you lose pA−pBp_A - p_B. The expected loss E[max⁡(pA−pB,0)]\mathbb{E}[\max(p_A - p_B, 0)] is about 0.0040.004 (0.4 percentage points); for shipping A it is about 0.0370.037. A common rule: ship when the expected loss is below a threshold you accept.
    Interactive figure: loading…

    Run a Bayesian A/B test. Set the visitors and conversions of each variant. The top panel shows the posteriors of pAp_A (blue) and pBp_B (aqua) with a uniform prior; the bottom panel the histogram of pB−pAp_B - p_A from 4000 posterior draws, aqua where B wins and magenta where A wins. The readout gives P(pB>pA∣D)P(p_B > p_A \mid \mathcal D) 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 0.820.82 has a standard error of about 0.82⋅0.18/106≈0.0004\sqrt{0.82 \cdot 0.18/10^6} \approx 0.0004.

    6. Where it shows up #

    • Regularisation. Ridge regression and weight decay are MAP estimates under a Gaussian prior (λ=σ2/σw2\lambda = \sigma^2/\sigma_w^2); 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 pp 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 P(pB>pA∣D)P(p_B > p_A \mid \mathcal D), the posterior of the lift, and the expected loss. Caution: a rule like "stop when P(pB>pA∣D)>0.95P(p_B > p_A \mid \mathcal D) > 0.95", 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. p(x∗∣θ^)p(x^* \mid \hat\theta) 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. λ=σ2/σw2\lambda = \sigma^2/\sigma_w^2 (noise variance over prior variance), not σw2\sigma_w^2.
    • 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(1,b1, b) prior and zero successes give p^MAP=0\hat p_{\text{MAP}} = 0).
    • "There is a 95% probability that θ\theta 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 n=10n = 10 above).
    • A "non-informative" flat prior. Flat in one parametrisation is not flat in another (λ\lambda vs 1/λ1/\lambda), so it still carries information.

    8. Check yourself #

    1. 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.
      AnswerBeta(1, 31). Mean 1/32≈0.0311/32 \approx 0.031; MAP 0. The CDF of Beta(1, bb) is 1−(1−p)b1 - (1-p)^b, so the upper bound solves (1−p)31=0.05(1-p)^{31} = 0.05: pu=1−0.051/31≈0.092p_u = 1 - 0.05^{1/31} \approx 0.092. Unlike the Wald interval of lesson 09, it does not collapse to a point.
    2. Show that updating a Gaussian mean with batch 1 and then batch 2 gives the same posterior as one update with both batches.
      AnswerEach update adds nj/σ2n_j/\sigma^2 to the precision and njxˉj/σ2n_j\bar x_j/\sigma^2 to "precision times mean". Sums do not depend on order or grouping, so in both cases the final precision is 1/τ02+(n1+n2)/σ21/\tau_0^2 + (n_1 + n_2)/\sigma^2 and the final precision times mean is μ0/τ02+(n1xˉ1+n2xˉ2)/σ2\mu_0/\tau_0^2 + (n_1\bar x_1 + n_2\bar x_2)/\sigma^2.
    3. For the kitchen scale of lesson 08 (n=4n = 4 readings with xˉ=1.3\bar x = 1.3, noise variance σ2=4\sigma^2 = 4) and the prior N(0,1)\mathcal N(0, 1), compute the posterior mean and variance. For which true offsets μ\mu does the posterior mean have a smaller MSE than xˉ\bar x?
      AnswerData precision 4/4=14/4 = 1, prior precision 1, so w=0.5w = 0.5: posterior mean 0.5⋅1.3=0.650.5 \cdot 1.3 = 0.65, variance 1/21/2. MSE of the posterior mean: w2σ2/n+(1−w)2μ2=0.25+0.25μ2w^2\sigma^2/n + (1-w)^2\mu^2 = 0.25 + 0.25\mu^2; MSE of xˉ\bar x: 11. It wins when μ2<3\mu^2 < 3, that is ∣μ∣<1.73|\mu| < 1.73, in agreement with (μ−μ0)2<σ2/n+2τ02=3(\mu - \mu_0)^2 < \sigma^2/n + 2\tau_0^2 = 3.
    4. Does the MAP of the mean waiting time θ=1/λ\theta = 1/\lambda equal 1/λMAP1/\lambda_{\text{MAP}}? Explain with the example of section 3.
      AnswerNo. With a flat prior on λ\lambda, λMAP=0.5\lambda_{\text{MAP}} = 0.5, so 1/λMAP=21/\lambda_{\text{MAP}} = 2. In θ\theta the prior picks up the Jacobian 1/θ21/\theta^2, and the posterior θ−7e−10/θ\theta^{-7}e^{-10/\theta} has its mode at 10/7≈1.4310/7 \approx 1.43. Densities change with a Jacobian; the mode moves. The MLE has no Jacobian and is invariant.
    5. For one future binary outcome the posterior predictive is Bernoulli(pˉ\bar p). In what sense is the Bayesian predictive "wider" than the plug-in Bernoulli(p^\hat p)?
      AnswerFor a single trial both are Bernoulli distributions; they differ only in the probability (pˉ\bar p is pulled toward the prior mean), and a Bernoulli's variance is fixed by its mean. The extra spread appears for m>1m > 1 future trials: the beta-binomial variance mpˉ(1−pˉ)a′+b′+ma′+b′+1m\bar p(1-\bar p)\frac{a'+b'+m}{a'+b'+1} is larger than the binomial mpˉ(1−pˉ)m\bar p(1-\bar p), because all mm trials share the same unknown pp.
    6. "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.
      AnswerCredible: "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."
    Recall cardsAnswer in your head first, then reveal. Add the cards to your review deck to see them again just before you would forget.
    1. Write Bayes' rule for a parameter θ\theta and name the terms.

    2. Posterior of a coin's pp with prior Beta(a,ba, b) after kk heads in nn flips?

    3. Posterior precision and mean for a Gaussian mean with prior N(μ0,τ02)\mathcal N(\mu_0, \tau_0^2) and known noise σ2\sigma^2?

    4. MAP of a Bernoulli pp with prior Beta(a,ba, b)?

    5. Which prior turns an L2 penalty λ∥w∥2\lambda\|w\|^2 on a squared-error loss into a MAP estimate?

    6. What is the posterior predictive distribution?

    7. Why is the posterior predictive wider than a plug-in prediction?

    8. What does a 95% credible interval mean, compared with a confidence interval?

    9. What is a conjugate prior?

    10. Is the MAP invariant under a change of parameter?

    Open the review →

    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 4/54/5.
    • "Derive ridge regression from a Bayesian view." — Gaussian likelihood and Gaussian prior; the negative log-posterior is 12σ2∥y−Xw∥2+12σw2∥w∥2\frac{1}{2\sigma^2}\|y - Xw\|^2 + \frac{1}{2\sigma_w^2}\|w\|^2, so λ=σ2/σw2\lambda = \sigma^2/\sigma_w^2.
    • "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 P(B better than A)P(B \text{ better than } A)?" — Sample both Beta posteriors and count, or compute ∫fB(p) FA(p) dp\int f_B(p)\,F_A(p)\,dp.
    • "When does the prior still matter with lots of data?" — When it excludes the truth, when the number of parameters grows with nn (hierarchical models, many small groups), and in directions the data do not inform.
    • "Credible vs confidence interval?" — A probability about θ\theta 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:

    1. A grid posterior for a coin, compared with the conjugate Beta posterior (maximum absolute difference).
    2. map_gaussian_mean and the Gaussian–Gaussian posterior, checked against the precision formula and a numerical optimiser.
    3. MSE of the MLE and of the MAP for a coin, by simulation over a grid of true pp, against the exact sums.
    4. The beta-binomial predictive for the next 50 users against the plug-in binomial.
    5. A Bayesian A/B test: P(pB>pA)P(p_B > p_A) by Monte Carlo and by numerical integration, and the expected loss.

    11. Watch and read #

    A probability as an unknown with its own distribution, using reviews of online sellers; it builds the Beta posterior and Laplace's rule.
    Open on YouTube · the player loads from youtube-nocookie.com when you press play
    Prior, likelihood, posterior and the evidence, with the link to regularisation.
    Open on YouTube · the player loads from youtube-nocookie.com when you press play
    Priors, conjugate priors, Jeffreys priors and the comparison with the frequentist view.
    Open on YouTube · the player loads from youtube-nocookie.com when you press play