Course contents 02 / 15

02 / 15 · Bayesian Modelling

Conjugate priors and the exponential family

Priors that keep the posterior in their own family, so that learning adds counts: the standard pairs, the exponential family that explains them, closed-form evidence and predictives, and what a light-tailed prior gets wrong.

On this page 12

A coin is flipped seven times: 1,0,1,1,0,1,11, 0, 1, 1, 0, 1, 1. Before the flips you believed it was probably close to fair, a Beta(2,2)\mathrm{Beta}(2, 2) prior on its probability of heads ff. After them, your belief is Beta(7,4)\mathrm{Beta}(7, 4): two pseudo-counts went up by the five heads and the two tails. Two numbers carry the whole posterior, and the next flip is heads with probability 7/117/11, the posterior mean.

Most posteriors are not like that. The previous note answered every question by a sum over eleven urns. With a continuous parameter the sum becomes an integral, and the normalizing integral of Bayes’ formula, the evidence, usually has no closed form.

Without a formula, the posterior can still be computed on a grid: evaluate likelihood × prior at GG points per parameter and normalize. The cost is GdG^d evaluations for dd parameters. The Code section computes the posterior of a normal mean and precision on a 1201×16001201 \times 1600 grid, about two million evaluations for two parameters. Ten parameters with a coarse 100 points each would need 102010^{20}. Exact Bayesian inference in higher dimensions needs integrals done on paper, and the coin is the simplest case in which paper suffices.

Conjugacy: the posterior stays in the family#

A family of priors p(θ∣α)p(\theta \mid \alpha), indexed by hyperparameters α\alpha, is conjugate to a likelihood p(x∣θ)p(x \mid \theta) if for every prior in the family and every dataset the posterior is again in the family:

p(θ∣X,α)∝p(X∣θ) p(θ∣α)∝p(θ∣α′).p(\theta \mid X, \alpha) \propto p(X \mid \theta)\, p(\theta \mid \alpha) \propto p(\theta \mid \alpha') .

A primed hyperparameter, α′\alpha', is the value after the update. Learning is the map α→α′\alpha \to \alpha' on a few numbers. Because the posterior is again a prior of the family, the map can be applied one observation at a time, and by the sequential updating argument the result does not depend on the order or the batching of the data.

How do we find a conjugate prior before any theory? We read the likelihood of one observation as a function of the parameter and look for densities of the same functional form, since multiplying two such functions keeps the form. Take a normal with mean zero and an unknown precision λ\lambda:

N(x∣0,λ−1)=λ2π e−λx2/2.\mathcal N(x \mid 0, \lambda^{-1}) = \sqrt{\frac{\lambda}{2\pi}}\, e^{-\lambda x^2/2} .

As a function of λ\lambda it is a power of λ\lambda times the exponential of a linear function of λ\lambda. The gamma density λa−1e−bλ\lambda^{a-1} e^{-b\lambda}, up to its constant, has the same form. Their product adds 1/21/2 to aa and x2/2x^2/2 to bb, so the gamma prior is conjugate. The exponential family turns this reading into a rule.

Two more quantities come free. Write the prior as p(θ∣α)=p~(θ∣α)/Z(α)p(\theta \mid \alpha) = \tilde p(\theta \mid \alpha) / Z(\alpha), with p~\tilde p unnormalized and ZZ its normalizing constant. Conjugacy means that the likelihood times p~(θ∣α)\tilde p(\theta \mid \alpha) equals c(X) p~(θ∣α′)c(X)\, \tilde p(\theta \mid \alpha') for a factor c(X)c(X) that does not depend on θ\theta. The evidence is the sum rule over θ\theta followed by the product rule; substituting this identity and integrating,

p(X∣α)=∫p(X∣θ) p~(θ∣α)Z(α) dθ=c(X)Z(α)∫p~(θ∣α′) dθ(conjugacy)=c(X) Z(α′)Z(α)(definition of Z).\begin{aligned} p(X \mid \alpha) &= \int p(X \mid \theta)\, \frac{\tilde p(\theta \mid \alpha)}{Z(\alpha)}\, d\theta \\ &= \frac{c(X)}{Z(\alpha)} \int \tilde p(\theta \mid \alpha')\, d\theta && \text{(conjugacy)} \\ &= c(X)\, \frac{Z(\alpha')}{Z(\alpha)} && \text{(definition of } Z) . \end{aligned}

The evidence is a ratio of normalizing constants. The predictive of a new point is the evidence of one more observation divided by the evidence of the data, p(x∗∣X,α)=p(X,x∗∣α)/p(X∣α)p(x_* \mid X, \alpha) = p(X, x_* \mid \alpha) / p(X \mid \alpha) by the definition of a conditional distribution, and so again a ratio of normalizing constants.

Beta–Bernoulli and the evidence#

The Beta(a,b)\mathrm{Beta}(a, b) density on [0,1][0, 1] is fa−1(1−f)b−1/B(a,b)f^{a-1}(1-f)^{b-1} / B(a, b), with the normalizing constant B(a,b)=Γ(a)Γ(b)/Γ(a+b)B(a, b) = \Gamma(a)\Gamma(b)/\Gamma(a+b), where Γ(a)=∫0∞ta−1e−t dt\Gamma(a) = \int_0^\infty t^{a-1} e^{-t}\, dt and Γ(n)=(n−1)!\Gamma(n) = (n-1)! for integers. The beta section derives this constant by a change of variables in Γ(a)Γ(b)\Gamma(a)\Gamma(b); the same substitution with KK variables gives the Dirichlet constant below.

For flips xi∈{0,1}x_i \in \{0, 1\} with probability of heads ff, the posterior after kk heads in nn flips is Beta(a+k, b+n−k)\mathrm{Beta}(a + k,\ b + n - k). The Bayesian inference note derived this update and read aa and bb as pseudo-counts.

The new ingredient is the evidence. The likelihood of the sequence is fk(1−f)n−kf^k (1-f)^{n-k}, so c(X)=1c(X) = 1 and

p(X∣a,b)=B(a+k, b+n−k)B(a,b).p(X \mid a, b) = \frac{B(a + k,\ b + n - k)}{B(a, b)} .

For the seven flips of the opening, k=5k = 5 and the prior is Beta(2,2)\mathrm{Beta}(2, 2); with Γ(n)=(n−1)!\Gamma(n) = (n-1)!,

B(7,4)B(2,2)=6! 3!/10!1! 1!/3!=1/8401/6=1140=0.00714.\frac{B(7, 4)}{B(2, 2)} = \frac{6!\, 3! / 10!}{1!\, 1! / 3!} = \frac{1/840}{1/6} = \frac{1}{140} = 0.00714 .

The same number is the product of the seven one-step predictives, each the current posterior mean a/(a+b)a/(a + b) or its complement, with aa or bb raised by one after each flip:

24⋅25⋅36⋅47⋅38⋅59⋅610=1140.\frac{2}{4} \cdot \frac{2}{5} \cdot \frac{3}{6} \cdot \frac{4}{7} \cdot \frac{3}{8} \cdot \frac{5}{9} \cdot \frac{6}{10} = \frac{1}{140} .

By the product rule, p(x1,…,xn)=∏ip(xi∣x1,…,xi−1)p(x_1, \dots, x_n) = \prod_i p(x_i \mid x_1, \dots, x_{i-1}): the evidence is the probability with which the model predicted each observation from the ones before it. The next note builds model comparison on this reading.

Dirichlet–categorical#

A categorical variable takes one of KK values with probabilities π=(π1,…,πK)\pi = (\pi_1, \dots, \pi_K). The Dirichlet distribution Dir(α1,…,αK)\mathrm{Dir}(\alpha_1, \dots, \alpha_K) on such probability vectors has density proportional to ∏kπkαk−1\prod_k \pi_k^{\alpha_k - 1}; write α0=∑kαk\alpha_0 = \sum_k \alpha_k. With counts n1,…,nKn_1, \dots, n_K in nn observations, the likelihood is ∏kπknk\prod_k \pi_k^{n_k}, and

p(π∣X)∝∏k=1Kπknk⋅∏k=1Kπkαk−1=∏k=1Kπkαk+nk−1,\begin{aligned} p(\pi \mid X) &\propto \prod_{k=1}^K \pi_k^{n_k} \cdot \prod_{k=1}^K \pi_k^{\alpha_k - 1} \\ &= \prod_{k=1}^K \pi_k^{\alpha_k + n_k - 1} , \end{aligned}

so π∣X∼Dir(α1+n1,…,αK+nK)\pi \mid X \sim \mathrm{Dir}(\alpha_1 + n_1, \dots, \alpha_K + n_K). The Dirichlet is the beta distribution for KK categories. Its normalizing constant is Z(α)=∏kΓ(αk)/Γ(α0)Z(\alpha) = \prod_k \Gamma(\alpha_k) / \Gamma(\alpha_0). Both quantities below are ratios of such constants. The mean of πk\pi_k multiplies the density by one more πk\pi_k, so it is Z(α+ek)/Z(α)=αk/α0Z(\alpha + e_k)/Z(\alpha) = \alpha_k/\alpha_0 by Γ(x+1)=x Γ(x)\Gamma(x + 1) = x\,\Gamma(x), with eke_k the kk-th unit vector. The posterior mean is the predictive probability of category kk, as for the coin, and the evidence is Z(α+n)/Z(α)Z(\alpha + n)/Z(\alpha) with c(X)=1c(X) = 1:

p(x∗=k∣X)=αk+nkα0+n,p(X∣α)=Γ(α0)Γ(α0+n)∏k=1KΓ(αk+nk)Γ(αk).\begin{aligned} p(x_* = k \mid X) &= \frac{\alpha_k + n_k}{\alpha_0 + n}, \\ p(X \mid \alpha) &= \frac{\Gamma(\alpha_0)}{\Gamma(\alpha_0 + n)} \prod_{k=1}^K \frac{\Gamma(\alpha_k + n_k)}{\Gamma(\alpha_k)} . \end{aligned}

Take four categories, a uniform prior Dir(1,1,1,1)\mathrm{Dir}(1, 1, 1, 1) and counts (5,2,0,1)(5, 2, 0, 1). The posterior is Dir(6,3,1,2)\mathrm{Dir}(6, 3, 1, 2), and the predictive probabilities are 0.5,0.25,0.083,0.1670.5, 0.25, 0.083, 0.167. The category never seen keeps probability 1/121/12 instead of the maximum likelihood value 0. The evidence, with Γ(4)=3!\Gamma(4) = 3!, Γ(12)=11!\Gamma(12) = 11! and Γ(1+nk)=nk!\Gamma(1 + n_k) = n_k!, is

3!11!⋅5! 2! 0! 1!=127720.\frac{3!}{11!} \cdot 5!\, 2!\, 0!\, 1! = \frac{1}{27720} .

Adding α\alpha to every count is the add-α\alpha smoothing of n-gram language models, seen as a posterior mean. The total α0\alpha_0 is the strength of the prior in pseudo-counts. Values αk<1\alpha_k < 1 make the exponents αk−1\alpha_k - 1 negative, so the density grows without bound as any πk→0\pi_k \to 0: the prior mass sits near the edges and corners of the simplex and favours sparse probability vectors, which is how latent Dirichlet allocation makes each document use few topics.

Normal–normal: an unknown mean#

For observations from N(μ,σ2)\mathcal N(\mu, \sigma^2) with known σ2\sigma^2 and a prior N(μ0,τ2)\mathcal N(\mu_0, \tau^2), the Bayesian inference note derived the posterior N(μn,σn2)\mathcal N(\mu_n, \sigma_n^2) with

1σn2=1τ2+nσ2,μnσn2=μ0τ2+∑ixiσ2.\begin{aligned} \frac{1}{\sigma_n^2} &= \frac{1}{\tau^2} + \frac{n}{\sigma^2}, \\ \frac{\mu_n}{\sigma_n^2} &= \frac{\mu_0}{\tau^2} + \frac{\sum_i x_i}{\sigma^2} . \end{aligned}

To see where they come from, take the logarithm of prior × likelihood and collect the powers of μ\mu; every term free of μ\mu goes into the constant:

log⁡p(μ∣X)=−(μ−μ0)22τ2−∑i=1n(xi−μ)22σ2+const=−μ22(1τ2+nσ2)+μ(μ0τ2+∑ixiσ2)+const.\begin{aligned} \log p(\mu \mid X) &= -\frac{(\mu - \mu_0)^2}{2\tau^2} - \sum_{i=1}^n \frac{(x_i - \mu)^2}{2\sigma^2} + \text{const} \\ &= -\frac{\mu^2}{2} \Big(\frac{1}{\tau^2} + \frac{n}{\sigma^2}\Big) \\ &\quad + \mu \Big(\frac{\mu_0}{\tau^2} + \frac{\sum_i x_i}{\sigma^2}\Big) + \text{const} . \end{aligned}

The log-density of N(μn,σn2)\mathcal N(\mu_n, \sigma_n^2) is −μ2/(2σn2)+μ μn/σn2+const-\mu^2/(2\sigma_n^2) + \mu\, \mu_n/\sigma_n^2 + \text{const}. Matching the coefficients of μ2\mu^2 and of μ\mu gives the two updates; completing the square does the same for vectors.

The inverse of a variance is a precision. Written this way, both updates are additions: the precision grows by 1/σ21/\sigma^2 per observation, and precision × mean grows by xi/σ2x_i/\sigma^2. The data enter only through nn and ∑ixi\sum_i x_i, a first example of the sufficient statistics below.

The predictive of a new point x∗=μ+εx_* = \mu + \varepsilon adds the noise to the posterior uncertainty of the mean. Given XX, the mean μ\mu and the new noise ε∼N(0,σ2)\varepsilon \sim \mathcal N(0, \sigma^2) are independent, and the sum of two independent Gaussians is Gaussian with the means and the variances added (linear-Gaussian marginal):

p(x∗∣X)=N(x∗∣μn, σn2+σ2).p(x_* \mid X) = \mathcal N(x_* \mid \mu_n,\ \sigma_n^2 + \sigma^2) .

With the prior N(0,1)\mathcal N(0, 1), noise variance σ2=4\sigma^2 = 4 and four observations with mean 1.51.5, the posterior precision is 1+4/4=21 + 4/4 = 2. So σn2=0.5\sigma_n^2 = 0.5 and, with ∑ixi=6\sum_i x_i = 6, μn=0.5⋅(0+6/4)=0.75\mu_n = 0.5 \cdot (0 + 6/4) = 0.75, and the predictive is N(0.75,4.5)\mathcal N(0.75, 4.5). For vectors, the same update with precision matrices is the conditional of a joint Gaussian, and Bayesian linear regression is this update for the weights of a linear model.

Normal with known mean: a gamma prior on the precision#

Now the mean μ0\mu_0 is known and the precision λ=1/σ2\lambda = 1/\sigma^2 is not. The opening of the note read one observation of N(0,λ−1)\mathcal N(0, \lambda^{-1}) as a function of λ\lambda and found the gamma form. The gamma distribution with shape a>0a > 0 and rate b>0b > 0 is defined on λ>0\lambda > 0 by the density

Gamma(λ∣a,b)=baΓ(a) λa−1e−bλ.\mathrm{Gamma}(\lambda \mid a, b) = \frac{b^a}{\Gamma(a)}\, \lambda^{a-1} e^{-b\lambda} .

Its mean is a/ba/b and its variance a/b2a/b^2, both derived in the gamma section from ∫0∞λc−1e−bλ dλ=Γ(c)/bc\int_0^\infty \lambda^{c-1} e^{-b\lambda}\, d\lambda = \Gamma(c)/b^c.

As a function of λ\lambda, the likelihood of nn observations is a power of λ\lambda times an exponential:

p(X∣λ)=∏i=1nλ2π e−λ(xi−μ0)2/2∝λn/2exp⁡(−λ2∑i=1n(xi−μ0)2).\begin{aligned} p(X \mid \lambda) &= \prod_{i=1}^n \sqrt{\frac{\lambda}{2\pi}}\, e^{-\lambda (x_i - \mu_0)^2 / 2} \\ &\propto \lambda^{n/2} \exp\Big(-\frac\lambda2 \sum_{i=1}^n (x_i - \mu_0)^2\Big) . \end{aligned}

Multiplying by the prior λa0−1e−b0λ\lambda^{a_0 - 1} e^{-b_0 \lambda} adds the powers of λ\lambda and the coefficients of −λ-\lambda, so the posterior is Gamma(an,bn)\mathrm{Gamma}(a_n, b_n) with

an=a0+n2,bn=b0+12∑i=1n(xi−μ0)2.\begin{aligned} a_n &= a_0 + \frac n2, \\ b_n &= b_0 + \frac12 \sum_{i=1}^n (x_i - \mu_0)^2 . \end{aligned}

Each observation adds 1/21/2 to the shape and half its squared deviation to the rate. The more the data spread around μ0\mu_0, the larger bnb_n and the smaller the posterior mean an/bna_n/b_n of the precision. Setting the derivative n/(2λ)−12∑i(xi−μ0)2n/(2\lambda) - \frac12 \sum_i (x_i - \mu_0)^2 of the log-likelihood to zero gives the maximum likelihood value n/∑i(xi−μ0)2n / \sum_i (x_i - \mu_0)^2. The posterior mean (a0+n/2)/(b0+12∑i(xi−μ0)2)(a_0 + n/2)/\big(b_0 + \frac12 \sum_i (x_i - \mu_0)^2\big) is the mediant of the prior mean a0/b0a_0/b_0 and this value, so it lies between them.

Take μ0=1\mu_0 = 1, the prior Gamma(1,1)\mathrm{Gamma}(1, 1), with mean 1 and variance 1, and the five points 1.2,0.4,2.1,1.5,0.81.2, 0.4, 2.1, 1.5, 0.8 of the next section:

QuantityValue
∑i(xi−μ0)2\sum_i (x_i - \mu_0)^21.901.90
ana_n, bn=1+1.90/2b_n = 1 + 1.90/23.53.5, 1.951.95
posterior mean an/bna_n/b_n1.791.79
posterior standard deviation an/bn\sqrt{a_n}/b_n0.960.96
maximum likelihood 5/1.905/1.902.632.63

Doubling every deviation from μ0\mu_0 multiplies the sum of squares by 4, to 7.67.6, and the posterior mean of the precision drops to 3.5/4.8=0.733.5/4.8 = 0.73.

Normal–gamma: unknown mean and precision#

When the noise level is unknown too, both μ\mu and the precision λ=1/σ2\lambda = 1/\sigma^2 need a prior. The likelihood of nn observations is

p(X∣μ,λ)=(λ2π)n/2exp⁡(−λ2∑i=1n(xi−μ)2).p(X \mid \mu, \lambda) = \Big(\frac{\lambda}{2\pi}\Big)^{n/2} \exp\Big(-\frac{\lambda}{2} \sum_{i=1}^n (x_i - \mu)^2\Big) .

Why not take independent priors, a normal for μ\mu and a gamma for λ\lambda? Expand the square: the exponent contains λμxi\lambda \mu x_i and λμ2\lambda \mu^2, products of the two unknowns, so the likelihood does not factorize into a function of μ\mu times a function of λ\lambda. A conjugate prior must have the same shape, so it cannot factorize either. With independent priors the posterior leaves every standard family; the variational inference note starts from exactly that case.

The conjugate prior ties the two together. With the gamma distribution in shape and rate, the normal–gamma prior is

p(μ,λ)=N(μ∣μ0,(κ0λ)−1) Gamma(λ∣a0,b0),p(\mu, \lambda) = \mathcal N\big(\mu \mid \mu_0, (\kappa_0 \lambda)^{-1}\big)\, \mathrm{Gamma}(\lambda \mid a_0, b_0) ,

in which, given λ\lambda, the mean has the precision of κ0\kappa_0 observations: the more precise the data, the more precisely the mean is pinned down.

Two identities do the update. With xˉ\bar x the sample mean and S=∑i(xi−xˉ)2S = \sum_i (x_i - \bar x)^2, the sum of squares splits as ∑i(xi−μ)2=S+n(xˉ−μ)2\sum_i (x_i - \mu)^2 = S + n(\bar x - \mu)^2: write xi−μ=(xi−xˉ)+(xˉ−μ)x_i - \mu = (x_i - \bar x) + (\bar x - \mu) and expand; the cross term vanishes because ∑i(xi−xˉ)=0\sum_i (x_i - \bar x) = 0. Completing the square in μ\mu,

κ0(μ−μ0)2+n(μ−xˉ)2=κn(μ−μn)2+κ0nκn(xˉ−μ0)2,\begin{aligned} \kappa_0 (\mu - \mu_0)^2 &+ n(\mu - \bar x)^2 \\ &= \kappa_n (\mu - \mu_n)^2 + \frac{\kappa_0 n}{\kappa_n} (\bar x - \mu_0)^2 , \end{aligned}

where κn=κ0+n\kappa_n = \kappa_0 + n and μn=(κ0μ0+nxˉ)/κn\mu_n = (\kappa_0 \mu_0 + n \bar x)/\kappa_n. To check it, compare the two sides: the coefficients of μ2\mu^2 are both κn\kappa_n, those of μ\mu both −2κnμn-2\kappa_n \mu_n, and the constants agree because κn(κ0μ02+nxˉ2)−(κ0μ0+nxˉ)2=κ0n(xˉ−μ0)2\kappa_n(\kappa_0 \mu_0^2 + n \bar x^2) - (\kappa_0 \mu_0 + n \bar x)^2 = \kappa_0 n (\bar x - \mu_0)^2.

Now multiply the prior by the likelihood and keep only what depends on μ\mu or λ\lambda. The prior contributes λ1/2e−κ0λ(μ−μ0)2/2 λa0−1e−b0λ\lambda^{1/2} e^{-\kappa_0 \lambda (\mu - \mu_0)^2/2}\, \lambda^{a_0 - 1} e^{-b_0 \lambda}, the likelihood λn/2e−λ(S+n(xˉ−μ)2)/2\lambda^{n/2} e^{-\lambda (S + n(\bar x - \mu)^2)/2}. By the two identities the product is

λ1/2e−κnλ(μ−μn)2/2×λa0+n/2−1e−λ(b0+S2+κ0n(xˉ−μ0)22κn).\begin{aligned} &\lambda^{1/2} e^{-\kappa_n \lambda (\mu - \mu_n)^2 / 2} \\ &\times \lambda^{a_0 + n/2 - 1} e^{-\lambda \left(b_0 + \frac S2 + \frac{\kappa_0 n (\bar x - \mu_0)^2}{2\kappa_n}\right)} . \end{aligned}

The first line is a normal density in μ\mu with precision κnλ\kappa_n \lambda, up to its constant; the second is a gamma density in λ\lambda. The posterior is normal–gamma with

κn=κ0+n,μn=κ0μ0+nxˉκn,an=a0+n2,bn=b0+S2+κ0n(xˉ−μ0)22κn.\begin{aligned} \kappa_n &= \kappa_0 + n, \\ \mu_n &= \frac{\kappa_0 \mu_0 + n \bar x}{\kappa_n}, \\ a_n &= a_0 + \frac n2, \\ b_n &= b_0 + \frac S2 + \frac{\kappa_0 n (\bar x - \mu_0)^2}{2 \kappa_n} . \end{aligned}

The rate bnb_n collects three sources of squared deviation: the prior’s, the spread of the data around their mean, and the disagreement between the data mean and the prior mean. Writing σ2=1/λ\sigma^2 = 1/\lambda instead gives the same model as the normal–inverse-gamma prior.

The marginal posterior of the mean integrates out the precision. For a normal with precision τλ\tau\lambda and a Gamma(a,b)\mathrm{Gamma}(a, b) precision, using ∫0∞λc−1e−dλ dλ=Γ(c)/dc\int_0^\infty \lambda^{c-1} e^{-d\lambda}\, d\lambda = \Gamma(c)/d^c,

∫0∞λ1/2e−τλ(μ−m)2/2 λa−1e−bλ dλ∝(b+τ(μ−m)22)−(a+1/2)∝(1+(μ−m)22a⋅b/(aτ))−(2a+1)/2.\begin{aligned} \int_0^\infty \lambda^{1/2} e^{-\tau\lambda (\mu - m)^2 / 2}&\, \lambda^{a-1} e^{-b\lambda}\, d\lambda \\ &\propto \Big(b + \frac{\tau (\mu - m)^2}{2}\Big)^{-(a + 1/2)} \\ &\propto \Big(1 + \frac{(\mu - m)^2}{2a \cdot b/(a\tau)}\Big)^{-(2a+1)/2} . \end{aligned}

The second line takes b−(a+1/2)b^{-(a + 1/2)} out of the bracket. The Student-t density with location mm, squared scale s2s^2 and ν\nu degrees of freedom is, by definition, St(μ∣m,s2,ν)∝(1+(μ−m)2/(νs2))−(ν+1)/2\mathrm{St}(\mu \mid m, s^2, \nu) \propto \big(1 + (\mu - m)^2/(\nu s^2)\big)^{-(\nu + 1)/2}. Matching the last line gives ν=2a\nu = 2a and s2=b/(aτ)s^2 = b/(a\tau). So

p(μ∣X)=St(μ  ∣  μn, bnanκn, 2an).p(\mu \mid X) = \mathrm{St}\Big(\mu \;\Big|\; \mu_n,\ \frac{b_n}{a_n \kappa_n},\ 2a_n\Big) .

Take the prior μ0=0\mu_0 = 0, κ0=1\kappa_0 = 1, a0=b0=1a_0 = b_0 = 1 and the data 1.2,0.4,2.1,1.5,0.81.2, 0.4, 2.1, 1.5, 0.8:

QuantityValue
nn, xˉ\bar x, SS55, 1.21.2, 1.701.70
κn\kappa_n, μn\mu_n, ana_n66, 1.01.0, 3.53.5
bn=1+1.70/2+5⋅1.22/12b_n = 1 + 1.70/2 + 5 \cdot 1.2^2/122.452.45
squared scale of μ\mu, bn/(anκn)b_n/(a_n \kappa_n)0.1170.117

The mean has a Student-t posterior with 7 degrees of freedom, centre 1.01.0 and squared scale 0.1170.117. The Code section checks this marginal against the two-million-point grid of the opening: the two densities agree to 10−410^{-4}.

The exponential family#

Every pair so far had the same structure. The likelihood depended on the data through a few sums: kk and nn; the counts nkn_k; ∑xi\sum x_i, ∑xi2\sum x_i^2 and nn. And the prior had the form of that likelihood. The exponential family is the class of distributions for which this always happens.

Natural parameters and sufficient statistics#

A distribution belongs to the exponential family if its density, or probability mass function, can be written as

p(x∣η)=h(x)exp⁡(η⊤u(x)−A(η)),A(η)=log⁡∫h(x) eη⊤u(x) dx,\begin{aligned} p(x \mid \eta) &= h(x) \exp\big(\eta^\top u(x) - A(\eta)\big), \\ A(\eta) &= \log \int h(x)\, e^{\eta^\top u(x)}\, dx , \end{aligned}

where η\eta are the natural parameters, u(x)u(x) the sufficient statistics, h(x)h(x) a base measure, and A(η)A(\eta) the log-partition function, which makes the density integrate to 1. The usual parameters are a reparametrization of η\eta:

Distributionη\etau(x)u(x)A(η)A(\eta)h(x)h(x)
Bernoulli(p)(p)log⁡p1−p\log \frac{p}{1-p}xxlog⁡(1+eη)\log(1 + e^\eta)11
Poisson(λ)(\lambda)log⁡λ\log \lambdaxxeηe^\eta1/x!1/x!
N(μ,σ2)\mathcal N(\mu, \sigma^2)(μσ2,−12σ2)\big(\frac{\mu}{\sigma^2}, -\frac{1}{2\sigma^2}\big)(x,x2)(x, x^2)−η124η2−12log⁡(−2η2)-\frac{\eta_1^2}{4\eta_2} - \frac12 \log(-2\eta_2)12π\frac{1}{\sqrt{2\pi}}
Categorical(π)(\pi)log⁡πkπK\log \frac{\pi_k}{\pi_K}, k<Kk < Kone-hot, first K−1K - 1 entrieslog⁡(1+∑k<Keηk)\log\big(1 + \sum_{k<K} e^{\eta_k}\big)11
Gamma(a,b)\mathrm{Gamma}(a, b)(a−1,−b)(a - 1, -b)(log⁡x,x)(\log x, x)log⁡Γ(η1+1)−(η1+1)log⁡(−η2)\log\Gamma(\eta_1 + 1) - (\eta_1 + 1)\log(-\eta_2)11

For the Bernoulli, px(1−p)1−x=exp⁡(xlog⁡p1−p+log⁡(1−p))p^x (1-p)^{1-x} = \exp\big(x \log\frac{p}{1-p} + \log(1 - p)\big) and −log⁡(1−p)=log⁡(1+eη)-\log(1-p) = \log(1 + e^\eta). For the normal, expanding −(x−μ)2/(2σ2)-(x - \mu)^2/(2\sigma^2) gives the terms xμ/σ2x \mu/\sigma^2 and −x2/(2σ2)-x^2/(2\sigma^2), and the rest, μ2/(2σ2)+log⁡σ\mu^2/(2\sigma^2) + \log\sigma, is AA written in η\eta. The beta, Dirichlet, multivariate normal and Wishart distributions belong to the family too: the beta density is exp⁡((a−1)log⁡f+(b−1)log⁡(1−f)−log⁡B(a,b))\exp\big((a-1)\log f + (b-1)\log(1-f) - \log B(a, b)\big), and the others expand the same way. The uniform distribution on [0,θ][0, \theta] with unknown θ\theta does not: its support moves with θ\theta, while h(x) eη⊤u(x)−A(η)h(x)\, e^{\eta^\top u(x) - A(\eta)} is positive wherever hh is, whatever η\eta. The Student-t and mixtures do not either: their log-densities, log⁡(1+(x−m)2/(νs2))\log\big(1 + (x - m)^2/(\nu s^2)\big) or a log of a sum, do not split into a sum of products of a function of the parameters and a function of xx.

For i.i.d. data the log-likelihood is

log⁡p(X∣η)=∑i=1nlog⁡h(xi)+η⊤∑i=1nu(xi)−nA(η).\log p(X \mid \eta) = \sum_{i=1}^n \log h(x_i) + \eta^\top \sum_{i=1}^n u(x_i) - n A(\eta) .

The data enter only through ∑iu(xi)\sum_i u(x_i) and nn, a vector whose size does not grow with nn. Two datasets with the same sums have proportional likelihoods and therefore, under any prior, the same posterior.

A statistic T(X)T(X) is sufficient for η\eta, by definition, when the conditional distribution of the data given T(X)T(X) does not depend on η\eta. The Fisher–Neyman factorization criterion says that this holds exactly when the likelihood factorizes as p(X∣η)=g(T(X),η) k(X)p(X \mid \eta) = g\big(T(X), \eta\big)\, k(X). The log-likelihood above has this form with T(X)=(∑iu(xi),n)T(X) = \big(\sum_i u(x_i), n\big) and k(X)=∏ih(xi)k(X) = \prod_i h(x_i). The whole sample is always sufficient, with T(X)=XT(X) = X and k=1k = 1. So when a model such as the Student-t is said to have no sufficient statistic, the claim is that none has a size that stays fixed as nn grows.

Proof of the factorization criterion for discrete data

Fix a dataset XX and write t=T(X)t = T(X). If the likelihood factorizes, the probability of T=tT = t is the sum over all datasets X′X' with T(X′)=tT(X') = t, so by the definition of a conditional probability

P(X∣T=t,η)=g(t,η) k(X)∑X′:T(X′)=tg(t,η) k(X′)=k(X)∑X′:T(X′)=tk(X′),\begin{aligned} P(X \mid T = t, \eta) &= \frac{g(t, \eta)\, k(X)}{\sum_{X' : T(X') = t} g(t, \eta)\, k(X')} \\ &= \frac{k(X)}{\sum_{X' : T(X') = t} k(X')} , \end{aligned}

which is free of η\eta. Conversely, if P(X∣T=t,η)=r(X)P(X \mid T = t, \eta) = r(X) does not depend on η\eta, the product rule gives p(X∣η)=P(T=t∣η) r(X)p(X \mid \eta) = P(T = t \mid \eta)\, r(X), a factorization with g(t,η)=P(T=t∣η)g(t, \eta) = P(T = t \mid \eta) and k=rk = r. For densities the sums become integrals over the sets {X′:T(X′)=t}\{X' : T(X') = t\}, and making that rigorous needs measure theory (Halmos and Savage, 1949).

Derivatives of the log-partition function#

Differentiating the normalization eA(η)=∫h(x) eη⊤u(x) dxe^{A(\eta)} = \int h(x)\, e^{\eta^\top u(x)}\, dx under the integral sign gives the moments of u(x)u(x). The exchange of derivative and integral is valid for η\eta in the interior of the set where AA is finite; Murphy (2023, Section 2.4.3) derives the same identities. The first derivative:

∇A(η) eA(η)=∫u(x) h(x) eη⊤u(x) dx,∇A(η)=∫u(x) p(x∣η) dx=E[u(x)].\begin{aligned} \nabla A(\eta)\, e^{A(\eta)} &= \int u(x)\, h(x)\, e^{\eta^\top u(x)}\, dx, \\ \nabla A(\eta) &= \int u(x)\, p(x \mid \eta)\, dx = \mathbb E[u(x)] . \end{aligned}

Differentiating ∇A(η)=∫u(x) h(x) eη⊤u(x)−A(η) dx\nabla A(\eta) = \int u(x)\, h(x)\, e^{\eta^\top u(x) - A(\eta)}\, dx once more, the exponent contributes u(x)−∇A(η)u(x) - \nabla A(\eta):

∇2A(η)=∫u(x)(u(x)−∇A(η))⊤p(x∣η) dx=E[uu⊤]−E[u] E[u]⊤=Cov⁡[u(x)].\begin{aligned} \nabla^2 A(\eta) &= \int u(x) \big(u(x) - \nabla A(\eta)\big)^\top p(x \mid \eta)\, dx \\ &= \mathbb E[u u^\top] - \mathbb E[u]\, \mathbb E[u]^\top \\ &= \operatorname{Cov}[u(x)] . \end{aligned}

Moments therefore come from derivatives. For the Bernoulli, A′(η)=eη/(1+eη)=pA'(\eta) = e^\eta/(1 + e^\eta) = p and A′′(η)=p(1−p)A''(\eta) = p(1 - p). For the normal, ∂A/∂η1=−η1/(2η2)=μ\partial A/\partial \eta_1 = -\eta_1/(2\eta_2) = \mu and ∂A/∂η2=μ2+σ2=E[x2]\partial A/\partial\eta_2 = \mu^2 + \sigma^2 = \mathbb E[x^2]. For the gamma, ∂A/∂η1=ψ(a)−log⁡b=E[log⁡x]\partial A/\partial\eta_1 = \psi(a) - \log b = \mathbb E[\log x], with ψ\psi the digamma function, a moment that is hard to get any other way and that every variational update with a gamma factor needs.

A covariance matrix is positive semidefinite, so AA is convex, by the second-order condition for convexity. The log-likelihood above is then concave in η\eta. It is strictly concave when no linear combination of the statistics u(x)u(x) is constant, because c⊤∇2A c=Var⁡[c⊤u(x)]c^\top \nabla^2 A\, c = \operatorname{Var}[c^\top u(x)] is then positive for every c≠0c \ne 0; a strictly concave function has at most one maximum. Setting its gradient to zero gives the maximum likelihood equation

∇A(η^)=1n∑i=1nu(xi).\nabla A(\hat\eta) = \frac1n \sum_{i=1}^n u(x_i) .

This is moment matching: the fitted model reproduces the sample averages of the sufficient statistics. The Gaussian fit by sample mean and sample second moment is an instance, and so is the logistic regression gradient, predicted minus observed.

Concavity gives uniqueness, not existence. Ten flips that all come up heads make the Bernoulli log-likelihood 10η−10log⁡(1+eη)=−10log⁡(1+e−η)10\eta - 10 \log(1 + e^\eta) = -10 \log(1 + e^{-\eta}). It increases with η\eta towards 0 and never reaches it: −6.93-6.93 at η=0\eta = 0, −0.067-0.067 at η=5\eta = 5. The equation A′(η^)=1A'(\hat\eta) = 1 has no solution, because A′(η)=pA'(\eta) = p is below 1 for every finite η\eta; the supremum sits at p^=1\hat p = 1, on the boundary. When the natural parameters range over an open set, a maximum exists exactly when the sample average of uu is a value of ∇A\nabla A, a mean that some finite η\eta produces: a stationary point of a concave function is its maximum, and a maximum in an open set is a stationary point.

Concavity also belongs to the natural parametrization and can be lost in another one. For a normal with known mean μ0\mu_0, write S0=∑i(xi−μ0)2S_0 = \sum_i (x_i - \mu_0)^2. In the variance v=σ2v = \sigma^2 the log-likelihood is, up to a constant,

ℓ(v)=−n2log⁡v−S02v,ℓ′′(v)=n2v2−S0v3,\begin{aligned} \ell(v) &= -\frac n2 \log v - \frac{S_0}{2v}, \\ \ell''(v) &= \frac{n}{2v^2} - \frac{S_0}{v^3} , \end{aligned}

which is positive for v>2S0/nv > 2S_0/n. The maximum v^=S0/n\hat v = S_0/n is still unique, but a Newton step started beyond 2S0/n2S_0/n moves away from it: there the first derivative (S0−nv)/(2v2)(S_0 - nv)/(2v^2) is negative and the second positive, so v−ℓ′(v)/ℓ′′(v)>vv - \ell'(v)/\ell''(v) > v. In η2=−1/(2v)\eta_2 = -1/(2v) the same function is concave.

Why the exponential family has conjugate priors#

Look at the likelihood as a function of η\eta: it is exp⁡(η⊤∑iu(xi)−nA(η))\exp\big(\eta^\top \sum_i u(x_i) - n A(\eta)\big) times a factor free of η\eta. A prior of the same shape,

p(η∣χ,ν)=1Z(χ,ν)exp⁡(η⊤χ−νA(η)),Z(χ,ν)=∫exp⁡(η⊤χ−νA(η)) dη,\begin{aligned} p(\eta \mid \chi, \nu) &= \frac{1}{Z(\chi, \nu)} \exp\big(\eta^\top \chi - \nu A(\eta)\big), \\ Z(\chi, \nu) &= \int \exp\big(\eta^\top \chi - \nu A(\eta)\big)\, d\eta , \end{aligned}

multiplies with it into the same shape again:

p(η∣X)∝exp⁡(η⊤χ′−ν′A(η)),χ′=χ+∑i=1nu(xi),ν′=ν+n.\begin{aligned} p(\eta \mid X) &\propto \exp\big(\eta^\top \chi' - \nu' A(\eta)\big), \\ \chi' &= \chi + \sum_{i=1}^n u(x_i), \\ \nu' &= \nu + n . \end{aligned}

The prior is the likelihood of ν\nu imaginary observations whose sufficient statistics sum to χ\chi, and the update adds the real ones (Bishop, 2006, Section 2.4.2). It is a proper prior only when Z(χ,ν)Z(\chi, \nu) is finite; for the Bernoulli below this means 0<χ<ν0 < \chi < \nu. With c(X)=∏ih(xi)c(X) = \prod_i h(x_i), the general formulas of the conjugacy section become

p(X∣χ,ν)=∏i=1nh(xi)⋅Z(χ′,ν′)Z(χ,ν),p(x∗∣X)=h(x∗) Z(χ′+u(x∗), ν′+1)Z(χ′,ν′).\begin{aligned} p(X \mid \chi, \nu) &= \prod_{i=1}^n h(x_i) \cdot \frac{Z(\chi', \nu')}{Z(\chi, \nu)}, \\ p(x_* \mid X) &= h(x_*)\, \frac{Z\big(\chi' + u(x_*),\ \nu' + 1\big)}{Z(\chi', \nu')} . \end{aligned}

The beta prior is an instance. For the Bernoulli, A(η)=log⁡(1+eη)A(\eta) = \log(1 + e^\eta) with eη=p/(1−p)e^\eta = p/(1-p), so eηχ=(p1−p)χe^{\eta\chi} = \big(\frac{p}{1-p}\big)^\chi and e−νA(η)=(1−p)νe^{-\nu A(\eta)} = (1 - p)^\nu. The prior density in η\eta is proportional to pχ(1−p)ν−χp^\chi (1-p)^{\nu - \chi}. As a density in pp it gains the Jacobian dη/dp=1/(p(1−p))d\eta/dp = 1/\big(p(1-p)\big):

p(p∣χ,ν)∝pχ−1(1−p)ν−χ−1=Beta(p∣χ, ν−χ).p(p \mid \chi, \nu) \propto p^{\chi - 1} (1 - p)^{\nu - \chi - 1} = \mathrm{Beta}(p \mid \chi,\ \nu - \chi) .

So a=χa = \chi and b=ν−χb = \nu - \chi, and the update χ′=χ+k\chi' = \chi + k, ν′=ν+n\nu' = \nu + n is a′=a+ka' = a + k, b′=b+n−kb' = b + n - k. The Jacobian is why the beta exponents are a−1a - 1 rather than aa, the offset between the two pseudo-count conventions of the Bayesian inference note. For the seven flips, Beta(2,2)\mathrm{Beta}(2, 2) is four imaginary flips with two heads; adding the real ∑ixi=5\sum_i x_i = 5 and n=7n = 7 gives χ′=7\chi' = 7, ν′=11\nu' = 11:

Figure

A conjugate update: add the sufficient statistics

A conjugate update: add the sufficient statisticsA row of seven flips 1 0 1 1 0 1 1 is reduced to the statistics Σx = 5 and n = 7. The prior hyperparameters (2, 4) plus the statistics (5, 7) give (7, 11), which is Beta(7, 4). From it the probability of heads, 0.636, and the evidence, 1/140, are read off.data X: 7 flips1011011ΣΣx = 5n = 7statistics1χ = 2ν = 4priorBeta(2, 2)2+=χ′ = 7ν′ = 11posteriorBeta(7, 4)3P(x = 1 | X) = 0.636χ′/ν′ = 7/11p(X) = 1/140B(7, 4) / B(2, 2)4A conjugate update: add the sufficient statisticsA row of seven flips 1 0 1 1 0 1 1 is reduced to the statistics Σx = 5 and n = 7. The prior hyperparameters (2, 4) plus the statistics (5, 7) give (7, 11), which is Beta(7, 4). From it the probability of heads, 0.636, and the evidence, 1/140, are read off.data X: 7 flips1011011Σ1Σx = 5n = 7statisticsχ = 2ν = 4priorBeta(2, 2)2+=χ′ = 7ν′ = 11posteriorBeta(7, 4)3P(x = 1 | X) = 0.636χ′/ν′ = 7/11p(X) = 1/140B(7, 4) / B(2, 2)4
The beta–Bernoulli update in exponential-family form, for 5 heads in 7 flips. (1) The data reduce to Σx and n. (2) The prior Beta(2, 2) is χ = 2 heads in ν = 4 imaginary flips. (3) The update adds them. (4) The predictive is χ′/ν′; the evidence is a ratio of normalizers.

Conjugacy is not limited to the exponential family. The uniform distribution on [0,θ][0, \theta] has the likelihood θ−n\theta^{-n} for θ≥max⁡ixi\theta \ge \max_i x_i and 0 otherwise; the Pareto prior ∝θ−(α+1)\propto \theta^{-(\alpha + 1)} for θ≥xm\theta \ge x_m multiplies with it into a Pareto with α+n\alpha + n and max⁡(xm,max⁡ixi)\max(x_m, \max_i x_i). For families with a support that does not depend on the parameter, though, a sufficient statistic of fixed size for every nn, and with it this kind of conjugate prior, exists only in the exponential family. This is the Pitman–Koopman–Darmois theorem, which also needs smooth densities; its proof is in Koopman (1936), and Murphy (2023, Section 3.4.5) discusses it.

Mixtures of conjugate priors#

Optional depth: how to keep conjugacy with a more flexible prior. The last section uses it once.

A single conjugate prior can be too rigid: “the coin is probably fair, but it might be anything” is not a beta distribution. A mixture of conjugate priors, p(θ)=∑jwj p(θ∣αj)p(\theta) = \sum_j w_j\, p(\theta \mid \alpha_j), is conjugate too. Bayes’ formula for one component, rearranged, says p(X∣θ) p(θ∣αj)=p(X∣αj) p(θ∣αj′)p(X \mid \theta)\, p(\theta \mid \alpha_j) = p(X \mid \alpha_j)\, p(\theta \mid \alpha_j'). Summing over the components,

p(θ∣X)∝∑jwj p(X∣αj) p(θ∣αj′),p(\theta \mid X) \propto \sum_j w_j\, p(X \mid \alpha_j)\, p(\theta \mid \alpha_j') ,

so each component updates as before, and the weights are reweighted by each component’s evidence and normalized to sum to 1:

p(θ∣X)=∑jwj′ p(θ∣αj′),wj′=wj p(X∣αj)∑lwl p(X∣αl).\begin{aligned} p(\theta \mid X) &= \sum_j w_j'\, p(\theta \mid \alpha_j'), \\ w_j' &= \frac{w_j\, p(X \mid \alpha_j)}{\sum_l w_l\, p(X \mid \alpha_l)} . \end{aligned}

Take the prior 0.5 Beta(20,20)+0.5 Beta(1,1)0.5\, \mathrm{Beta}(20, 20) + 0.5\, \mathrm{Beta}(1, 1) and 9 heads in 10 flips. The components have the evidences B(29,21)/B(20,20)B(29, 21)/B(20, 20) and B(10,2)/B(1,1)B(10, 2)/B(1, 1), and the weights become 0.1560.156 and 0.8440.844: the data have moved belief from “fair” to “anything”. The posterior mean is

0.156⋅2950+0.844⋅1012=0.794.0.156 \cdot \frac{29}{50} + 0.844 \cdot \frac{10}{12} = 0.794 .

With 5 heads in 10, the weights are 0.7070.707 and 0.2930.293 instead. The weight update is already a comparison of two models by their evidence, the subject of the next note.

Posterior predictive distributions#

The predictive averages the likelihood over the posterior. For conjugate pairs it has a closed form, and it is wider than the plug-in prediction at the posterior mean, because it adds the uncertainty about the parameter to the noise of the data.

The beta–binomial#

The number of heads kk in mm future flips, under a Beta(a,b)\mathrm{Beta}(a, b) posterior, has probabilities

P(k∣m)=∫01(mk)fk(1−f)m−k Beta(f∣a,b) df=(mk)B(a+k, b+m−k)B(a,b),\begin{aligned} P(k \mid m) &= \int_0^1 \binom mk f^k (1-f)^{m-k}\, \mathrm{Beta}(f \mid a, b)\, df \\ &= \binom mk \frac{B(a + k,\ b + m - k)}{B(a, b)} , \end{aligned}

the beta–binomial distribution. The first line is the predictive integral, with flips independent given ff; the second collects the powers of ff and 1−f1 - f and uses the definition of BB. Its mean, ma/(a+b)m a/(a + b), is that of a binomial with the posterior mean plugged in. Its variance is larger by the factor (a+b+m)/(a+b+1)(a + b + m)/(a + b + 1):

Var⁡[k]=maa+bba+b⋅a+b+ma+b+1.\operatorname{Var}[k] = m \frac{a}{a+b} \frac{b}{a+b} \cdot \frac{a + b + m}{a + b + 1} .
Derivation of the mean and variance

Write fˉ=a/(a+b)\bar f = a/(a + b). Ratios of beta constants give the moments of ff: E[f]=B(a+1,b)/B(a,b)=fˉ\mathbb E[f] = B(a + 1, b)/B(a, b) = \bar f and E[f2]=B(a+2,b)/B(a,b)=fˉ (a+1)/(a+b+1)\mathbb E[f^2] = B(a + 2, b)/B(a, b) = \bar f\, (a + 1)/(a + b + 1), so Var⁡[f]=fˉ(1−fˉ)/(a+b+1)\operatorname{Var}[f] = \bar f (1 - \bar f)/(a + b + 1). Given ff, kk is binomial with mean mfmf and variance mf(1−f)mf(1 - f). The tower property gives E[k]=mfˉ\mathbb E[k] = m \bar f, and the law of total variance gives

Var⁡[k]=E[mf(1−f)]+Var⁡[mf]=mfˉ(1−fˉ)a+ba+b+1+m2fˉ(1−fˉ)a+b+1=mfˉ(1−fˉ) a+b+ma+b+1,\begin{aligned} \operatorname{Var}[k] &= \mathbb E\big[m f (1 - f)\big] + \operatorname{Var}[m f] \\ &= m \bar f (1 - \bar f) \frac{a + b}{a + b + 1} + \frac{m^2 \bar f (1 - \bar f)}{a + b + 1} \\ &= m \bar f (1 - \bar f)\, \frac{a + b + m}{a + b + 1} , \end{aligned}

where the second line uses E[f(1−f)]=fˉ−Var⁡[f]−fˉ2\mathbb E[f(1 - f)] = \bar f - \operatorname{Var}[f] - \bar f^2.

After the seven flips, Beta(7,4)\mathrm{Beta}(7, 4), the predictive for m=10m = 10 more flips has variance 10⋅711⋅411⋅2112=4.0510 \cdot \frac{7}{11} \cdot \frac{4}{11} \cdot \frac{21}{12} = 4.05, against 2.312.31 for the binomial with p=7/11p = 7/11. The probability of 3 heads or fewer is 0.0890.089 under the predictive and 0.0320.032 under the plug-in.

The Student-t#

Under the normal–gamma posterior, a new observation is x∗=μ+εx_* = \mu + \varepsilon. Given λ\lambda, the mean has variance 1/(κnλ)1/(\kappa_n \lambda) and the independent noise 1/λ1/\lambda, so by the sum of independent Gaussians x∗∣λ∼N(μn,(1+1/κn)/λ)x_* \mid \lambda \sim \mathcal N\big(\mu_n, (1 + 1/\kappa_n)/\lambda\big), a normal with precision τλ\tau \lambda, τ=κn/(κn+1)\tau = \kappa_n/(\kappa_n + 1). Integrating out λ\lambda as for the marginal of μ\mu,

p(x∗∣X)=St(x∗  ∣  μn, bn(κn+1)anκn, 2an).p(x_* \mid X) = \mathrm{St}\Big(x_* \;\Big|\; \mu_n,\ \frac{b_n (\kappa_n + 1)}{a_n \kappa_n},\ 2a_n\Big) .

In the example of five points this is a Student-t with 7 degrees of freedom, centre 1.01.0 and squared scale 2.45⋅7/21=0.8172.45 \cdot 7/21 = 0.817. Plugging in the posterior means, μ=1.0\mu = 1.0 and λ=an/bn\lambda = a_n/b_n, gives N(1.0,0.7)\mathcal N(1.0, 0.7) instead:

Predictive Student-tPlug-in N(1.0,0.7)\mathcal N(1.0, 0.7)
central 95% interval[−1.14,3.14][-1.14, 3.14][−0.64,2.64][-0.64, 2.64]
P(x∗>3)P(x_* > 3)0.0310.0310.00840.0084

The predictive gives almost four times the probability to an observation above 3, because it keeps the possibility that the noise is larger than its estimate. Plugging in the maximum likelihood fit, mean 1.21.2 and variance S/n=0.34S/n = 0.34, would give 0.0010.001.

Figure

The predictive is wider than the plug-in

The predictive is wider than the plug-inLeft, pairs of bars for k = 0 to 10: the beta–binomial is lower in the middle and higher at the ends than the binomial; variances 4.05 and 2.31. Right, a Student-t density with 7 degrees of freedom and a normal density, both centred at 1; the t has heavier tails, with P(x > 3) equal to 0.031 against 0.0084.heads in the next 10 flipsbeta–binomial predictivebinomial, p = 7/1100.10.2012345678910number of heads kvariance 4.05 vs 2.31P(k ≤ 3): 0.089 vs 0.032a new observation xStudent-t predictive, 7 dofnormal, posterior means plugged in00.20.4-2024xP(x > 3):0.031 vs 0.0084The predictive is wider than the plug-inLeft, pairs of bars for k = 0 to 10: the beta–binomial is lower in the middle and higher at the ends than the binomial; variances 4.05 and 2.31. Right, a Student-t density with 7 degrees of freedom and a normal density, both centred at 1; the t has heavier tails, with P(x > 3) equal to 0.031 against 0.0084.heads in the next 10 flipsbeta–binomial predictivebinomial, p = 7/1100.10.2012345678910number of heads kvariance 4.05 vs 2.31P(k ≤ 3): 0.089 vs 0.032a new observation xStudent-t predictive, 7 dofnormal, posterior means plugged in00.20.4-2024xP(x > 3):0.031 vs 0.0084
Predictive (blue) against plug-in (amber). Left: heads in the next 10 flips after Beta(7, 4); same mean 6.36, variance 4.05 against 2.31. Right: a new observation in the normal–gamma example, Student-t with 7 degrees of freedom and squared scale 0.817 against N(1, 0.7). Dashed: x = 3.

A table of conjugate pairs#

Each row follows by the reading of the conjugacy section: write the likelihood as a function of the parameter, multiply by the prior and add the exponents. For the Poisson, λ∑ixie−nλ\lambda^{\sum_i x_i} e^{-n\lambda} times λa−1e−bλ\lambda^{a-1} e^{-b\lambda} gives a+∑ixia + \sum_i x_i and b+nb + n. The predictive of each row is the ratio of normalizers of the conjugacy section; the names follow Wikipedia’s table and Murphy (2023, Section 3.4).

LikelihoodConjugate priorPosterior hyperparametersPredictive
Bernoulli, binomialBeta(a,b)\mathrm{Beta}(a, b)a+k, b+n−ka + k,\ b + n - kbeta–binomial
Categorical, multinomialDir(α)\mathrm{Dir}(\alpha)αk+nk\alpha_k + n_kDirichlet–multinomial
Poisson(λ)(\lambda)Gamma(a,b)\mathrm{Gamma}(a, b)a+∑ixi, b+na + \sum_i x_i,\ b + nnegative binomial
Exponential(λ)(\lambda)Gamma(a,b)\mathrm{Gamma}(a, b)a+n, b+∑ixia + n,\ b + \sum_i x_iLomax (Pareto II)
N(μ,σ2)\mathcal N(\mu, \sigma^2), known σ2\sigma^2N(μ0,τ2)\mathcal N(\mu_0, \tau^2)precisions addnormal
N(μ,1/λ)\mathcal N(\mu, 1/\lambda), known μ\muGamma(a,b)\mathrm{Gamma}(a, b)a+n/2, b+∑i(xi−μ)2/2a + n/2,\ b + \sum_i (x_i - \mu)^2/2Student-t
N(μ,1/λ)\mathcal N(\mu, 1/\lambda), both unknownnormal–gammaκn,μn,an,bn\kappa_n, \mu_n, a_n, b_n aboveStudent-t
Nd(μ,Λ−1)\mathcal N_d(\mu, \Lambda^{-1}), both unknownnormal–Wishartthe same with matricesmultivariate Student-t
Uniform(0,θ)(0, \theta)Pareto(xm,α)(x_m, \alpha)max⁡(xm,max⁡ixi), α+n\max(x_m, \max_i x_i),\ \alpha + n—

Where it breaks: a prior with light tails#

A conjugate prior is chosen for its algebra, and its shape comes with the algebra. The normal prior has light tails, and they decide what happens when the data disagree with it. The example follows Murphy (2023, Section 3.4.6.2), after Berger.

One observation x=5x = 5 comes from N(θ,1)\mathcal N(\theta, 1). The prior belief is that θ\theta has median 0 and quartiles −1-1 and 11. The normal prior with these quartiles has standard deviation 1/0.674=1.481/0.674 = 1.48, variance 2.202.20. The Cauchy prior, a Student-t with one degree of freedom, has the same quartiles but heavy tails. Both state the same belief about the middle of the distribution, and they give different answers:

PriorPosterior mean of θ\theta
normal, variance 2.202.203.443.44
Cauchy4.564.56
0.8⋅0.8 \cdot normal, variance 2.202.20, + 0.2⋅N(0,100)+\ 0.2 \cdot \mathcal N(0, 100)4.444.44

The normal posterior is the precision-weighted average, 5⋅2.20/3.20=3.445 \cdot 2.20/3.20 = 3.44. It sits where neither the prior nor the likelihood puts much belief: the likelihood says θ\theta is within about 2 of 5, and the prior gives θ>3.4\theta > 3.4 a probability of 1%. Under a normal prior, a datum is always pulled towards the prior mean by the same fraction, however surprising it is. A heavy-tailed prior gives up when the data are far away; the Cauchy posterior stays near the observation. The posterior mode shows why. It solves (x−θ)+ddθlog⁡p(θ)=0(x - \theta) + \frac{d}{d\theta} \log p(\theta) = 0, so the prior pulls the estimate back by the slope of its log-density. For the normal prior the slope −θ/2.20-\theta/2.20 grows with θ\theta, and the pull is 1.561.56. For the Cauchy, the slope −2θ/(1+θ2)-2\theta/(1 + \theta^2) fades for large θ\theta: the mode is 4.584.58, a pull of only 0.420.42.

The Cauchy prior is not conjugate, and its posterior needs numerical integration. A mixture of conjugate priors is a conjugate compromise: a broad component with a small weight absorbs a surprising observation. In the third row, each component’s evidence is the linear-Gaussian marginal N(5∣0,v+1)\mathcal N(5 \mid 0, v + 1) with v=2.20v = 2.20 or 100100; reweighting by them moves the weight of the broad component from 0.20.2 to 0.660.66, and the posterior mean to 4.444.44.

Two other limits follow from the same algebra. Models built from blocks rarely have a usable conjugate prior as a whole: for a logistic regression, a mixture or a neural network, no prior family with a known normalizer stays closed under the update. Conjugacy then survives inside the blocks, conditional on the other variables, which is what variational inference and Gibbs sampling exploit. And the normal–gamma prior ties the uncertainty of the mean to the noise variance. When prior knowledge about the mean is independent of the noise level, the conjugate prior cannot express it.

What you should remember#

  • Conjugate: the posterior stays in the prior’s family, and learning updates a few hyperparameters, in any order and batching.
  • Beta–Bernoulli: a+ka + k, b+n−kb + n - k; the evidence B(a+k,b+n−k)/B(a,b)B(a + k, b + n - k)/B(a, b) is the product of the one-step predictives. Dirichlet: (αk+nk)/(α0+n)(\alpha_k + n_k)/(\alpha_0 + n) is add-α\alpha smoothing.
  • Unknown mean and precision need the normal–gamma prior, which ties them; the mean and the predictive are Student-t.
  • Exponential family: h(x)exp⁡(η⊤u(x)−A(η))h(x) \exp(\eta^\top u(x) - A(\eta)), with ∇A=E[u]\nabla A = \mathbb E[u] and ∇2A=Cov⁡[u]\nabla^2 A = \operatorname{Cov}[u]; maximum likelihood matches the sample means of uu.
  • Its conjugate prior is ∝exp⁡(η⊤χ−νA(η))\propto \exp(\eta^\top \chi - \nu A(\eta)): add ∑iu(xi)\sum_i u(x_i) to χ\chi and nn to ν\nu.
  • Predictives are wider than plug-ins. A normal prior shrinks every datum by the same fraction, however far it lies.

Code#

Sequential updates checked against the batch formulas, the evidence as a product of predictives, the Dirichlet example, the normal–gamma posterior against the grid and its predictive against Monte Carlo, the derivatives of the log-partition function, the beta–binomial predictive, a mixture prior, and the normal against the Cauchy prior. Seeds are fixed; the script runs in about a second, and exact numbers can differ in the last digit across platforms and library versions.

import numpy as np
from scipy import stats, special, integrate, optimize

rng = np.random.default_rng(0)
lbeta = special.betaln

# beta-Bernoulli: one flip at a time gives the batch posterior, and the product of the
# one-step predictives is the evidence B(a + k, b + n - k) / B(a, b)
x = np.array([1, 0, 1, 1, 0, 1, 1])                    # 5 heads in 7 flips
a, b, log_ev = 2.0, 2.0, 0.0                           # prior Beta(2, 2)
for xi in x:
    p_head = a / (a + b)                               # predictive of the next flip
    log_ev += np.log(p_head if xi else 1 - p_head)
    a, b = a + xi, b + 1 - xi                          # conjugate update
print(a, b, round(a / (a + b), 3))                     # 7.0 4.0 0.636
print(round(np.exp(log_ev), 6), round(np.exp(lbeta(7, 4) - lbeta(2, 2)), 6))   # 0.007143 0.007143: 1/140 both ways

# Dirichlet-categorical: counts (5, 2, 0, 1) with a uniform Dir(1, 1, 1, 1) prior
alpha, counts = np.ones(4), np.array([5, 2, 0, 1])
post = alpha + counts
print((post / post.sum()).round(3))                    # [0.5   0.25  0.083 0.167]: the unseen category keeps 1/12
log_ev = (special.gammaln(alpha.sum()) - special.gammaln(post.sum())
          + (special.gammaln(post) - special.gammaln(alpha)).sum())
print(round(1 / np.exp(log_ev)))                       # 27720: the evidence of the sequence is 1/27720

# normal-gamma: unknown mean and precision, prior mu | lam ~ N(m0, 1/(k0 lam)), lam ~ Gamma(a0, rate b0)
def ng_update(m, k, a, b, xs):
    n, xbar = len(xs), np.mean(xs)
    S = ((xs - xbar) ** 2).sum()
    return ((k * m + n * xbar) / (k + n), k + n, a + n / 2,
            b + S / 2 + k * n * (xbar - m) ** 2 / (2 * (k + n)))

xs = np.array([1.2, 0.4, 2.1, 1.5, 0.8])
batch = ng_update(0.0, 1.0, 1.0, 1.0, xs)
seq = (0.0, 1.0, 1.0, 1.0)
for xi in xs:
    seq = ng_update(*seq, np.array([xi]))
print(np.round(batch, 4), np.allclose(batch, seq))     # [1.   6.   3.5  2.45] True

# check against brute force: the posterior on a grid of (mu, lam), marginalized over lam
mn, kn, an, bn = batch
mu, lam = np.linspace(-2, 4, 1201), np.linspace(1e-4, 8, 1600)
M, L = np.meshgrid(mu, lam, indexing='ij')
log_joint = (stats.norm.logpdf(M, 0, 1 / np.sqrt(L)) + stats.gamma.logpdf(L, 1, scale=1)
             + stats.norm.logpdf(xs[:, None, None], M, 1 / np.sqrt(L)).sum(axis=0))
grid = np.exp(log_joint - log_joint.max()).sum(axis=1)
grid /= grid.sum() * (mu[1] - mu[0])                   # the marginal posterior density of mu on the grid
exact = stats.t(2 * an, loc=mn, scale=np.sqrt(bn / (an * kn))).pdf(mu)
print(round(float(np.abs(grid - exact).max()), 4))     # 0.0001: the closed-form Student-t marginal matches

# the posterior predictive is a Student-t; a Monte Carlo check by sampling lam, mu, then x
scale2 = bn * (kn + 1) / (an * kn)                     # the predictive scale squared
pred = stats.t(2 * an, loc=mn, scale=np.sqrt(scale2))
lam_s = rng.gamma(an, 1 / bn, size=400_000)
x_s = rng.normal(rng.normal(mn, 1 / np.sqrt(kn * lam_s)), 1 / np.sqrt(lam_s))
print(round(scale2, 4), round(pred.sf(3), 4), round((x_s > 3).mean(), 4))   # 0.8167 0.0313 0.0312
plug = stats.norm(mn, np.sqrt(bn / an))                # plug in the posterior means of mu and of lam
print(pred.ppf([0.025, 0.975]).round(2), plug.ppf([0.025, 0.975]).round(2), round(plug.sf(3), 4))
# [-1.14  3.14] [-0.64  2.64] 0.0084
print(round(stats.norm(1.2, np.sqrt(0.34)).sf(3), 4))  # 0.001: the plug-in maximum likelihood fit, variance S/n

# the log-partition function: its gradient is E[u(x)], its second derivative Var[u(x)]
A = lambda eta: np.log1p(np.exp(eta))                  # Bernoulli, eta = log(p / (1 - p))
eta, h = np.log(0.3 / 0.7), 1e-4
print(round((A(eta + h) - A(eta - h)) / (2 * h), 4), round((A(eta + h) - 2 * A(eta) + A(eta - h)) / h ** 2, 4))   # 0.3 0.21

# beta-binomial predictive for the next 10 flips after Beta(7, 4), against the plug-in binomial
bb, bi = stats.betabinom(10, 7, 4), stats.binom(10, 7 / 11)
print(round(bb.var(), 3), round(bi.var(), 3), round(bb.cdf(3), 3), round(bi.cdf(3), 3))   # 4.05 2.314 0.089 0.032

# a mixture of conjugate priors is conjugate: 0.5 Beta(20, 20) + 0.5 Beta(1, 1), then 9 heads in 10
w = np.array([0.5 * np.exp(lbeta(29, 21) - lbeta(20, 20)), 0.5 * np.exp(lbeta(10, 2) - lbeta(1, 1))])
w /= w.sum()
print(w.round(3), round(w @ [29 / 50, 10 / 12], 3))     # [0.156 0.844] 0.794
w5 = np.array([np.exp(lbeta(25, 25) - lbeta(20, 20)), np.exp(lbeta(6, 6) - lbeta(1, 1))])
print((w5 / w5.sum()).round(3))                        # [0.707 0.293]: with 5 heads in 10, "fair" gains

# a light-tailed prior: x = 5 from N(theta, 1), priors with median 0 and quartiles -1 and 1
x, v = 5.0, (1 / stats.norm.ppf(0.75)) ** 2            # the normal prior's variance, 2.198
lik = lambda th: stats.norm.pdf(x, th, 1)
Z = integrate.quad(lambda th: stats.cauchy.pdf(th) * lik(th), -60, 60, points=[0, 5])[0]
m_cauchy = integrate.quad(lambda th: th * stats.cauchy.pdf(th) * lik(th), -60, 60, points=[0, 5])[0] / Z
ev = np.array([0.8 * stats.norm.pdf(x, 0, np.sqrt(v + 1)), 0.2 * stats.norm.pdf(x, 0, np.sqrt(101))])
w = ev / ev.sum()                                      # posterior weights of the two normal components
print(round(v, 2), round(v / (v + 1) * x, 2), round(m_cauchy, 2), w.round(2), round(w @ [v / (v + 1) * x, 100 / 101 * x], 2))
# 2.2 3.44 4.56 [0.34 0.66] 4.44
mode = lambda logprior: optimize.minimize_scalar(lambda th: -(stats.norm.logpdf(x, th, 1) + logprior(th)),
                                                 bounds=(0, 6), method='bounded').x
print(round(stats.norm(0, np.sqrt(v)).sf(3.4), 2), round(mode(stats.cauchy.logpdf), 2))   # 0.01 4.58

Next#

The evidence appeared in every section as a by-product: the normalizer of the posterior, a ratio of two constants, the product of one-step predictions, the weight of a mixture component. The next note makes it the main object. Comparing the evidence of two models compares how well each predicted the data before seeing them, and this comparison prefers the simplest model that explains the data without any penalty added by hand.

References#