Simple Algorithm
Machine Learning · Descent · 22 min

Bayesian Inference

Priors, posteriors and predictions that average over uncertainty.

Maximum likelihood picks one parameter value and forgets the rest. Bayesian inference keeps all of them, weighted by how well they explain the data and how plausible they were to begin with. This lesson works the coin end to end: prior, posterior and evidence, predictions that average over what you do not know, credible intervals, and why the prior eventually stops mattering.

What you’ll learn

  • Apply Bayes' rule to parameters, name the prior, likelihood, posterior and evidence, and update sequentially.
  • Derive the Beta–Bernoulli posterior, write its mean as a shrinkage estimate, and compute the evidence.
  • Compute posterior predictive probabilities, and explain why they differ from plug-in predictions.
  • Distinguish credible intervals from confidence intervals, and state the Bernstein–von Mises theorem with its conditions.
  • Choose priors (informative, weakly informative, Jeffreys) and recognize them as regularizers.

Bayes' rule for parameters

Treat the unknown parameter θ\boldsymbol\theta as a random variable. Before the data it has a prior density p(θ)p(\boldsymbol\theta); the model supplies the likelihood p(D∣θ)p(\data \mid \boldsymbol\theta); Bayes' rule combines them into the posterior:

p(θ∣D)=p(D∣θ) p(θ)p(D),p(D)=∫p(D∣θ) p(θ) dθ.p(\boldsymbol\theta \mid \data) = \frac{p(\data \mid \boldsymbol\theta)\,p(\boldsymbol\theta)}{p(\data)},\qquad p(\data) = \int p(\data \mid \boldsymbol\theta)\,p(\boldsymbol\theta)\,d\boldsymbol\theta.

The denominator is the evidence, or marginal likelihood: the probability of the data averaged over the prior. It does not depend on θ\boldsymbol\theta, so for most purposes posterior ∝ likelihood × prior, and the evidence returns only when you compare models (Bayesian Model Selection).

DerivationSequential updating
  1. p(θ∣D1,D2)∝p(D2∣θ) p(D1∣θ) p(θ)p(\boldsymbol\theta \mid \data_1, \data_2) \propto p(\data_2 \mid \boldsymbol\theta)\,p(\data_1 \mid \boldsymbol\theta)\,p(\boldsymbol\theta)

    If two batches of data are conditionally independent given θ\boldsymbol\theta, the likelihood factorizes:

  2. p(θ∣D1,D2)∝p(D2∣θ)  p(θ∣D1)p(\boldsymbol\theta \mid \data_1, \data_2) \propto p(\data_2 \mid \boldsymbol\theta)\;p(\boldsymbol\theta \mid \data_1)

    Group the last two factors: they are proportional to the posterior after the first batch. So yesterday's posterior is today's prior, and the order of the batches does not matter.

  3. P(H∣E)P(¬H∣E)=P(E∣H)P(E∣¬H)⋅P(H)P(¬H)\frac{P(H \mid E)}{P(\neg H \mid E)} = \frac{P(E \mid H)}{P(E \mid \neg H)}\cdot\frac{P(H)}{P(\neg H)}

    For two hypotheses the normalizer cancels in a ratio, giving the odds form: each independent piece of evidence multiplies the odds by its likelihood ratio.

The Beta–Bernoulli model, worked fully

DerivationPrior × likelihood = posterior
  1. p(p)=pa−1(1−p)b−1B(a,b),p(D∣p)=ph(1−p)tp(p) = \frac{p^{a-1}(1-p)^{b-1}}{B(a, b)},\qquad p(\data \mid p) = p^{h}(1-p)^{t}

    Take the prior p∼Beta(a,b)p \sim \mathrm{Beta}(a, b), a Beta distribution, and observe hh heads and tt tails in n=h+tn = h + t independent flips of a particular sequence:

  2. p(p∣D)∝pa+h−1(1−p)b+t−1⟹p∣D∼Beta(a+h, b+t)p(p \mid \data) \propto p^{a+h-1}(1-p)^{b+t-1}\quad\Longrightarrow\quad p \mid \data \sim \mathrm{Beta}(a+h,\ b+t)

    Multiply and collect powers. The result is again a Beta kernel, so the posterior is a Beta distribution: the prior is a conjugate prior for the Bernoulli likelihood.

  3. p(D)=∫01pa+h−1(1−p)b+t−1B(a,b) dp=B(a+h, b+t)B(a,b)p(\data) = \int_0^1 \frac{p^{a+h-1}(1-p)^{b+t-1}}{B(a, b)}\,dp = \frac{B(a+h,\ b+t)}{B(a, b)}

    The normalizing constants give the evidence for free:

  4. E[p∣D]=a+ha+b+n=na+b+n⋅hn+a+ba+b+n⋅aa+b\E[p \mid \data] = \frac{a+h}{a+b+n} = \frac{n}{a+b+n}\cdot\frac{h}{n} + \frac{a+b}{a+b+n}\cdot\frac{a}{a+b}

    The posterior mean is a weighted average of the MLE and the prior mean, with weight w=n/(a+b+n)w = n/(a+b+n) on the data. That is shrinkage: the estimate is pulled toward the prior, less and less as nn grows.

  5. Var⁡[p∣D]=αβ(α+β)2(α+β+1),α=a+h,  β=b+t\Var[p \mid \data] = \frac{\alpha\beta}{(\alpha+\beta)^2(\alpha+\beta+1)},\qquad \alpha = a+h,\ \ \beta = b+t

    The posterior variance shrinks like 1/n1/n; for large nn it approaches p^(1−p^)/n\hat p(1-\hat p)/n, the squared standard error of the MLE.

Predict before you look

Prior Beta(2,2)\mathrm{Beta}(2, 2); you observe 7 heads and 3 tails. What is the posterior mean of pp?

Show the answer

0.643

The posterior is Beta(9,5)\mathrm{Beta}(9, 5), with mean 9/14≈0.6439/14 \approx 0.643: the MLE 0.70.7 with weight 10/1410/14 and the prior mean 0.50.5 with weight 4/144/14. Its mode, the MAP estimate, is 8/12≈0.6678/12 \approx 0.667, and its standard deviation is about 0.120.12: ten flips leave a lot of uncertainty.

Predicting: average over what you do not know

To predict a new observation x~\tilde x, the Bayesian answer averages the model's predictions over the posterior, the posterior predictive distribution:

p(x~∣D)=∫p(x~∣θ) p(θ∣D) dθ.p(\tilde x \mid \data) = \int p(\tilde x \mid \boldsymbol\theta)\,p(\boldsymbol\theta \mid \data)\,d\boldsymbol\theta.

For the coin, P(x~=1∣D)=E[p∣D]=(a+h)/(a+b+n)P(\tilde x = 1 \mid \data) = \E[p \mid \data] = (a+h)/(a+b+n). With the flat prior this is Laplace's rule of succession, (h+1)/(n+2)(h+1)/(n+2): after 3 heads in 3 flips it says 0.8, where the plug-in MLE says 1.

Think first After 3 heads in 3 flips with a flat prior, what is the probability that the next two flips are both heads? Is it 0.82=0.640.8^2 = 0.64?

No. The posterior is Beta(4,1)\mathrm{Beta}(4, 1) and the answer is E[p2∣D]=4⋅55⋅6=23≈0.667\E[p^2 \mid \data] = \frac{4\cdot5}{5\cdot6} = \frac23 \approx 0.667. Since E[p2]=(Ep)2+Var⁡p\E[p^2] = (\E p)^2 + \Var p, uncertainty about pp makes runs more likely than squaring the one-step prediction suggests: future flips are correlated through the shared unknown pp. The plug-in MLE would say 12=11^2 = 1.

If the loss is……the best point estimate isFor Beta(9,5)\mathrm{Beta}(9, 5)
squared error (θ^−θ)2(\hat\theta - \theta)^2the posterior mean0.6430.643
absolute error ∣θ^−θ∣\abs{\hat\theta - \theta}the posterior medianabout 0.6500.650
0–1 loss, in the limit of a vanishing tolerancethe posterior mode (MAP)0.6670.667
A posterior is a full distribution; a point estimate is a decision, and the loss decides which summary is optimal. Predictions, likewise, should usually integrate over the posterior instead of plugging in one value. For Gaussian models the predictive variance is the noise variance plus the posterior variance of the mean, so error bars widen where the parameters are uncertain (Bayesian Linear Regression).
Check your understanding

A rare-event model is fitted to 50 trials with no events. Which prediction for the next trial is more defensible, and why?

  1. The plug-in MLE, probability 0, because the data show the event never happens
  2. The posterior predictive under a flat prior, 1/52≈0.0191/52 \approx 0.019, because it averages over the event rates still compatible with the data
  3. Probability 0.5, because with no events we know nothing
  4. Neither: no prediction is possible without at least one event
Show the answer

B. The posterior predictive under a flat prior, 1/52≈0.0191/52 \approx 0.019, because it averages over the event rates still compatible with the data

The posterior is Beta(1,51)\mathrm{Beta}(1, 51) and the predictive probability is its mean, 1/521/52. Fifty clean trials make a high rate implausible, but they cannot rule out a small one. The plug-in estimate of zero would be refuted by the first event.

Credible intervals, confidence intervals and the vanishing prior

A 95% credible interval CC satisfies P(θ∈C∣D)=0.95P(\boldsymbol\theta \in C \mid \data) = 0.95: a probability statement about the parameter, given these data and the prior. The equal-tailed interval cuts 2.5% from each side of the posterior; the highest-posterior-density interval is the shortest one. A 95% confidence interval is a procedure that, over repeated samples, covers the fixed true parameter 95% of the time; for the data in hand it either covers it or not.

They can disagree sharply on small samples. With 0 heads in 10 flips, the textbook Wald interval p^±1.96p^(1−p^)/n\hat p \pm 1.96\sqrt{\hat p(1-\hat p)/n} collapses to the single point 00. The flat-prior posterior Beta(1,11)\mathrm{Beta}(1, 11) gives the equal-tailed interval (0.002,0.285)(0.002, 0.285) and the highest-density interval [0,0.238][0, 0.238], which honestly reflects that rates up to about a quarter are still plausible.

Choosing a prior

A prior is a modeling choice like the likelihood, and it plays the role a penalty plays elsewhere: a Gaussian prior on regression weights is ridge, a Beta prior adds pseudo-counts (Maximum Likelihood & MAP). Three broad kinds are used:

  • Informative priors encode real knowledge, such as earlier studies or physical constraints.
  • Weakly informative priors rule out absurd values without favoring any reasonable one. Simulating fake datasets from the prior, a prior predictive check, shows whether "vague" choices imply absurd data: a logistic-regression prior wide enough to allow odds ratios of a billion per standard deviation of a feature is not neutral.
  • Reference or "noninformative" priors aim to let the data speak. Flatness is not a neutral choice, though, because it depends on the parameterization: a flat prior on pp is a non-flat (logistic) density on the log-odds.
DerivationJeffreys' invariant prior
  1. pJ(θ)∝det⁡I(θ)p_J(\boldsymbol\theta) \propto \sqrt{\det I(\boldsymbol\theta)}

    Jeffreys (1946) proposed a prior proportional to the square root of the Fisher information determinant:

  2. Iη(η)=∣dθdη∣ Iθ(θ(η))\sqrt{I_\eta(\eta)} = \Big|\frac{d\theta}{d\eta}\Big|\,\sqrt{I_\theta(\theta(\eta))}

    Under a one-dimensional reparameterization θ=θ(η)\theta = \theta(\eta), the information transforms as Iη=(dθ/dη)2 IθI_\eta = (d\theta/d\eta)^2\,I_\theta, so Iη=∣dθ/dη∣Iθ\sqrt{I_\eta} = \abs{d\theta/d\eta}\sqrt{I_\theta}: exactly the change-of-variables rule for densities. The same rule applied in any parameterization describes the same prior beliefs.

  3. pJ(p)∝p−1/2(1−p)−1/2p_J(p) \propto p^{-1/2}(1-p)^{-1/2}

    For the coin I(p)=1/(p(1−p))I(p) = 1/(p(1-p)), so Jeffreys' prior is Beta(12,12)\mathrm{Beta}(\tfrac12, \tfrac12): half an imaginary head and half an imaginary tail, with more weight near 0 and 1 than the flat prior. It is the "Jeffreys" preset of the widgets.

Improper priors, such as a flat density on all of R\R for a location parameter, are allowed when the posterior they produce is proper, but they cannot be used to compare models through the evidence, which they define only up to an arbitrary constant (Bayesian Model Selection). And when nobody knows what prior to use for many related parameters, such as one success rate per hospital, a hierarchical model gives them a common prior whose own parameters are learned from all the groups at once.

Check your understanding

Your prior for a coin's pp is uniform on [0,0.5][0, 0.5] and zero above. The true pp is 0.70.7, and you observe 10,000 flips. What does the posterior look like?

  1. Concentrated near 0.7, because 10,000 flips overwhelm any prior
  2. Still uniform on [0,0.5][0, 0.5], because the data cannot move a uniform prior
  3. Spread evenly between 0.5 and 0.7
  4. Piled up against 0.5: it can never put mass where the prior is zero
Show the answer

D. Piled up against 0.5: it can never put mass where the prior is zero

The posterior is the prior times the likelihood, and zero times anything is zero. On [0,0.5][0, 0.5] the likelihood keeps increasing toward 0.5, so the posterior concentrates at the boundary, as close to the truth as the prior allows. Never give zero prior probability to anything you cannot rule out (sometimes called Cromwell's rule).

Key takeaways

  • Posterior ∝ likelihood × prior; the evidence p(D)=∫p(D∣θ)p(θ) dθp(\data) = \int p(\data \mid \boldsymbol\theta)p(\boldsymbol\theta)\,d\boldsymbol\theta normalizes. With conditionally independent data, yesterday's posterior is today's prior, and each piece of evidence multiplies the odds by its likelihood ratio.
  • Beta(a,b)\mathrm{Beta}(a, b) prior plus hh heads and tt tails gives Beta(a+h,b+t)\mathrm{Beta}(a+h, b+t), with evidence B(a+h,b+t)/B(a,b)B(a+h, b+t)/B(a, b) and posterior mean (a+h)/(a+b+n)(a+h)/(a+b+n), a shrinkage of the MLE toward the prior mean.
  • Predictions average over the posterior. They are less extreme than plug-in predictions and capture correlations between future observations; the optimal point estimate depends on the loss (mean, median or mode).
  • Credible intervals are probability statements about the parameter; confidence intervals are guarantees about a procedure. Under the Bernstein–von Mises conditions the posterior approaches N(θ^,(nI)−1)\mathcal N(\hat{\boldsymbol\theta}, (nI)^{-1}), the prior washes out, and the two nearly coincide.
  • Priors are modeling choices and regularizers. Flat is not neutral across parameterizations; Jeffreys' det⁡I\sqrt{\det I} is invariant (Beta(12,12)\mathrm{Beta}(\frac12, \frac12) for a coin); and zero prior mass can never be overturned by data.

Check yourself

In the interactive lesson these are scored with your confidence, and what you miss comes back for review.

Question 1

With a flat Beta(1,1)\mathrm{Beta}(1, 1) prior you observe 6 heads and 2 tails. What are the posterior and its mean?

  1. Beta(6,2)\mathrm{Beta}(6, 2), mean 0.750.75
  2. Beta(7,3)\mathrm{Beta}(7, 3), mean 0.70.7
  3. Beta(7,3)\mathrm{Beta}(7, 3), mean 0.750.75
  4. Beta(8,4)\mathrm{Beta}(8, 4), mean 0.6670.667
Show the answer

B. Beta(7,3)\mathrm{Beta}(7, 3), mean 0.70.7

Add the counts to the prior's parameters: Beta(1+6,1+2)=Beta(7,3)\mathrm{Beta}(1+6, 1+2) = \mathrm{Beta}(7, 3), with mean 7/107/10. Its mode is 6/8=0.756/8 = 0.75, the MLE, as always with a flat prior.

Question 2

With a flat prior, a coin shows 2 heads in 2 flips. What is the posterior predictive probability that the next flip is heads?

  1. 11
  2. 1/21/2
  3. 2/32/3
  4. 3/43/4
Show the answer

D. 3/43/4

The posterior is Beta(3,1)\mathrm{Beta}(3, 1), and the predictive probability is its mean, 3/43/4: Laplace's (h+1)/(n+2)(h+1)/(n+2).

Question 3

A 95% credible interval for pp is (0.62,0.78)(0.62, 0.78). Which statement is a correct reading?

  1. Given the data and the prior, pp lies in (0.62,0.78)(0.62, 0.78) with probability 0.95
  2. If the experiment were repeated many times, 95% of the estimates would fall in (0.62,0.78)(0.62, 0.78)
  3. The true pp is certainly in (0.62,0.78)(0.62, 0.78)
  4. 95% of the flips will have outcomes between 0.62 and 0.78
Show the answer

A. Given the data and the prior, pp lies in (0.62,0.78)(0.62, 0.78) with probability 0.95

A credible interval is a statement about the posterior distribution of pp. A confidence interval makes a statement about a procedure across repeated samples instead; with a flat prior and enough data the two kinds of interval nearly coincide numerically (Bernstein–von Mises), but they still answer different questions.

Question 4

Two analysts use the priors Beta(2,2)\mathrm{Beta}(2, 2) and Beta(20,20)\mathrm{Beta}(20, 20) and observe the same 10,000 flips, 5,000 of them heads. According to the Bernstein–von Mises theorem, what are their posteriors approximately?

  1. Their own priors, slightly narrowed
  2. N(0.5,0.25)\mathcal N(0.5, 0.25) for both
  3. Both approximately N(0.5, 0.0052)\mathcal N(0.5,\ 0.005^2)
  4. Different, because the second prior is ten times stronger
Show the answer

C. Both approximately N(0.5, 0.0052)\mathcal N(0.5,\ 0.005^2)

The posterior approaches N(p^,p^(1−p^)/n)\mathcal N(\hat p, \hat p(1-\hat p)/n) with p^=0.5\hat p = 0.5 and standard deviation 0.25/10,000=0.005\sqrt{0.25/10{,}000} = 0.005. The priors are worth 4 and 40 imaginary flips, against 10,000 real ones.

Go deeper

Further reading

  • A. Gelman, J. B. Carlin, H. S. Stern, D. B. Dunson, A. Vehtari & D. B. Rubin, Bayesian Data Analysis, 3rd ed. (CRC Press, 2013), chapters 1–3.
  • C. M. Bishop, Pattern Recognition and Machine Learning (Springer, 2006), section 2.1.
  • D. J. C. MacKay, Information Theory, Inference, and Learning Algorithms (Cambridge University Press, 2003), chapters 2–3.