Course contents 01 / 15

01 / 15 · Bayesian Modelling

The Bayesian approach

Keep a distribution over everything unknown and predict by averaging over it: two readings of probability, Bayesian reasoning with numbers, what a point estimate loses, models as graphs, and the plan of the course.

On this page 8

Eleven urns are labelled u=0,1,…,10u = 0, 1, \dots, 10; urn uu holds uu black balls and 10−u10 - u white ones. Someone picks an urn at random, draws N=10N = 10 balls with replacement, and sees nB=3n_B = 3 black ones. What is the probability that the next ball is black? The problem is from MacKay (2003, Section 2.3).

The working method of the Machine Learning course answers in two steps. First fit the parameter by maximum likelihood: urn uu has the fraction fu=u/10f_u = u/10 of black balls, its likelihood fu3(1−fu)7f_u^{3}(1 - f_u)^{7} is largest at u=3u = 3, because the derivative of 3ln⁡f+7ln⁡(1−f)3 \ln f + 7 \ln(1 - f), which is 3/f−7/(1−f)3/f - 7/(1 - f), vanishes at f=0.3f = 0.3. So the fitted urn is urn 3. Then plug it in: the next ball is black with probability f3=0.3f_3 = 0.3.

The answer ignores that urns 2 and 4 explain the data almost as well. With less data the defect becomes an error. After three draws, all white, maximum likelihood picks urn 0 and states that a black ball is impossible.

The Bayesian inference note of the probability course showed the alternative for a single coin: keep a distribution over the parameter, update it with the data, and predict by averaging over it. This course builds machine learning models that way. A model is assembled from a few standard distributions, everything unknown in it receives a distribution, and learning is the computation of the posterior.

Two readings of probability#

The rules of probability, the sum and product rules and Bayes’ formula, are the same in both readings. What differs is what a probability is about, and therefore which quantities may carry one.

In the frequentist reading, a probability is the long-run frequency of an outcome in a repeatable experiment. A parameter, such as a coin’s probability of heads, is a fixed unknown number. It has no distribution, and statements about it are statements about procedures: a 95% confidence interval is a rule that covers the true value in 95% of repeated samples.

In the Bayesian reading, a probability is a degree of belief in a statement, given the information at hand. Nothing needs to be repeatable. “This email is spam” and “the third weight of this network is positive” each have a probability once we state what we know. A coin toss is random in this sense too: with the exact impulse, mass and air resistance it could be computed, and it is uncertain only because we do not know them. Every unknown quantity, a parameter included, may then carry a distribution.

The same event can then have different probabilities for different observers. A commuter who has taken the 10:30 bus for months knows that it arrives within about seven minutes of the timetable; a passenger whose app tracks the bus knows the arrival to within about three. Both describe one arrival by distributions of different widths, because they know different things. Some randomness may be irreducible, as in radioactive decay, but the Bayesian reading does not have to decide which.

FrequentistBayesian
A probability isa long-run frequencya degree of belief, given information
A parameter θ\theta isa fixed unknown constanta random variable with a prior
Inference returnsan estimate θ^\hat\theta and its sampling behaviourthe posterior p(θ∣X)p(\theta \mid X)
Typical methodmaximum likelihood, confidence intervalsBayes’ formula, credible intervals, predictive averages
When it is justifiedexactly for some models, asymptotically in generalcoherent for any nn, if the model and the prior are right

The last row needs care. Some frequentist procedures are exact at every sample size. For normal data the t-interval covers the mean in exactly 95% of samples. The Clopper–Pearson interval for a binomial proportion keeps every value p0p_0 that neither one-sided binomial test of p=p0p = p_0 at level 2.5% rejects. The true value is then excluded only when one of the two tests rejects it, which has probability at most 5% for every nn (Clopper and Pearson, 1934). Bayes’ formula, for its part, makes small-sample answers consistent with the model and the prior, not more accurate: they are only as good as the model and the prior.

The row still matters for machine learning. A deep network or a topic model has more parameters than any sample can pin down, so the asymptotic arguments behind maximum likelihood do not apply, while Bayes’ formula applies to any sample size, even zero, where the posterior is the prior. As the sample grows with the model fixed, the posterior concentrates at the maximum likelihood estimate, by the Bernstein–von Mises theorem under its regularity conditions, and the two readings give the same answers. The price of the Bayesian reading is a prior, which must be chosen and defended, and an integral, which must be computed.

Why beliefs obey the rules of probability#

Optional depth: two arguments for treating degrees of belief as probabilities. The rest of the note does not depend on it.

Why should degrees of belief add up and multiply like frequencies? R. T. Cox showed in 1946 that if beliefs are real numbers that agree with ordinary logic when statements are certain, and satisfy a few consistency requirements, then they can be rescaled into numbers that obey the sum and product rules (MacKay, 2003, Section 2.2; Bishop, 2006, Section 1.2.3). Probability is then an extension of Boolean logic to uncertain statements. The full derivation of both rules from these requirements is in Jaynes (2003, Chapter 2).

A second argument uses bets. Suppose someone prices a bet that pays 1 if AA happens at 0.6, and a bet that pays 1 if AA does not happen also at 0.6, so that their beliefs sum to 1.2. A bookmaker sells them both bets for 1.2. Exactly one bet pays 1, so they lose 0.2 whatever happens. Any prices that break the axioms of probability for finitely many events admit such a set of bets with a sure loss, and prices that obey them do not: de Finetti’s Dutch book theorem (Vineberg, 2022, Sections 1.1 and 1.3).

Bayesian reasoning with numbers#

Which urn?#

Give each urn the prior probability 1/111/11. The draws are independent given the urn, so by the product rule a particular sequence with nBn_B black balls among NN has probability fu nB(1−fu)N−nBf_u^{\,n_B} (1 - f_u)^{N - n_B} under urn uu. Bayes’ formula over the eleven hypotheses, with the sum rule in the denominator, gives

p(u∣nB,N)=fu nB(1−fu)N−nB∑v=010fv nB(1−fv)N−nB,p(u \mid n_B, N) = \frac{f_u^{\,n_B} (1 - f_u)^{N - n_B}}{\sum_{v=0}^{10} f_v^{\,n_B} (1 - f_v)^{N - n_B}} ,

where the equal priors 1/111/11 cancel between the numerator and every term of the denominator. For nB=3n_B = 3 in N=10N = 10:

Urn uu12345678
p(u∣nB,N)p(u \mid n_B, N)0.0630.2210.2930.2360.1290.0470.0100.001

Urns 0, 9 and 10 are ruled out or nearly so. Urn 3 is the most probable, but it holds less than a third of the posterior mass.

The probability that the next ball is black follows in three steps. Write DD for the draws seen so far:

p(black∣D)=∑u=010p(black,u∣D)(sum rule)=∑u=010p(black∣u,D) p(u∣D)(product rule)=∑u=010fu p(u∣D)(draws independent given u)=0.333.\begin{aligned} p(\text{black} \mid D) &= \sum_{u=0}^{10} p(\text{black}, u \mid D) && \text{(sum rule)} \\ &= \sum_{u=0}^{10} p(\text{black} \mid u, D)\, p(u \mid D) && \text{(product rule)} \\ &= \sum_{u=0}^{10} f_u\, p(u \mid D) && \text{(draws independent given } u) \\ &= 0.333 . \end{aligned}

The first two lines are the law of total probability applied given DD. The third holds because, once the urn is known, the earlier draws say nothing more about the next one.

This is the value MacKay reports, against 0.30.3 for the plug-in. The Bayesian answer is larger because the posterior is skewed: urns with more black balls than urn 3 keep more mass than urns with fewer.

Figure

The posterior over the urns and the prediction

The posterior over the urns and the predictionTwo bar charts of the probabilities of urns 0 to 10. Left, after 3 black in 10 draws, a peak at urn 3 (0.293) with mass spread over urns 1 to 7; the prediction is 0.333 against 0.3 for the plug-in. Right, after 0 black in 3 draws, probabilities fall from 0.331 at urn 0; the prediction is 0.163 against 0 for the plug-in.3 black in 10 draws00.10.20.3012345678910urn u (u black balls of 10)P(next ball black):plug-in (urn 3): 0.300posterior average: 0.3330 black in 3 draws00.10.20.3012345678910urn u (u black balls of 10)P(next ball black):plug-in (urn 0): 0posterior average: 0.163The posterior over the urns and the predictionTwo bar charts of the probabilities of urns 0 to 10. Left, after 3 black in 10 draws, a peak at urn 3 (0.293) with mass spread over urns 1 to 7; the prediction is 0.333 against 0.3 for the plug-in. Right, after 0 black in 3 draws, probabilities fall from 0.331 at urn 0; the prediction is 0.163 against 0 for the plug-in.3 black in 10 draws00.10.20.3012345678910urn u (u black balls of 10)P(next ball black):plug-in (urn 3): 0.300posterior average: 0.3330 black in 3 draws00.10.20.3012345678910urn u (u black balls of 10)P(next ball black):plug-in (urn 0): 0posterior average: 0.163
Posterior probabilities of the eleven urns under a uniform prior; the urn of highest likelihood is amber. Left, after 3 black in 10 draws: the plug-in predicts black with probability 0.3, the posterior average 0.333. Right, after 3 white draws: the plug-in says 0, the average 0.163.

A coin with an unknown bias#

Replace the eleven urns by a continuum: a coin whose probability of heads ff can be any number in [0,1][0, 1], with a uniform prior. The posterior after nBn_B heads in NN flips is Beta(1+nB, 1+N−nB)\mathrm{Beta}(1 + n_B,\ 1 + N - n_B), the conjugate update of the probability course. For 3 heads in 10 it is Beta(4,8)\mathrm{Beta}(4, 8). The same three steps with an integral over ff give p(heads∣D)=∫01f p(f∣D) dfp(\text{heads} \mid D) = \int_0^1 f\, p(f \mid D)\, df, the posterior mean, and a Beta(a,b)\mathrm{Beta}(a, b) distribution has mean a/(a+b)a/(a + b) (Bayesian inference note):

nB+1N+2=412=0.333,\frac{n_B + 1}{N + 2} = \frac{4}{12} = 0.333 ,

Laplace’s rule of succession. The urns were a grid of eleven values of ff, and the grid already gives the continuous answer to three digits.

For three white balls in three draws, the urn posterior is 0.331,0.241,0.169,0.113,…0.331, 0.241, 0.169, 0.113, \dots for u=0,1,2,3,…u = 0, 1, 2, 3, \dots, and the probability that the next ball is black is 0.1630.163: small, but not zero. A model that predicted 0 and then saw a black ball would pay an infinite log loss. The predictive pays −ln⁡0.163=1.82-\ln 0.163 = 1.82 nats.

Sequential updating#

Data that arrive in batches can be processed one batch at a time. Split the ten urn draws into X1X_1, the first five (two black), and X2X_2, the last five (one black). We want the posterior after both batches written through p(θ∣X1)p(\theta \mid X_1), the posterior we already hold after the first.

The tool is Bayes’ formula with an extra condition xx that stays to the right of every bar:

p(y∣x,z)=p(z∣x,y) p(y∣x)p(z∣x).p(y \mid x, z) = \frac{p(z \mid x, y)\, p(y \mid x)}{p(z \mid x)} .

It is the ordinary formula inside the world where xx is known, and the denominator is again the sum rule followed by the product rule.

Derivation

It follows in two ways. First, apply the definition of a conditional distribution, then the product rule to the numerator and to the denominator, and cancel p(x)p(x):

p(y∣x,z)=p(x,y,z)p(x,z)(definition)=p(z∣x,y) p(y∣x) p(x)p(z∣x) p(x)(product rule).\begin{aligned} p(y \mid x, z) &= \frac{p(x, y, z)}{p(x, z)} && \text{(definition)} \\ &= \frac{p(z \mid x, y)\, p(y \mid x)\, p(x)}{p(z \mid x)\, p(x)} && \text{(product rule)} . \end{aligned}

Second, for a fixed xx the function p(⋅∣x)p(\cdot \mid x) is itself a probability distribution, so it obeys the sum and product rules and hence Bayes’ formula; conditioning everything on xx changes no step. The denominator comes from the sum rule and then the product rule, both given xx:

p(z∣x)=∫p(z,y∣x) dy=∫p(z∣x,y) p(y∣x) dy.\begin{aligned} p(z \mid x) &= \int p(z, y \mid x)\, dy \\ &= \int p(z \mid x, y)\, p(y \mid x)\, dy . \end{aligned}

If zz is independent of xx given yy, the first factor is p(z∣y)p(z \mid y), and p(z∣x)=∫p(z∣y) p(y∣x) dyp(z \mid x) = \int p(z \mid y)\, p(y \mid x)\, dy: the form used next.

Now set y=θy = \theta, x=X1x = X_1, z=X2z = X_2, and assume the batches are independent given θ\theta, so that p(X2∣θ,X1)=p(X2∣θ)p(X_2 \mid \theta, X_1) = p(X_2 \mid \theta). Then

p(θ∣X1,X2)=p(X2∣θ,X1) p(θ∣X1)p(X2∣X1)(Bayes given X1)=p(X2∣θ) p(θ∣X1)p(X2∣X1)(independence given θ),\begin{aligned} p(\theta \mid X_1, X_2) &= \frac{p(X_2 \mid \theta, X_1)\, p(\theta \mid X_1)}{p(X_2 \mid X_1)} && \text{(Bayes given } X_1) \\ &= \frac{p(X_2 \mid \theta)\, p(\theta \mid X_1)}{p(X_2 \mid X_1)} && \text{(independence given } \theta), \end{aligned}

and the normalizer follows from the sum and product rules given X1X_1 and the same independence:

p(X2∣X1)=∫p(X2∣θ) p(θ∣X1) dθ.p(X_2 \mid X_1) = \int p(X_2 \mid \theta)\, p(\theta \mid X_1)\, d\theta .

Together:

  p(θ∣X1,X2)=p(X2∣θ) p(θ∣X1)∫p(X2∣θ) p(θ∣X1) dθ  \boxed{\;p(\theta \mid X_1, X_2) = \frac{p(X_2 \mid \theta)\, p(\theta \mid X_1)}{\int p(X_2 \mid \theta)\, p(\theta \mid X_1)\, d\theta}\;}

Each piece has a role. The posterior after the first batch, p(θ∣X1)p(\theta \mid X_1), plays the prior. The likelihood is that of the second batch alone. The normalizer p(X2∣X1)p(X_2 \mid X_1) is the predictive probability of the second batch given the first, the same average over the posterior as for the next ball above. For the urns it is a sum over the eleven urns and equals 0.04550.0455; the evidence of the first batch is p(X1)=0.01515p(X_1) = 0.01515, and their product 0.0006890.000689 is p(X1,X2)p(X_1, X_2), the evidence of all ten draws, as the product rule requires.

The split does not matter. Substitute Bayes’ formula for p(θ∣X1)p(\theta \mid X_1) and the product rule p(X2∣X1)=p(X1,X2)/p(X1)p(X_2 \mid X_1) = p(X_1, X_2) / p(X_1); the factor p(X1)p(X_1) cancels:

p(θ∣X1,X2)=p(X2∣θ) p(X1∣θ) p(θ)p(X1,X2)(substitution)=p(X1,X2∣θ) p(θ)p(X1,X2)(independence given θ).\begin{aligned} p(\theta \mid X_1, X_2) &= \frac{p(X_2 \mid \theta)\, p(X_1 \mid \theta)\, p(\theta)}{p(X_1, X_2)} && \text{(substitution)} \\ &= \frac{p(X_1, X_2 \mid \theta)\, p(\theta)}{p(X_1, X_2)} && \text{(independence given } \theta) . \end{aligned}

This is the posterior from all the data at once. It is symmetric in X1X_1 and X2X_2, so neither the split nor the order of the batches changes it.

The Code section updates the urn posterior one ball at a time and recovers the batch answer to 10−1210^{-12}. Nothing but the posterior has to be stored between batches, which is why Bayesian learning suits streaming data; stochastic variational inference scales this idea to millions of documents.

Prior, likelihood, posterior and predictive#

Write X=(x1,…,xn)X = (x_1, \dots, x_n) for the observed data and θ\theta for the unknown parameters. The general scheme has four objects. The prior p(θ)p(\theta) states what is believed before the data. The likelihood p(X∣θ)p(X \mid \theta) states how the data are generated for each value of the parameter. Bayes’ formula combines them into the posterior:

p(θ∣X)=p(X∣θ) p(θ)p(X),p(X)=∫p(X∣θ) p(θ) dθ.\begin{aligned} p(\theta \mid X) &= \frac{p(X \mid \theta)\, p(\theta)}{p(X)}, \\ p(X) &= \int p(X \mid \theta)\, p(\theta)\, d\theta . \end{aligned}

The normalizer p(X)p(X) is the evidence, or marginal likelihood; its integral is the sum rule over θ\theta followed by the product rule p(X,θ)=p(X∣θ) p(θ)p(X, \theta) = p(X \mid \theta)\, p(\theta). The probability course wrote the prior as π(θ)\pi(\theta); this course writes p(⋅)p(\cdot) for every density and lets the argument say which one is meant.

The posterior and the joint differ only by that normalizer: p(θ,X)=p(θ∣X) p(X)p(\theta, X) = p(\theta \mid X)\, p(X), and p(X)p(X) does not depend on θ\theta. As functions of θ\theta they have the same shape and the same maximum, but only the posterior integrates to 1 over θ\theta; the joint integrates to p(X)p(X). “Posterior = likelihood × prior” is therefore true only up to that constant, p(θ∣X)∝p(X∣θ) p(θ)p(\theta \mid X) \propto p(X \mid \theta)\, p(\theta). For three black balls in ten draws, the joint p(u,X)=p(X∣u)/11p(u, X) = p(X \mid u)/11 sums over the urns to p(X)=0.000689p(X) = 0.000689. Its largest value, 0.0002020.000202, is at urn 3, as is the largest posterior probability, 0.000202/0.000689=0.2930.000202/0.000689 = 0.293.

The answer to a question about new data is the predictive distribution, the model’s predictions averaged over the posterior. It comes from the three steps used for the next ball:

p(x∗∣X)=∫p(x∗,θ∣X) dθ(sum rule)=∫p(x∗∣θ,X) p(θ∣X) dθ(product rule)=∫p(x∗∣θ) p(θ∣X) dθ.\begin{aligned} p(x_* \mid X) &= \int p(x_*, \theta \mid X)\, d\theta && \text{(sum rule)} \\ &= \int p(x_* \mid \theta, X)\, p(\theta \mid X)\, d\theta && \text{(product rule)} \\ &= \int p(x_* \mid \theta)\, p(\theta \mid X)\, d\theta . \end{aligned}

The last line assumes that new and old data are independent given θ\theta.

For a supervised model with inputs XX, targets T=(t1,…,tn)T = (t_1, \dots, t_n) and weights ww, the model states that the targets are independent given the inputs and the weights, so the likelihood is p(T∣X,w)=∏ip(ti∣xi,w)p(T \mid X, w) = \prod_i p(t_i \mid x_i, w). The posterior is over the weights. The same three steps give the prediction for a new input x∗x_*, with two modelling assumptions: t∗t_* depends on the data only through ww, and the new input alone says nothing about ww, so that p(w∣x∗,X,T)=p(w∣X,T)p(w \mid x_*, X, T) = p(w \mid X, T):

p(t∗∣x∗,X,T)=∫p(t∗∣x∗,w) p(w∣X,T) dw.p(t_* \mid x_*, X, T) = \int p(t_* \mid x_*, w)\, p(w \mid X, T)\, dw .

This is a vote of all the models the weights describe, each weighted by its posterior probability.

Every step after writing the model is an integral. The evidence does not change the shape of the posterior, but it is the quantity by which whole models are compared. For a few prior–likelihood pairs, the conjugate pairs, these integrals have closed forms. For the rest, the course builds approximations.

What a point estimate throws away#

Write θ^\hat\theta for a point estimate, maximum likelihood or MAP:

θ^ML=arg⁡max⁡θ p(X∣θ),θ^MAP=arg⁡max⁡θ p(X∣θ) p(θ).\begin{aligned} \hat\theta_{\text{ML}} &= \arg\max_\theta\, p(X \mid \theta), \\ \hat\theta_{\text{MAP}} &= \arg\max_\theta\, p(X \mid \theta)\, p(\theta) . \end{aligned}

The MAP line drops p(X)p(X) from Bayes’ formula because it does not depend on θ\theta and so does not move the maximum. For i.i.d. data the likelihood is a product over the points, the logarithm turns it into a sum, and the prior enters once for the whole dataset:

θ^MAP=arg⁡max⁡θ(∑i=1nlog⁡p(xi∣θ)+log⁡p(θ)).\hat\theta_{\text{MAP}} = \arg\max_\theta \Big(\sum_{i=1}^n \log p(x_i \mid \theta) + \log p(\theta)\Big) .

Writing ∏ip(xi∣θ) p(θ)\prod_i p(x_i \mid \theta)\, p(\theta) with the prior inside the product would count it nn times, as if the prior were p(θ)np(\theta)^n. For a Gaussian prior N(0,α−1I)\mathcal N(0, \alpha^{-1} I) that multiplies the ridge penalty α2∥θ∥2\frac\alpha2 \lVert\theta\rVert^2 by nn, because (e−α∥θ∥2/2)n=e−nα∥θ∥2/2\big(e^{-\alpha\lVert\theta\rVert^2/2}\big)^n = e^{-n\alpha\lVert\theta\rVert^2/2}.

Using a point estimate replaces the posterior by a spike at one value, p(θ∣X)≈δ(θ−θ^)p(\theta \mid X) \approx \delta(\theta - \hat\theta). Inside the predictive integral the delta function picks out the value of the integrand at θ^\hat\theta, and the predictive becomes the plug-in p(x∗∣θ^)p(x_* \mid \hat\theta). The approximation is good when the posterior is a narrow peak, the large-sample regime of the Bernstein–von Mises theorem. Away from that regime, several things are lost.

The first is uncertainty. After three white draws, ML and MAP with the uniform prior both pick urn 0 and predict black with probability 0, where the predictive says 0.1630.163. A point estimate cannot say how much the data constrained the parameter. The predictive is also wider than any single model’s prediction: for a normal mean, its variance is the noise variance plus the posterior variance of the mean (Bayesian inference note), and a plug-in keeps only the first.

The second is the choice of summary. The best single number depends on the loss it will be judged by: the posterior mean minimizes the expected squared error, the median the expected absolute error, and the mode the expected 0–1 loss (derivation below). After three white draws, the mode, median and mean of the fraction fuf_u are 00, 0.10.1 and 0.1630.163, three answers from one posterior.

Derivation

Let aa be the reported number and m=E[θ∣X]m = \mathbb E[\theta \mid X]. For squared error, add and subtract mm inside the square; the cross term has posterior mean zero:

E[(θ−a)2∣X]=Var⁡(θ∣X)+(m−a)2,\mathbb E\big[(\theta - a)^2 \mid X\big] = \operatorname{Var}(\theta \mid X) + (m - a)^2 ,

smallest at a=ma = m. For absolute error, the derivative of ∣θ−a∣\lvert \theta - a \rvert in aa is +1+1 when θ<a\theta < a and −1-1 when θ>a\theta > a, so the derivative of the expected loss is P(θ<a∣X)−P(θ>a∣X)P(\theta < a \mid X) - P(\theta > a \mid X). It vanishes where both probabilities are 1/21/2: at the median. For a discrete θ\theta, as for the urns, the 0–1 loss has expectation 1−P(θ=a∣X)1 - P(\theta = a \mid X), smallest at the most probable value. For a continuous θ\theta, a loss of 1 outside a window ∣θ−a∣<ε\lvert \theta - a \rvert < \varepsilon has expectation about 1−2ε p(a∣X)1 - 2\varepsilon\, p(a \mid X) for small ε\varepsilon, smallest at the mode.

The MAP estimate also changes under a reparametrization of θ\theta, while the posterior does not (Bayesian inference note). The reason is the change-of-variables rule: for ϕ=g(θ)\phi = g(\theta) the density of ϕ\phi is that of θ\theta times ∣dθ/dϕ∣\lvert d\theta / d\phi \rvert, a factor that varies with ϕ\phi and so moves the maximum, while probabilities of events are carried over unchanged.

The third is the shape. A posterior with several modes, such as that of a mixture whose components can be relabelled, is represented by one of them. Even the highest point can mislead. Take the density 0.9 N(0,1)+0.1 N(4,0.012)0.9\, \mathcal N(0, 1) + 0.1\, \mathcal N(4, 0.01^2). Its mode is at 4, the top of a needle that holds a tenth of the mass, with height 0.1/(0.012π)=3.990.1/(0.01\sqrt{2\pi}) = 3.99. The other nine tenths lie in the broad bump around 0, of height only 0.9/2π=0.3590.9/\sqrt{2\pi} = 0.359. A MAP estimate reports 4, a value near which almost nothing is likely.

The fourth is the combination of sources. By sequential updating, the posterior from one dataset is the prior for the next, and the result is the posterior of both. A point estimate cannot be passed on this way. As a prior it would be a point mass at θ^\hat\theta, and since the posterior is the prior times the likelihood, it would be zero wherever the prior is: no new data could move it.

The last is a way to compare models. The best-fit likelihood p(X∣θ^)p(X \mid \hat\theta) never decreases as a model grows: a larger model contains the smaller one as a special case, and a maximum over a larger set cannot be smaller. So it always prefers the largest model. The evidence, an integral over all parameter values, does not.

MAP estimation, sometimes called poor man’s Bayes, is still the workhorse of practice, and ridge regression and weight decay are MAP estimates. The Bayesian approach does not forbid them. It says what they approximate, so that we know when the approximation is safe.

A model is a graph of standard blocks#

Realistic models have many unknowns: parameters, hyperparameters that control the priors, and latent variables, one per observation, such as the cluster of a point in a Gaussian mixture. Writing their joint distribution directly is hopeless. A Bayesian network, or directed graphical model, writes it as a product of small conditional distributions, one per variable given its parents pa(vj)\mathrm{pa}(v_j) in a directed acyclic graph. Number the variables so that parents come before children. The product rule gives p(v1,…,vm)=∏jp(vj∣v1,…,vj−1)p(v_1, \dots, v_m) = \prod_j p(v_j \mid v_1, \dots, v_{j-1}) for any joint distribution, and the network is the assumption, by definition, that each factor depends on its parents only:

p(v1,…,vm)=∏j=1mp(vj∣pa(vj)).p(v_1, \dots, v_m) = \prod_{j=1}^m p(v_j \mid \mathrm{pa}(v_j)) .

Each factor is a standard block: a Bernoulli or categorical choice, a Gaussian whose mean is a linear function of its parents, a gamma distribution for a precision, a beta or Dirichlet distribution for probabilities. A repeated block, such as nn observations that share a parameter, is drawn once inside a box, a plate, with nn in its corner. Observed variables are shaded.

Inference is always the same operation: condition on the shaded variables and marginalize the ones that are not asked about. The definition of a conditional distribution gives the ratio p(query,obs)/p(obs)p(\text{query}, \text{obs}) / p(\text{obs}), and the sum rule, applied to the numerator and the denominator, brings both back to the joint:

p(query∣obs)=∑restp(query,rest,obs)∑query,restp(query,rest,obs),p(\text{query} \mid \text{obs}) = \frac{\sum_{\text{rest}} p(\text{query}, \text{rest}, \text{obs})}{\sum_{\text{query}, \text{rest}} p(\text{query}, \text{rest}, \text{obs})} ,

with sums replaced by integrals for continuous variables. Parameters are just more unobserved nodes, which is why the Bayesian approach needs no separate theory for them.

Explaining away: a worked example#

A house has a burglar alarm, a classic example that Vetrov and Kropotov’s first lecture also works through. A burglary BB and an earthquake EE happen independently, with P(B=1)=0.01P(B = 1) = 0.01 and P(E=1)=0.02P(E = 1) = 0.02. Either can set off the alarm AA, and the radio RR reports earthquakes. The graph has arrows B→AB \to A, E→AE \to A and E→RE \to R, and the joint distribution is p(b) p(e) p(a∣b,e) p(r∣e)p(b)\, p(e)\, p(a \mid b, e)\, p(r \mid e) with these tables:

b=0,e=0b = 0, e = 0b=0,e=1b = 0, e = 1b=1,e=0b = 1, e = 0b=1,e=1b = 1, e = 1
P(A=1∣b,e)P(A = 1 \mid b, e)0.0010.0010.30.30.90.90.950.95

and P(R=1∣E=1)=0.8P(R = 1 \mid E = 1) = 0.8, P(R=1∣E=0)=0.001P(R = 1 \mid E = 0) = 0.001.

Figure

The burglar alarm network: explaining away

The burglar alarm network: explaining awayA graph of four nodes: burglary and earthquake point to the alarm, earthquake also points to the radio report. On the right, the probabilities of a burglary and an earthquake: 0.010 and 0.020 with no evidence, 0.566 and 0.385 after the alarm, 0.033 and 0.998 after the radio report.burglary BP(B = 1) = 0.01earthquake EP(E = 1) = 0.02alarm AP(A | B, E)radio RP(R | E)observedobserved1no evidenceP(B) = 0.010 P(E) = 0.0202the alarm ringsP(B | A) = 0.566 P(E | A) = 0.3853the radio reports a quakeP(B | A, R) = 0.033 P(E | A, R) = 0.998The burglar alarm network: explaining awayA graph of four nodes: burglary and earthquake point to the alarm, earthquake also points to the radio report. On the right, the probabilities of a burglary and an earthquake: 0.010 and 0.020 with no evidence, 0.566 and 0.385 after the alarm, 0.033 and 0.998 after the radio report.burglary BP(B = 1) = 0.01earthquake EP(E = 1) = 0.02alarm AP(A | B, E)radio RP(R | E)observedobserved1no evidenceP(B) = 0.010P(E) = 0.0202the alarm ringsP(B | A) = 0.566P(E | A) = 0.3853the radio reports a quakeP(B | A, R) = 0.033P(E | A, R) = 0.998
Burglary B (P = 0.01) and earthquake E (P = 0.02) are independent causes of the alarm A; the radio R reports earthquakes. Observed nodes are green. Step 2: the alarm raises P(B) from 0.010 to 0.566. Step 3: the radio report makes the earthquake almost certain, and P(B) falls to 0.033.

When the alarm rings, we first marginalize the earthquake out of the alarm’s table, by the sum and product rules with P(e∣b)=P(e)P(e \mid b) = P(e) since BB and EE are independent, then apply Bayes’ formula:

P(A=1∣B=1)=0.98⋅0.9+0.02⋅0.95=0.901,P(A=1∣B=0)=0.98⋅0.001+0.02⋅0.3=0.00698,P(B=1∣A=1)=0.901⋅0.010.901⋅0.01+0.00698⋅0.99=0.566.\begin{aligned} P(A = 1 \mid B = 1) &= 0.98 \cdot 0.9 + 0.02 \cdot 0.95 = 0.901, \\ P(A = 1 \mid B = 0) &= 0.98 \cdot 0.001 + 0.02 \cdot 0.3 = 0.00698, \\ P(B = 1 \mid A = 1) &= \frac{0.901 \cdot 0.01}{0.901 \cdot 0.01 + 0.00698 \cdot 0.99} = 0.566 . \end{aligned}

A rare event becomes the likelier explanation. In the same way, P(E=1∣A=1)=0.385P(E = 1 \mid A = 1) = 0.385.

Then the radio reports an earthquake. The same enumeration over the joint table (Code section) gives P(E=1∣A=1,R=1)=0.998P(E = 1 \mid A = 1, R = 1) = 0.998, and the burglary falls back to P(B=1∣A=1,R=1)=0.033P(B = 1 \mid A = 1, R = 1) = 0.033. The earthquake explains the alarm, and the evidence for a burglary is explained away.

The graph makes the mechanism visible. BB and EE are independent a priori: knowing that there was an earthquake leaves P(B=1∣E=1)=0.01P(B = 1 \mid E = 1) = 0.01. Once their common effect AA is observed they become dependent, and P(B=1∣E=1,A=1)=0.031P(B = 1 \mid E = 1, A = 1) = 0.031. Bishop (2006, Section 8.2.1) shows the same pattern with a fuel gauge. It is also why the posterior over the weights of a regression is correlated even when their prior is independent, and why the latent variables of most models in this course have no simple joint posterior.

The models of this course as compositions#

Every model of the course is a composition of the same few blocks, and the inference method follows from the composition:

ModelBlocksPosterior
Beta–Bernoulli, normal–gammaa conjugate prior and its likelihoodexact, closed form
Bayesian linear regressionGaussian prior on ww, linear-Gaussian likelihoodexact Gaussian
Relevance vector machinethe same with one prior precision per weightevidence maximization
Bayesian logistic regressionGaussian prior, Bernoulli likelihood with a sigmoidLaplace approximation
Gaussian mixture, probabilistic PCAcategorical or Gaussian latent variable, Gaussian likelihoodEM, variational inference
Latent Dirichlet allocationDirichlet priors, two categorical layersvariational inference, Gibbs sampling
Variational autoencoderGaussian prior, neural-network likelihoodamortized variational inference

Where it breaks: a correct computation in a wrong model#

Bayes’ formula is coherent given the model. It cannot repair the model. Vetrov and Kropotov end their alarm example with the owner, reassured by the radio report, returning to a burgled flat. Every calculation was right; the graph was wrong. Burglars listen to the radio too, and an earthquake is a good night for them, so BB and EE were never independent.

Put that into the model as a toy number. Let a burglary be twenty times as likely on a night with an earthquake, P(B=1∣E=1)=0.2P(B = 1 \mid E = 1) = 0.2, and keep P(B=1∣E=0)=0.01P(B = 1 \mid E = 0) = 0.01. The graph gains an arrow E→BE \to B, and the same enumeration gives:

Beliefindependent causesP(B=1∣E=1)=0.2P(B = 1 \mid E = 1) = 0.2
P(B=1)P(B = 1)0.0100.0100.0140.014
P(B=1∣A=1)P(B = 1 \mid A = 1)0.5660.5660.6860.686
P(B=1∣A=1,R=1)P(B = 1 \mid A = 1, R = 1)0.0330.0330.4430.443

The radio report that made a burglary negligible now leaves it close to even odds. The prior probability of a burglary barely moved, from 0.0100.010 to 0.0140.014, so no amount of checking the marginal rates would have revealed the error. Only the dependence changed, and the dependence is what explaining away runs on.

The same happens with a likelihood that misdescribes the data. The posterior concentrates, confidently, on the parameter whose model is closest to the truth in KL divergence, the same limit as maximum likelihood. The reason is the law of large numbers: 1nlog⁡p(X∣θ)\frac1n \log p(X \mid \theta) tends to the expectation of log⁡p(x∣θ)\log p(x \mid \theta) under the true distribution, which is minus that KL divergence plus a constant. So the likelihood behaves like e−nKLe^{-n \mathrm{KL}} up to a factor free of θ\theta, and it swamps the prior. Kleijn and van der Vaart (2012) state the conditions and prove the limit.

Two other costs are of a different kind. The prior must be chosen, and for small data it shapes the answer, so its influence has to be checked; the model selection note shows that the evidence depends on it even more than the posterior. And the integrals are hard: enumeration over mm binary variables costs 2m2^m terms, and closed-form posteriors over continuous parameters exist essentially for conjugate and linear-Gaussian models. The rest of the course is about approximating them.

The plan of the course#

The course follows one question through five sections: how to compute the posterior, and what to do when it cannot be computed exactly. The scope and order follow the course of Vetrov and Kropotov (2015) at Moscow State University.

SectionNotesWhat it adds
Bayesian Modellingthis note; conjugate priors; model selectionthe cases with a closed-form posterior and evidence; comparing models by their evidence
Bayesian Linear ModelsBayesian linear regression; the relevance vector machine; the Laplace approximationa Gaussian posterior and predictive; hyperparameters fitted by the evidence; per-weight priors that switch features off; the first approximate posterior, for classification
Latent Variables and Approximate InferenceEM and Bayesian PCA; variational inference; Gibbs samplingthe three general methods for models whose posterior has no formula
Nonparametric and Topic ModelsGaussian processes; Dirichlet processes; latent Dirichlet allocationpriors over functions; mixtures with an unbounded number of components; a topic model built from the earlier blocks
Scalable Inferencestochastic variational inference; black-box variational inference and the VAE; Bayesian deep learninglarge datasets; models without conjugacy; what a posterior over network weights adds

The course assumes the Bayesian inference, multivariate Gaussian and Markov chain Monte Carlo notes of the probability course, the linear models and EM algorithm of the Machine Learning course, and the symmetric matrices and matrix calculus of the Mathematics course.

Its last section leads into the variational and sampling methods of the Generative Models course, starting from the variational autoencoder.

What you should remember#

  • Bayesian reading: a probability is a degree of belief, and every unknown, parameters included, gets a distribution.
  • Posterior ∝ likelihood × prior; the evidence p(X)p(X) normalizes it and compares models.
  • Predict by averaging over the posterior: urns give 0.3330.333 instead of the plug-in 0.30.3, and 0.1630.163 instead of 00.
  • For independent batches, the posterior after one batch is the prior for the next.
  • A point estimate loses the width, the shape and the evidence; it is safe when the posterior is a narrow peak.
  • A Bayesian network is a product of blocks, one per variable given its parents. Observing a common effect makes independent causes dependent, and a missing arrow makes the exact answer wrong.

Code#

The urn posterior and its predictive, the continuous coin, the three point estimates after three white draws, a mode that misleads, sequential updating and its normalizer, and the burglar alarm by enumeration, with independent causes and with burglaries more likely during earthquakes. The script runs in about a second; exact numbers can differ in the last digit across platforms and library versions.

import numpy as np
from itertools import product
from scipy import stats

# Which urn? Urn u holds u black and 10 - u white balls; an urn is picked uniformly, balls are drawn with replacement
u = np.arange(11)
f = u / 10                                      # the fraction of black balls in urn u
def urn_posterior(n_black, n_draws, prior=np.full(11, 1 / 11)):
    lik = f ** n_black * (1 - f) ** (n_draws - n_black)
    return lik * prior / (lik * prior).sum()    # Bayes' formula over the 11 hypotheses

post = urn_posterior(3, 10)
print(post.round(3))                            # [0.    0.063 0.221 0.293 0.236 0.129 0.047 0.01  0.001 0.    0.   ]
print(round(post @ f, 3), f[post.argmax()])     # 0.333 0.3: the predictive against the plug-in of the best urn

# the same question with a continuous bias and a uniform prior: Beta(1 + 3, 1 + 7)
print(round(stats.beta(4, 8).mean(), 3))        # 0.333

# three white balls in three draws: the point estimates say "never black"
post = urn_posterior(0, 3)
cdf = post.cumsum()
print(post[:4].round(3), f[post.argmax()], f[np.searchsorted(cdf, 0.5)], round(post @ f, 4))
# [0.331 0.241 0.169 0.113] 0.0 0.1 0.1625: posterior mode, median and mean of the fraction of black balls
print(round(-np.log(post @ f), 2))              # 1.82: the log loss of the predictive if the next ball is black

# a mode that misleads: 0.9 N(0, 1) + 0.1 N(4, 0.01^2), the heights of the needle and of the bump
mix = lambda t: 0.9 * stats.norm.pdf(t, 0, 1) + 0.1 * stats.norm.pdf(t, 4, 0.01)
print(round(mix(4.0), 2), round(mix(0.0), 3), round(0.9 * 0 + 0.1 * 4, 1))   # 3.99 0.359 0.4: mode at 4, mean 0.4

# sequential updating: one ball at a time gives the batch posterior
draws = [1, 0, 0, 1, 0, 0, 0, 1, 0, 0]          # 3 black in 10
p = np.full(11, 1 / 11)
for d in draws:
    p = urn_posterior(d, 1, prior=p)
print(np.abs(p - urn_posterior(3, 10)).max() < 1e-12)   # True

# the normalizer of the second update: X1 = the first five draws (2 black), X2 = the last five (1 black)
pX1 = (f ** 2 * (1 - f) ** 3).mean()            # p(X1): the sum rule over urns with prior 1/11
pX2_X1 = urn_posterior(2, 5) @ (f * (1 - f) ** 4)   # p(X2 | X1) = sum_u p(X2 | u) p(u | X1)
print(round(pX2_X1, 4), round(pX1, 5), round(pX1 * pX2_X1, 6), round((f ** 3 * (1 - f) ** 7).mean(), 6))
# 0.0455 0.01515 0.000689 0.000689: p(X2 | X1), p(X1), their product and p(X1, X2)

# the burglar alarm by enumeration of the joint distribution p(e) p(b | e) p(a | b, e) p(r | e)
pE = 0.02
pA = {(0, 0): 0.001, (0, 1): 0.3, (1, 0): 0.9, (1, 1): 0.95}   # P(a = 1 | b, e)
pR = {0: 0.001, 1: 0.8}                                        # P(r = 1 | e)

def alarm(pB):                                  # pB[e] = P(b = 1 | e); equal entries mean independent causes
    def joint(b, e, a, r):
        return ((pB[e] if b else 1 - pB[e]) * (pE if e else 1 - pE)
                * (pA[b, e] if a else 1 - pA[b, e]) * (pR[e] if r else 1 - pR[e]))
    def prob(query, evidence):
        states = [dict(zip('bear', s)) for s in product((0, 1), repeat=4)]
        match = lambda s, c: all(s[k] == v for k, v in c.items())
        den = sum(joint(**s) for s in states if match(s, evidence))
        return round(sum(joint(**s) for s in states if match(s, evidence) and match(s, query)) / den, 3)
    return prob

prob = alarm({0: 0.01, 1: 0.01})
print(prob({'b': 1}, {}), prob({'b': 1}, {'a': 1}), prob({'b': 1}, {'a': 1, 'r': 1}))
# 0.01 0.566 0.033: the alarm raises the belief in a burglary, the radio report explains it away
print(prob({'e': 1}, {'a': 1}), prob({'e': 1}, {'a': 1, 'r': 1}))     # 0.385 0.998
print(prob({'b': 1}, {'e': 1}), prob({'b': 1}, {'e': 1, 'a': 1}))     # 0.01 0.031: independent until the alarm is observed

# the wrong graph: burglaries are 20 times as likely on a night with an earthquake
prob = alarm({0: 0.01, 1: 0.2})
print(prob({'b': 1}, {}), prob({'b': 1}, {'a': 1}), prob({'b': 1}, {'a': 1, 'r': 1}))
# 0.014 0.686 0.443: the radio report no longer explains the burglary away

Next#

Every Bayesian answer here was a sum over eleven urns or sixteen states of the alarm. With continuous parameters the sums become integrals, and the integral in the denominator of Bayes’ formula usually has no formula. The next note finds the cases in which it does: priors that, combined with their likelihood, give a posterior of the same family, so that learning reduces to adding counts. They exist for every member of the exponential family, which includes almost all the standard blocks of this note.

References#