SafeZone AI Learn
Learn/ Mathematical Foundations/ Probability & Statistical Inference · lesson 4 of 9

Bayesian inference

Bayes' theorem as a learning rule: watch a Beta prior absorb coin flips into a posterior, see regularization unmasked as a prior in disguise, and learn when the Bayesian and frequentist answers stop disagreeing.

Maximum likelihood answers “which parameters make the data least surprising?” and gave a confident absurdity on three heads in three flips. The Bayesian move is to add the one ingredient MLE lacks: what you believed before the data arrived. This lesson builds the machinery — prior, likelihood, posterior — on the cleanest possible example, watches it learn live, and then delivers the payoff this curriculum has been promising since the Regularization lesson: the penalties you have been adding to losses are priors, term for term.

Bayes’ theorem, promoted from formula to learning rule

As a formula it is one line of conditional-probability algebra from lesson 1:

p(θD)  =  p(Dθ)  p(θ)p(D)    p(Dθ)likelihood  p(θ)prior.p(\theta \mid \mathcal D) \;=\; \frac{p(\mathcal D \mid \theta)\; p(\theta)}{p(\mathcal D)} \;\propto\; \underbrace{p(\mathcal D \mid \theta)}_{\text{likelihood}} \; \underbrace{p(\theta)}_{\text{prior}} .

Read as a learning rule it says: beliefs are distributions over parameters, and data updates them by reweighting — multiply prior belief by how well each θ\theta explains the observations, renormalize. Three consequences deserve immediate notice. The output is a whole posterior distribution, not a point — uncertainty comes built in rather than bolted on. The update is sequential: today’s posterior is tomorrow’s prior, and processing data one batch at a time provably gives the same answer as all at once. And the denominator p(D)p(\mathcal D) — the evidence — is a constant in θ\theta you can usually ignore, until model comparison, where it becomes the star (it automatically penalizes complexity, the “Bayesian Occam’s razor”).

The cleanest example in statistics: Beta–Bernoulli

Estimate a coin’s bias pp from flips. Take the prior pBeta(α,β)p \sim \mathrm{Beta}(\alpha, \beta), with density pα1(1p)β1\propto p^{\alpha-1}(1-p)^{\beta-1}. Multiply by the Bernoulli likelihood ps(1p)fp^{s}(1-p)^{f} for ss heads and ff tails, and the posterior is

pD    Beta(α+s,  β+f)p \mid \mathcal D \;\sim\; \mathrm{Beta}(\alpha + s,\; \beta + f)

— the same family back, with the data simply added to the parameters. This is conjugacy: prior and likelihood matched so the update is closed-form bookkeeping, and it hands you the exact reading of the prior: Beta(α,β)\mathrm{Beta}(\alpha, \beta) is α+β2\alpha{+}\beta{-}2 imaginary flips you saw before the real ones. The posterior mean makes the compromise explicit:

E[pD]=α+sα+β+s+f=λαα+βprior mean+(1λ)ss+fMLE,λ=α+βα+β+n\mathbb{E}[p \mid \mathcal D] = \frac{\alpha + s}{\alpha + \beta + s + f} = \lambda\, \underbrace{\frac{\alpha}{\alpha+\beta}}_{\text{prior mean}} + (1 - \lambda)\, \underbrace{\frac{s}{s+f}}_{\text{MLE}}, \quad \lambda = \frac{\alpha + \beta}{\alpha + \beta + n}

— a weighted average that starts at the prior and slides to the MLE as real flips outnumber imaginary ones. Watch that slide happen:

Start at Beta(2,2) — a mild “probably fair-ish” belief — and feed it single flips: each head drags the curve right, each tail left, and early flips move it far more than late ones (the prior’s weight λ shrinking as n grows). Now the three-heads absurdity, resolved: after H,H,H the MLE says p = 1, but your posterior mean says 5/7 ≈ 0.71 — skeptical exactly in proportion to how little data three flips is. Then run the two instructive extremes. Beta(1,1) is the flat prior: the posterior mean becomes (s+1)/(n+2) — Laplace’s rule of succession, still refusing the absurdity. And a stubborn Beta(30,30) versus a true bias of 0.75: feed it 100 flips and watch the data win anyway — with enough evidence, reasonable priors converge to the same place, which is the honest answer to “isn’t the prior just subjective?” It matters exactly as long as data is scarce, which is precisely when you NEED something to matter.

The reveal: regularization is a prior

Now the payoff. Suppose instead of the full posterior you just want its peak — the maximum a posteriori (MAP) estimate. Take logs of Bayes’ rule:

θ^MAP=argmaxθ  [logp(Dθ)log-likelihood+logp(θ)penalty!].\hat\theta_{\text{MAP}} = \arg\max_\theta\; \Big[ \underbrace{\log p(\mathcal D \mid \theta)}_{\text{log-likelihood}} + \underbrace{\log p(\theta)}_{\text{penalty!}} \Big].

The log-prior is an additive term in the objective — a regularizer. Make it concrete with a Gaussian prior θN(0,τ2I)\theta \sim \mathcal N(0, \tau^2 I): logp(θ)=12τ2θ2+const\log p(\theta) = -\frac{1}{2\tau^2}\lVert\theta\rVert^2 + \text{const}, so MAP estimation with Gaussian noise and a Gaussian prior is

minθ  12σ2yXθ2+12τ2θ2\min_\theta\; \frac{1}{2\sigma^2}\lVert y - X\theta \rVert^2 + \frac{1}{2\tau^2}\lVert \theta \rVert^2

ridge regression, exactly, with λ=σ2/τ2\lambda = \sigma^2/\tau^2. A Laplace prior yields the 1\ell_1 penalty — lasso — whose sharp peak at zero is why it zeroes coefficients out. The whole regularization toolkit is unmasked: weight decay asserts “parameters are probably small,” sparsity penalties assert “most parameters are probably zero,” and choosing λ\lambda is choosing how strongly you believe it. Even the SVD lesson’s ridge-shrinkage formula σi2/(σi2+λ)\sigma_i^2/(\sigma_i^2 + \lambda) is now a statement about posterior means under that Gaussian prior. This is the curriculum’s tightest unification so far: MLE, MAP and regularized loss minimization are one family, differing only in what they assume about θ\theta before seeing data.

Credible vs confident, and what full posteriors buy

Two honesty notes, both load-bearing. First, vocabulary: the widget’s band is a credible interval — “given prior and data, pp lies here with probability 0.95,” the statement civilians think confidence intervals make (next lesson draws the frequentist contrast precisely). Second, cost: the Beta posterior was free only because of conjugacy. For neural networks the posterior is a billion-dimensional object nobody can normalize — hence the working hierarchy: MAP (cheap: just regularized optimization — what almost all deep learning does), MCMC (sampling from the posterior; gold standard, expensive), variational inference (fit a tractable approximation by optimization — the idea inside VAEs, ahead in the Deep Learning track). When does paying for a full posterior matter? Whenever the tails drive the decision: medical calls, pricing risk, exploration bonuses in RL (Thompson sampling literally acts by sampling this lesson’s posteriors — the bandit connection returns in the RL track), and any setting where “how sure are we?” changes what you do next.

import numpy as np
from scipy import stats

rng = np.random.default_rng(7)
flips = rng.binomial(1, 0.75, size=100)          # hidden truth 0.75

a, b = 2.0, 2.0                                   # Beta(2,2) prior
for i, x in enumerate(flips, 1):
    a, b = a + x, b + (1 - x)                     # one-line Bayesian update
post = stats.beta(a, b)
print(post.mean(), post.interval(0.95))           # ≈ 0.73, tight around truth
# sequential == batch: same (a, b) as a + sum(flips), b + n - sum(flips)

Exercises

Work these before the next lesson

  1. Derive the Beta posterior update from Bayes’ rule (multiply densities, recognize the family, ignore constants). Then prove the sequential-equals-batch claim in one sentence about exponents.
    Solution

    Worked solutions are part of Premiumunlock all of them for £5/month →

  2. 5 more exercises — each with a worked solution — are part of Premium. Unlock everything for £5/month →

References

  • D. MacKay, Information Theory, Inference, and Learning Algorithms, ch. 2–3 & 28 — Bayesian reasoning and Occam’s razor, free online and unmatched.
  • A. Gelman et al., Bayesian Data Analysis, 3rd ed. — the field’s reference; ch. 1–2 cover this lesson at depth.
  • K. Murphy, Probabilistic Machine Learning: An Introduction, 2022 — the MAP/regularization bridge, textbook-official.
  • P.-S. Laplace, “Mémoire sur la probabilité des causes par les événements”, 1774 — the rule of succession, from the man who used it on sunrises.