AnyLearn
All lessons
Mathintermediate

Bayesian Inference

Understand what it really means to update beliefs with data. Derive Bayes' theorem from first principles, dissect the roles of prior, likelihood, posterior, and evidence, work through a complete Beta-Binomial conjugate example numerically, and see why the base-rate fallacy trips up even experts.

Updated · AI-authored, review-gated · how lessons are made

Not signed in: your progress and quiz score won't be saved.
Progress1 / 9

Bayes' theorem from the product rule

One line of algebra, endlessly applicable. From the definition of conditional probability:

P(AB)=P(AB)P(B)=P(BA)P(A).P(A \cap B) = P(A \mid B)\, P(B) = P(B \mid A)\, P(A).

Rearrange the right two expressions:

P(AB)=P(BA)P(A)P(B).P(A \mid B) = \frac{P(B \mid A)\, P(A)}{P(B)}.

In statistical inference we replace AA with a parameter θ\theta and BB with observed data DD:

P(θD)=P(Dθ)P(θ)P(D).\boxed{P(\theta \mid D) = \frac{P(D \mid \theta)\, P(\theta)}{P(D)}.}

Nothing more than the chain rule. The interpretation is where all the depth lives.

Full lesson text

All 9 steps on one page, for reading, reference, and search.

Show

1. Bayes' theorem from the product rule

One line of algebra, endlessly applicable. From the definition of conditional probability:

P(AB)=P(AB)P(B)=P(BA)P(A).P(A \cap B) = P(A \mid B)\, P(B) = P(B \mid A)\, P(A).

Rearrange the right two expressions:

P(AB)=P(BA)P(A)P(B).P(A \mid B) = \frac{P(B \mid A)\, P(A)}{P(B)}.

In statistical inference we replace AA with a parameter θ\theta and BB with observed data DD:

P(θD)=P(Dθ)P(θ)P(D).\boxed{P(\theta \mid D) = \frac{P(D \mid \theta)\, P(\theta)}{P(D)}.}

Nothing more than the chain rule. The interpretation is where all the depth lives.

2. Prior, likelihood, posterior, evidence

Each term in Bayes' theorem has a job:

TermSymbolRole
PriorP(θ)P(\theta)Your belief about θ\theta before seeing data
LikelihoodP(Dθ)P(D \mid \theta)How probable is the data if θ\theta were true?
PosteriorP(θD)P(\theta \mid D)Updated belief after seeing data
EvidenceP(D)P(D)Normalizing constant; marginalizes out θ\theta

The evidence P(D)=P(Dθ)P(θ)dθP(D) = \int P(D \mid \theta)\, P(\theta)\, d\theta is usually the hardest to compute — but for inference you often just need the shape of the posterior, so you write:

P(θD)P(Dθ)P(θ).P(\theta \mid D) \propto P(D \mid \theta)\, P(\theta).

Posterior \propto likelihood ×\times prior. The evidence is just the normalizer that makes everything sum to 1.

3. Conjugate priors

A prior P(θ)P(\theta) is conjugate to a likelihood P(Dθ)P(D \mid \theta) when the posterior has the same functional form as the prior — only the parameters change. Conjugacy makes inference analytic.

The canonical pair: Beta prior with Binomial likelihood.

If θBeta(α,β)\theta \sim \text{Beta}(\alpha, \beta) and DD consists of kk successes in nn trials: P(θD)=Beta(α+k,  β+nk).P(\theta \mid D) = \text{Beta}(\alpha + k,\; \beta + n - k).

Intuition: α\alpha and β\beta act like pseudo-counts of prior successes and failures. Observing real successes and failures just adds to those counts. No integration required.

LikelihoodConjugate priorPosterior
BinomialBetaBeta
PoissonGammaGamma
Gaussian (mean, known σ2\sigma^2)GaussianGaussian
CategoricalDirichletDirichlet

4. Worked example: Beta-Binomial coin inference

You suspect a coin is fair. You encode this as θBeta(10,10)\theta \sim \text{Beta}(10, 10) — a prior centered at 0.5 with moderate certainty. You flip the coin 30 times and see 22 heads.

Posterior: Beta(10+22,  10+8)=Beta(32,18)\text{Beta}(10 + 22,\; 10 + 8) = \text{Beta}(32, 18).

Posterior mean: E[θD]=3232+18=3250=0.64\mathbb{E}[\theta \mid D] = \frac{32}{32 + 18} = \frac{32}{50} = 0.64.

Posterior mode (MAP estimate): θ^MAP=321502=31480.646\hat{\theta}_{\text{MAP}} = \frac{32 - 1}{50 - 2} = \frac{31}{48} \approx 0.646.

MLE (no prior): θ^MLE=22/30=0.733\hat{\theta}_{\text{MLE}} = 22/30 = 0.733. The prior pulled the estimate toward 0.5.

from scipy import stats
import numpy as np

alpha_prior, beta_prior = 10, 10
k, n = 22, 30
posterior = stats.beta(alpha_prior + k, beta_prior + n - k)
print(f"Posterior mean: {posterior.mean():.3f}")  # 0.640
print(f"95% credible interval: {posterior.interval(0.95)}")
# (0.499, 0.769)

5. MAP vs posterior mean vs MLE

Three point estimates from the posterior, with different loss functions:

θ^MLE=argmaxθP(Dθ)\hat{\theta}_{\text{MLE}} = \arg\max_\theta P(D \mid \theta) θ^MAP=argmaxθP(θD)=argmaxθ[logP(Dθ)+logP(θ)]\hat{\theta}_{\text{MAP}} = \arg\max_\theta P(\theta \mid D) = \arg\max_\theta \left[\log P(D \mid \theta) + \log P(\theta)\right] θ^PM=E[θD]=θP(θD)dθ\hat{\theta}_{\text{PM}} = \mathbb{E}[\theta \mid D] = \int \theta\, P(\theta \mid D)\, d\theta

MAP minimizes 0-1 loss (mode); posterior mean minimizes squared-error loss. MLE ignores the prior entirely.

In regularized regression: L2 regularization = MAP with a Gaussian prior; L1 regularization = MAP with a Laplace prior. What looks like a regularization trick in frequentist ML is Bayesian MAP inference in disguise.

Full Bayesian inference uses the entire posterior — not just a point — propagating uncertainty through predictions.

6. Posterior predictive distribution

Once you have a posterior P(θD)P(\theta \mid D), predicting a new observation x~\tilde{x} means marginalizing over θ\theta:

P(x~D)=P(x~θ)P(θD)dθ.P(\tilde{x} \mid D) = \int P(\tilde{x} \mid \theta)\, P(\theta \mid D)\, d\theta.

This is the posterior predictive distribution — it accounts for both the randomness in x~\tilde{x} given θ\theta and the uncertainty in θ\theta itself. It is always wider than a prediction that plugs in a single θ^\hat{\theta}.

For the Beta-Binomial example: the posterior predictive for the next flip is P(x~=1D)=E[θD]=α+kα+β+n=3250=0.64.P(\tilde{x} = 1 \mid D) = \mathbb{E}[\theta \mid D] = \frac{\alpha + k}{\alpha + \beta + n} = \frac{32}{50} = 0.64.

In Gaussian processes and Bayesian neural networks, entire posterior predictive distributions over function values are maintained — not just means.

7. The base-rate fallacy

A test for a disease is 99% sensitive (true-positive rate) and 99% specific (true-negative rate). The disease prevalence is 0.1%. You test positive. What's the probability you actually have the disease?

Let DD = disease, T+T^+ = positive test.

  • P(T+D)=0.99P(T^+ \mid D) = 0.99 (sensitivity)
  • P(T¬D)=0.99P(T^- \mid \neg D) = 0.99, so P(T+¬D)=0.01P(T^+ \mid \neg D) = 0.01 (false-positive rate)
  • P(D)=0.001P(D) = 0.001 (base rate)

By Bayes: P(DT+)=0.99×0.0010.99×0.001+0.01×0.9990.000990.010989%.P(D \mid T^+) = \frac{0.99 \times 0.001}{0.99 \times 0.001 + 0.01 \times 0.999} \approx \frac{0.00099}{0.01098} \approx 9\%.

Only 9% — not 99%. The rare base rate dominates. Most positive tests are false positives. Ignoring the prior P(D)P(D) is the base-rate fallacy, and it affects medical screening, spam filters, and fraud detection equally.

8. Bayesian vs frequentist: the real difference

The philosophical split is about what θ\theta means:

  • Frequentist: θ\theta is a fixed (unknown) constant. Probability refers only to long-run frequencies of repeatable experiments. A 95% confidence interval does not mean "θ\theta is in this interval with 95% probability" — θ\theta is fixed, not random.
  • Bayesian: θ\theta is uncertain; we model uncertainty with a probability distribution. A 95% credible interval genuinely means "we assign 95% probability to θ\theta lying here, given our prior and the data."

In practice, the two often agree asymptotically (Bernstein–von Mises theorem: with enough data, the posterior concentrates around the MLE regardless of the prior). The differences are sharpest when:

  • Data is scarce.
  • The prior captures real domain knowledge.
  • You need full uncertainty propagation (not just point estimates).

Modern ML uses both: SGD is frequentist; Bayesian optimization, Gaussian processes, and variational inference are Bayesian.

9. Sequential (online) Bayesian updating

One of the cleanest features of the Bayesian framework: today's posterior is tomorrow's prior. You don't need all data at once.

After observing D1D_1: P(θD1)P(D1θ)P(θ)P(\theta \mid D_1) \propto P(D_1 \mid \theta)\, P(\theta). After observing D2D_2: P(θD1,D2)P(D2θ)P(θD1)P(\theta \mid D_1, D_2) \propto P(D_2 \mid \theta)\, P(\theta \mid D_1).

This is identical to computing the posterior on all data jointly (assuming conditional independence of D1D_1 and D2D_2 given θ\theta). The order doesn't matter.

from scipy import stats

# Beta-Binomial sequential update
a, b = 1, 1  # flat prior
for heads, flips in [(3, 5), (7, 10), (2, 5)]:
    a += heads
    b += flips - heads
    posterior = stats.beta(a, b)
    print(f"After {heads}/{flips}: mean={posterior.mean():.3f}")
# After 3/5: mean=0.500
# After 10/15: mean=0.524
# After 12/20: mean=0.520

This sequential property underpins online learning, Kalman filters, and streaming ML systems.

Check your understanding

The lesson ends with a 5-question quiz. Take it in the player above to see your score.

  1. A disease affects 1% of the population. A test has 95% sensitivity and 90% specificity. Someone tests positive. Approximately what is the probability they have the disease?
    • 95%
    • 50%
    • About 9%
    • About 1%
  2. If $\theta \sim \text{Beta}(3, 7)$ is your prior and you observe 4 successes in 6 trials, what is your posterior?
    • $\text{Beta}(4, 6)$
    • $\text{Beta}(7, 9)$
    • $\text{Beta}(12, 42)$
    • $\text{Beta}(3, 7)$
  3. The evidence $P(D)$ in Bayes' theorem plays which role?
    • It measures how well the model fits the data.
    • It is a normalizing constant that ensures the posterior integrates to 1.
    • It is equal to the prior times the likelihood.
    • It is the probability of $\theta$ before observing any data.
  4. L2 regularization in linear regression corresponds to which Bayesian assumption?
    • A Laplace prior on the weights, promoting sparsity.
    • A Gaussian prior on the weights, shrinking them toward zero.
    • A uniform prior on the weights — no regularization.
    • A Beta prior on the weights, bounding them to $[0,1]$.
  5. You update your Beta posterior sequentially: first on 5 data points, then on 10 more. How does the final posterior compare to updating on all 15 points at once?
    • Sequential updating yields a wider posterior because information is added gradually.
    • They are identical, assuming data points are conditionally independent given $\theta$.
    • Batch updating is always more accurate than sequential updating.
    • Sequential updating gives a different result unless the data is Gaussian.

Related lessons

Math
intermediate

Counting Without Listing

Combinatorics answers how many arrangements exist without producing any of them, which is what makes password strength, hash collisions and search-space size computable at all. This lesson builds the product rule, permutations, combinations, inclusion-exclusion and the pigeonhole principle, then applies them to problems where intuition is reliably wrong.

10 steps·~15 min
Math
intermediate

Gradients, Jacobians, and Hessians: Calculus in Many Dimensions

One derivative becomes three objects once a function has many inputs and many outputs. This lesson builds the gradient, the Jacobian and the Hessian, shows what each one actually tells you, and explains why curvature decides how many steps an optimiser needs and why nobody ever writes the Hessian down.

10 steps·~15 min
Math
intermediate

The Derivative Is a Local Linear Model

Machine learning uses the derivative as a search strategy, not a symbolic exercise. This lesson builds it as the best local linear approximation, derives the gradient descent update from it, and shows why estimating derivatives numerically loses half your digits and costs one function evaluation per parameter.

10 steps·~15 min
Business
intermediate

Peeking: How Watching Your Experiment Ruins It

The most natural behaviour in experimentation, checking results daily and stopping when they look significant, quietly destroys the statistical guarantee everyone thinks they have. This lesson shows the peeking mechanism with honest arithmetic, then the fixes: fixed-horizon discipline, group sequential designs, and always-valid inference.

7 steps·~11 min