TExcelTAD
Home › Math for Machine Learning › Conjugacy and the Exponential Family

Conjugacy and the Exponential Family

Bayesian updating is easy when the posterior has the same form as the prior: then learning is just updating a few numbers. Such priors are called conjugate. Most standard distributions (Bernoulli, Gaussian, Poisson, Beta, Gamma, categorical) belong to one family, the exponential family, which explains why conjugate priors exist and why their sufficient statistics are simple counts and sums.

Beta-Bernoulli: the model example

A coin with unknown bias μ\mu. Prior: μ∼Beta⁡(α,β)\mu \sim \operatorname{Beta}(\alpha, \beta), with density

p(μ)=Γ(α+β)Γ(α)Γ(β) μα−1(1−μ)β−1p(\mu) = \frac{\Gamma(\alpha + \beta)}{\Gamma(\alpha)\Gamma(\beta)}\,\mu^{\alpha - 1}(1 - \mu)^{\beta - 1}

Observe hh heads and tt tails. The likelihood is μh(1−μ)t\mu^h(1 - \mu)^t, so

p(μ∣data)∝μh(1−μ)t⋅μα−1(1−μ)β−1=μα+h−1(1−μ)β+t−1p(\mu \mid \text{data}) \propto \mu^{h}(1 - \mu)^{t} \cdot \mu^{\alpha - 1}(1 - \mu)^{\beta - 1} = \mu^{\alpha + h - 1}(1 - \mu)^{\beta + t - 1}

The posterior is Beta⁡(α+h,β+t)\operatorname{Beta}(\alpha + h, \beta + t): add the heads to α\alpha and the tails to β\beta. The prior acts like α\alpha and β\beta imaginary pseudo-counts. The posterior mean is α+hα+β+h+t\frac{\alpha + h}{\alpha + \beta + h + t}.

python · try it yourself
import numpy as np
from math import lgamma

def beta_logpdf(mu, a, b):
    return lgamma(a + b) - lgamma(a) - lgamma(b) + (a - 1) * np.log(mu) + (b - 1) * np.log(1 - mu)

a, b = 2.0, 2.0                          # mild prior belief in a fair coin
flips = [1, 1, 0, 1, 1, 1, 0, 1]         # 6 heads, 2 tails
for i, f in enumerate(flips, 1):
    a, b = a + f, b + (1 - f)
    if i in (1, 4, 8):
        print(f"after {i} flips: Beta({a:.0f}, {b:.0f}), posterior mean {a / (a + b):.3f}")
# conjugacy check: normalized prior x likelihood on a grid equals the Beta(8, 4) density
mu = np.linspace(0.001, 0.999, 999); dmu = mu[1] - mu[0]
unnorm = np.exp(beta_logpdf(mu, 2, 2)) * mu**6 * (1 - mu)**2
grid_post = unnorm / (unnorm.sum() * dmu)
print("max difference to Beta(8,4):", round(float(np.max(np.abs(grid_post - np.exp(beta_logpdf(mu, 8, 4))))), 3))
after 1 flips: Beta(3, 2), posterior mean 0.600
after 4 flips: Beta(5, 3), posterior mean 0.625
after 8 flips: Beta(8, 4), posterior mean 0.667
max difference to Beta(8,4): 0.0

Other conjugate pairs

Likelihood Conjugate prior Posterior update
Bernoulli / binomial Beta(α,β\alpha, \beta) add successes and failures
categorical / multinomial Dirichlet(α\boldsymbol{\alpha}) add the class counts to α\boldsymbol{\alpha}
Poisson Gamma add the total count and the number of observations
Gaussian, known variance Gaussian on the mean precision-weighted average

The Dirichlet-categorical pair is Laplace (add-one) smoothing in disguise: with αk=1\alpha_k = 1, the posterior mean of class kk is nk+1N+K\frac{n_k + 1}{N + K}, so unseen words in a naive Bayes spam filter do not get probability 0.

The exponential family

A family of distributions is an exponential family if its densities can be written as

p(x∣θ)=h(x)exp⁡ ⁣(⟨θ,ϕ(x)⟩−A(θ))p(x \mid \boldsymbol{\theta}) = h(x)\exp\!\big(\langle \boldsymbol{\theta}, \boldsymbol{\phi}(x) \rangle - A(\boldsymbol{\theta})\big)

with natural parameters θ\boldsymbol{\theta}, sufficient statistics ϕ(x)\boldsymbol{\phi}(x) and log-partition function A(θ)A(\boldsymbol{\theta}). For the Bernoulli,

μx(1−μ)1−x=exp⁡ ⁣(xlog⁡μ1−μ+log⁡(1−μ))\mu^x(1 - \mu)^{1-x} = \exp\!\big(x\log\tfrac{\mu}{1 - \mu} + \log(1 - \mu)\big)

so ϕ(x)=x\phi(x) = x, θ=log⁡μ1−μ\theta = \log\frac{\mu}{1 - \mu} (the logit) and μ=σ(θ)\mu = \sigma(\theta), the sigmoid. That is why logistic regression models the logit as a linear function: it is the Bernoulli's natural parameter. The same calculation for the categorical gives the softmax.

Useful facts: the gradient of AA is the mean of ϕ(x)\boldsymbol{\phi}(x), all information in a dataset about θ\boldsymbol{\theta} is in ∑nϕ(xn)\sum_n \boldsymbol{\phi}(x_n), and every exponential family has a conjugate prior.

python · try it yourself
import numpy as np

theta = 0.8                                   # natural parameter (logit)
A = lambda t: np.log1p(np.exp(t))             # Bernoulli log-partition
dA = (A(theta + 1e-6) - A(theta - 1e-6)) / 2e-6
print("A'(theta) =", round(dA, 6), " sigmoid(theta) = mean =", round(1 / (1 + np.exp(-theta)), 6))
A'(theta) = 0.689974  sigmoid(theta) = mean = 0.689974

In software

  • Generalized linear models (logistic, Poisson regression) use the natural parameter as the linear predictor; statsmodels.GLM is organized by exponential family.
  • Naive Bayes in scikit-learn has an alpha smoothing parameter: the Dirichlet pseudo-count.
  • Thompson sampling for A/B tests keeps a Beta posterior per variant and samples from it.

Exercises

Exercise 1: Update a Beta

Prior Beta⁡(1,1)\operatorname{Beta}(1, 1) (uniform). You see 3 successes and 7 failures. What is the posterior and its mean?

Answer

Beta⁡(4,8)\operatorname{Beta}(4, 8), mean 13\frac{1}{3}.

Solution

Add counts: α=1+3\alpha = 1 + 3, β=1+7\beta = 1 + 7. Mean 4/124/12. (The maximum-likelihood estimate would be 0.30.3.)

Exercise 2: Add-one smoothing

A toy spam vocabulary has K=2K = 2 word types. Among N=98N = 98 spam words, one type never appears. With add-one smoothing (αk=1\alpha_k = 1), what probability does it get?

Answer

1100\frac{1}{100}.

Solution

nk+1N+K=0+198+2=0.01\frac{n_k + 1}{N + K} = \frac{0 + 1}{98 + 2} = 0.01, instead of 0.

Exercise 3: Thompson sampling (code)

Two ad variants have Beta posteriors Beta⁡(13,89)\operatorname{Beta}(13, 89) and Beta⁡(18,84)\operatorname{Beta}(18, 84). Estimate by sampling the probability that variant B has the higher click rate.

Answer

About 0.84.

Solution

Draw from both posteriors and count how often B wins.

python · try it yourself
import numpy as np
rng = np.random.default_rng(0)
a = rng.beta(13, 89, size=200000); b = rng.beta(18, 84, size=200000)
print(round(float(np.mean(b > a)), 2))
0.84

Test yourself

With a Beta⁡(α,β)\operatorname{Beta}(\alpha, \beta) prior and hh heads, tt tails, the posterior is…

  1. Beta⁡(αh,βt)\operatorname{Beta}(\alpha h, \beta t)
  2. Beta⁡(α+h,β+t)\operatorname{Beta}(\alpha + h, \beta + t)
  3. Beta⁡(h,t)\operatorname{Beta}(h, t)
  4. a Gaussian

The natural parameter of the Bernoulli distribution is…

  1. μ\mu
  2. the logit log⁡μ1−μ\log\frac{\mu}{1 - \mu}
  3. μ2\mu^2
  4. 1−μ1 - \mu

What is the advantage of a conjugate prior?

  1. It is always correct
  2. The posterior has the same form, so updating is a closed-form parameter change
  3. It removes the need for data
  4. It makes the likelihood Gaussian