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 . Prior: , with density
Observe heads and tails. The likelihood is , so
The posterior is : add the heads to and the tails to . The prior acts like and imaginary pseudo-counts. The posterior mean is .
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() | add successes and failures |
| categorical / multinomial | Dirichlet() | add the class counts to |
| 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 , the posterior mean of class is , 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
with natural parameters , sufficient statistics and log-partition function . For the Bernoulli,
so , (the logit) and , 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 is the mean of , all information in a dataset about is in , and every exponential family has a conjugate prior.
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.GLMis organized by exponential family. - Naive Bayes in scikit-learn has an
alphasmoothing 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 (uniform). You see 3 successes and 7 failures. What is the posterior and its mean?
Answer
, mean .
Solution
Add counts: , . Mean . (The maximum-likelihood estimate would be .)
Exercise 2: Add-one smoothing
A toy spam vocabulary has word types. Among spam words, one type never appears. With add-one smoothing (), what probability does it get?
Answer
.
Solution
, instead of 0.
Exercise 3: Thompson sampling (code)
Two ad variants have Beta posteriors and . 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.
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 prior and heads, tails, the posterior is…
- a Gaussian
The natural parameter of the Bernoulli distribution is…
- the logit
What is the advantage of a conjugate prior?
- It is always correct
- The posterior has the same form, so updating is a closed-form parameter change
- It removes the need for data
- It makes the likelihood Gaussian