Chapter 11: Bayesian inference

Previous: PS 10 Confidence Intervals and Hypothesis Tests | PS 00 Course Map | Next: PS 12 Markov Chains and Information

The big idea

Bayesian inference treats an unknown parameter as a random variable that describes your knowledge. You start with a prior distribution, observe data, and use Bayes’ rule to get a posterior distribution. The posterior states exactly what is still plausible and how uncertain you are, it improves smoothly as data arrives, and it gives sensible answers even with very little data. Regularization, Kalman filtering and uncertainty-aware robots all come from this one idea.

In this chapter you will learn to
  1. Write posterior ∝ likelihood × prior, and explain each part.
  2. Update a Beta prior with success/failure data, and a Gaussian prior with a measurement.
  3. Interpret the posterior mean as a weighted compromise between prior and data.
  4. Summarize a posterior with its mean, mode (MAP) and a credible interval.
  5. Show that MAP estimation with a Gaussian prior is L2-regularized maximum likelihood.
  6. Make predictions that account for parameter uncertainty, and distinguish two kinds of uncertainty.
Before you start

You need Bayes’ rule (PS 02 Conditional Probability and Bayes Rule), likelihoods and MLE (PS 09 Estimation and Maximum Likelihood), and confidence intervals (PS 10 Confidence Intervals and Hypothesis Tests) for comparison.


11.1 The Bayesian idea

Uncertainty about a parameter

In chapter 9, the parameter was a fixed unknown number and the answer was a single best guess. Here we describe our knowledge of with a probability distribution:

  • Values we consider plausible get high probability.
  • Values we consider implausible get low probability.

After seeing data, we update that distribution.

Bayes’ rule for parameters

Bayesian updating

Usually written

This is exactly Bayes’ rule from chapter 2, with the hypothesis now a continuous parameter.

PartWhat it is
prior what you believe about before the data
likelihood how probable the data is for each (chapter 9)
posterior what you believe after the data
evidence a constant that makes the posterior integrate to 1

Since the evidence does not depend on , you can usually ignore it while working out the shape of the posterior, then normalize at the end.

A picture

Plot the prior and the likelihood as curves over . Multiply them point by point. Where both are high, the posterior is high; where either is near zero, the posterior is near zero. The posterior always sits between the two, pulled toward whichever is narrower (more informative).


11.2 Estimating a success rate: the Beta-Binomial model

The prior: the Beta distribution

For an unknown probability , a convenient prior is the Beta distribution:

Beta()

Interpreting and . Think of as imaginary prior successes and as imaginary prior failures. The bigger , the more confident the prior.

PriorShapeMeaning
Beta(1,1)flatno preference: every equally plausible
Beta(2,2)gentle hump at 0.5mild belief it is near 0.5
Beta(8,2)peaked near 0.8fairly confident it is high
Beta(50,50)sharp spike at 0.5very confident it is 0.5

The update

Observe successes in trials. The likelihood is . Multiply by the prior:

Beta-Binomial update

Updating is just adding counts.

When the posterior has the same family as the prior, the prior is called conjugate. Conjugate pairs make the algebra trivial.

Worked example 11.1: very little data

Flat prior Beta(1,1). A new policy succeeds in 3 of 3 trials.

  • Posterior: Beta(4,1).
  • Posterior mean: .
  • Compare MLE: , a claim that the policy never fails.

The Bayesian answer is far more sensible. And the posterior is a full distribution: Beta(4,1) puts substantial probability on rates from about 0.4 to 1. A 95% credible interval is roughly . Three successes simply cannot tell you much.

Worked example 11.2: more data

Same flat prior, now 30 of 40 successes.

  • Posterior: Beta(31,11), mean , close to the MLE .
  • The posterior is now much narrower: its standard deviation is about .

As data accumulates, the likelihood dominates and the choice of prior matters less and less.

Sequential updating

Data can be added one batch at a time, and the result is the same as adding it all at once:

Beta(1,1) → (3 successes, 0 failures) → Beta(4,1) → (27 successes, 10 failures) → Beta(31,11).

Today’s posterior is tomorrow’s prior.


11.3 The posterior mean as a compromise

For the Beta-Binomial model,

Rewrite it:

Shrinkage

The posterior mean is a weighted average of the prior mean and the observed frequency. The weights are the amounts of evidence behind each: imaginary observations against real ones.

  • With no data, you keep the prior.
  • With little data, you are pulled toward the prior (“shrunk”).
  • With much data, you follow the data.

Worked example 11.3. Prior Beta(8,2) (mean 0.8, worth 10 observations). Data: 5 successes in 10 trials (rate 0.5).

Equal evidence on both sides, so the answer is halfway.

This shrinkage pattern recurs in every Bayesian model, and it is why Bayesian estimates are more stable than raw frequencies when data is scarce.


11.4 Gaussian prior, Gaussian measurement

The update

The unknown is a quantity (a position, say).

  • Prior: .
  • One measurement: , with known noise variance .

The posterior is Gaussian, with

Gaussian update

Reading it

Precisions add. Precision is : how much information a source carries. Combining the prior with the measurement adds their precisions. So the posterior is always more certain than either source alone.

The gain is between 0 and 1:

  • If the prior is vague ( large), : trust the measurement.
  • If the sensor is noisy ( large), : keep the prior.

The update moves the estimate from the prior mean toward the measurement, by times the surprise .

This is precisely the Gaussian conditioning formula of PS 07 The Multivariate Gaussian in one dimension, and it is the measurement update of the Kalman filter, with the Kalman gain.

Worked example 11.4

A robot believes its position is m (prior variance 4). A sensor reads m with noise variance 1.

  • .
  • m.
  • , so m.

The sensor is more precise than the prior, so the estimate moves most of the way to the reading, and the uncertainty drops below both 4 and 1.

Several measurements

With independent measurements, each of variance , precisions keep adding:

With a vague prior, this gives : the square-root law again (PS 04 Expectation and Variance).


11.5 Summarizing a posterior

A posterior is a whole distribution. Common summaries:

SummaryDefinitionBest when
posterior meanyou are scored by squared error
posterior medianmiddle of the posterioryou are scored by absolute error
MAP (maximum a posteriori)the peak (mode)you want one most-plausible value
credible intervala range holding, say, 95% of the posterioryou want to state uncertainty
Credible interval

A 95% credible interval satisfies .

This does mean what people often wrongly think a confidence interval means: “given the data (and my prior), there is a 95% probability that lies in this range.” The price of that direct interpretation is that it depends on the prior.


11.6 MAP is regularized maximum likelihood

The MAP estimate maximizes the posterior, or equivalently its logarithm:

Now choose a Gaussian prior on the parameters, . Its log is . Negating to get a loss:

Priors are regularizers

L2 regularization (weight decay) is a Gaussian prior that says “parameters are probably small”.

  • A tighter prior (small ) means a stronger penalty (large ).
  • A Laplace prior gives an L1 penalty, which pushes many parameters to exactly zero.
  • A flat prior gives no penalty: MAP becomes MLE.

So regularization is not an arbitrary trick. Each regularizer is a stated belief about the parameters.


11.7 Prediction: averaging over uncertainty

To predict a new observation, do not plug in a single best . Average the prediction over everything you still believe is plausible:

Posterior predictive distribution

Worked example 11.5. After 3 successes in 3 trials with a flat prior, what is the probability that the next trial succeeds?

Not 1, which is what plugging in the MLE would give. This is Laplace’s rule of succession: after successes in trials, predict .

Plugging in one value ignores parameter uncertainty and produces overconfident predictions. Averaging keeps that uncertainty, which matters most exactly when data is scarce.


11.8 Two kinds of uncertainty

AleatoricEpistemic
sourcerandomness in the worldlack of knowledge
examplea fair coin; sensor noisea policy never tested in the dark
does more data reduce it?noyes
measured bythe likelihood’s spreadthe posterior’s spread

A robot should respond to them differently:

  • High epistemic uncertainty: “I have not seen this situation before.” Act cautiously, ask for help, or gather data.
  • High aleatoric uncertainty: “This is as predictable as it gets.” More data will not help; plan for the variability.

Ensembles of networks and Bayesian neural networks try to estimate epistemic uncertainty; disagreement between ensemble members signals unfamiliar inputs (16 Evaluation and Uncertainty).


11.9 Frequentist and Bayesian, side by side

FrequentistBayesian
parameterfixed, unknownrandom variable describing knowledge
answerpoint estimate and confidence intervalposterior distribution
prior knowledgenot used formallyencoded in the prior
interval meaningthe procedure covers the truth 95% of the time95% probability given data and prior
weak pointindirect interpretationanswers depend on the prior when data is scarce

With plenty of data the two approaches give nearly identical numbers. They differ when data is scarce, which is exactly when the choice of prior must be made carefully and stated openly.


Summary

IdeaFormula or fact
Bayes for parametersposterior ∝ likelihood × prior
Beta-BinomialBeta() → Beta(, )
posterior meanweighted average of prior mean and data
Gaussian updateprecisions add;
MAP with Gaussian priorMLE + L2 penalty
predictionaverage over the posterior
credible interval95% posterior probability

Three facts to remember:

  1. Posterior ∝ likelihood × prior; today’s posterior is tomorrow’s prior.
  2. With little data you shrink toward the prior; with much data you follow the data.
  3. Every regularizer is a prior; every Kalman update is a Bayesian update.

Exercises

Part A: warm-up

A1. Prior Beta(2,2). Observe 7 successes in 10 trials. Give the posterior and its mean.

A2. With a flat prior, a new gripper succeeds in 0 of 5 trials. Give the posterior mean. What does the MLE say?

A3. Prior . One measurement with noise variance 1. Find the posterior mean and variance.

A4. Which prior gives stronger weight decay: or ?

Part B: core

B1. Two policies, flat priors. A: 9/10 successes. B: 45/50 successes. Both have MLE 0.9. Give each posterior, mean and standard deviation. Which estimate are you more confident in? (Beta() has variance .)

B2. A robot’s prior on its -position is . Two independent sensors read (variance ) and (variance ). Find the posterior mean and variance, processing them one after the other. Check that the order does not matter.

B3. You believe a sensor’s bias is near zero, prior . Ten readings of a known zero signal average , each with noise variance . Find the posterior on the bias.

B4. Show that with prior Beta(), the posterior mean always lies between the prior mean and the observed rate .

B5. A colleague reports “the success rate is 100%” after 4 trials. Using the rule of succession and a credible interval idea, write a one-paragraph reply.

Part C: explain and prove

C1. Show that sequential updating (Beta(1,1) with 3/3, then 27/37) gives the same posterior as updating once with 30/40.

C2. Explain why MAP with a flat prior equals MLE.

C3. Explain the difference between a 95% confidence interval and a 95% credible interval in two sentences each.

C4. Explain why ensembles of networks that disagree on an input suggest epistemic, not aleatoric, uncertainty.

Part D: practise with code

D1. Plot the Beta posterior after 0, 1, 5, 20 and 100 trials of a simulated policy with true rate 0.7, starting from a flat prior. Watch it sharpen around 0.7.

D2. Compute a 95% credible interval for Beta(4,1) with scipy.stats.beta.ppf([0.025, 0.975], 4, 1).

D3. Implement the 1-D Kalman measurement update and run it on 50 noisy readings of a fixed position, starting from a vague prior. Plot the estimate and its band over time.

D4. Fit ridge regression for several values to 15 noisy points with a degree-9 polynomial. Plot the fits. Relate to the prior width .


Where this is used

Next: PS 12 Markov Chains and Information: sequences, long-run behaviour, and measuring surprise.