AI Wiki中文/EN

Conjugate priors

共轭先验

Derive Beta, Dirichlet and Gamma updates, interpret prior strength, and check which likelihood assumptions preserve conjugacy.

On this pageIntuitionMathematics & methodImplementationLimitationsExercisesResearch connections

Update the distribution by changing a few numbers

A small service has produced three successes and one failure. You modeled its unknown success probability pp with a Beta(2,2) prior: centered at one half, without ruling out other interior values. After those four observations, the posterior is Beta(5,3). Both its location and its spread can be read from the updated parameters. You did not need to build a numerical integration routine to identify the result.

This is conjugacy. A prior family is conjugate to a specified likelihood family when updating any member with admissible data keeps the posterior in that same prior family. Beta is conjugate to the Bernoulli likelihood; it is not “conjugate” in isolation. The posterior is Beta, not Bernoulli, because it describes the unknown probability rather than the next binary outcome. MML, Definition 6.13 gives the closure property; MIT 15.097, Section 3 states it for prior and likelihood families.

Match the kernel, then supply the normalizer

Bayes’ rule says the posterior is proportional to prior times likelihood. Here a kernel means the part of a density that depends on the parameter being inferred. A parameter-independent factor can be omitted while identifying the family, but it still matters when calculating the marginal probability of the observed data.

Suppose binary observations are conditionally independent given a common pp, with ss successes and ff failures. For a,b>0a,b>0, multiplying the Bernoulli likelihood by the Beta prior gives

π(p∣D)∝ps(1−p)fpa−1(1−p)b−1=pa+s−1(1−p)b+f−1.\pi(p\mid D)\propto p^s(1-p)^f p^{a-1}(1-p)^{b-1}=p^{a+s-1}(1-p)^{b+f-1}.

The result is Beta(a+s,b+fa+s,b+f), with normalizer B(a+s,b+f)B(a+s,b+f). Here B(u,v)=Γ(u)Γ(v)/Γ(u+v)B(u,v)=\Gamma(u)\Gamma(v)/\Gamma(u+v) is the Beta function. The evidence for a particular ordered sequence is B(a+s,b+f)/B(a,b)B(a+s,b+f)/B(a,b). If the observation is instead a binomial count with fixed total, its evidence includes the binomial coefficient; the posterior is unchanged because that coefficient does not depend on pp. MML, Examples 6.11–6.12 derives both updates.

For n=s+f>0n=s+f>0, write the posterior mean as

E[p∣D]=a+sa+b+n=a+ba+b+naa+b+na+b+nsn.E[p\mid D]=\frac{a+s}{a+b+n}=\frac{a+b}{a+b+n}\frac{a}{a+b}+\frac{n}{a+b+n}\frac{s}{n}.

The prior mean and the observed proportion receive weights based on prior concentration a+ba+b and sample size nn. In the opening example, each weight is one half, giving 5/85/8. The language of “prior counts” describes this algebraic influence; it does not mean fictional observations were actually collected. An interpretation based on the interior mode instead involves a−1,b−1a-1,b-1, so pseudo-count conventions must be stated rather than mixed together.

A categorical model extends the same calculation. Let p=(p1,…,pK)p=(p_1,\ldots,p_K) lie on the simplex, and let all Dirichlet shapes αi>0\alpha_i>0. For conditionally independent categorical observations with counts nin_i, the likelihood kernel is ∏ipini\prod_i p_i^{n_i}. Multiplying exponents yields

p∣D∼Dirichlet⁡(α1+n1,…,αK+nK),E[pi∣D]=αi+niα0+N,p\mid D\sim\operatorname{Dirichlet}(\alpha_1+n_1,\ldots,\alpha_K+n_K),\qquad E[p_i\mid D]=\frac{\alpha_i+n_i}{\alpha_0+N},

where α0=∑iαi\alpha_0=\sum_i\alpha_i and N=∑iniN=\sum_i n_i. Fixed-total multinomial counts have the same update. For prior (1,2,1)(1,2,1) and counts (2,0,3)(2,0,3), the posterior is (3,2,4)(3,2,4), with mean (1/3,2/9,4/9)(1/3,2/9,4/9). An unobserved category keeps positive posterior mean because its prior shape was positive. This is the multinomial–Dirichlet pair listed in MML, Table 6.2.

For counts per unit time, specify the Gamma convention before updating. We use shape a>0a>0 and rate b>0b>0:

π(λ)=baΓ(a)λa−1e−bλ,λ>0,E[λ]=ab,Var⁡(λ)=ab2.\pi(\lambda)=\frac{b^a}{\Gamma(a)}\lambda^{a-1}e^{-b\lambda},\quad\lambda>0,\qquad E[\lambda]=\frac ab,\qquad\operatorname{Var}(\lambda)=\frac a{b^2}.

The alternative Gamma scale is 1/b1/b. Let known exposures ti>0t_i>0 accompany counts yi∈{0,1,…}y_i\in\{0,1,\ldots\}, with Yi∣λ∼Poisson⁡(tiλ)Y_i\mid\lambda\sim\operatorname{Poisson}(t_i\lambda) conditionally independently. The likelihood kernel is λ∑iyie−λ∑iti\lambda^{\sum_i y_i}e^{-\lambda\sum_i t_i}, so

λ∣D∼Gamma⁡(a+∑iyi, b+∑iti)(shape, rate).\lambda\mid D\sim\operatorname{Gamma}\left(a+\sum_i y_i,\ b+\sum_i t_i\right)\quad\text{(shape, rate)}.

Unit exposures recover the rate update b+nb+n in MIT’s conjugacy table. The exposure generalization follows directly from the displayed Poisson kernel. With prior Gamma(2,1), counts (1,4)(1,4) over exposures (1,2)(1,2) yield Gamma(7,4), mean 7/47/4, and variance 7/167/16. Adding the number of windows instead of their total exposure would give the wrong rate. If exposure is measured in hours and λ\lambda in events per hour, bb is expressed in hours too.

Three exact updates with explicit input contracts

The complete standard-library program uses integers and exact fractions. It accepts positive rational hyperparameters, nonnegative integer counts, and strictly positive rational exposures. Empty observations leave the prior unchanged. An interval of zero exposure is excluded by this interface; it can contain only zero events in the stated model and can be omitted before calling the function.

from fractions import Fraction as F

def positive(value):
    if type(value) is not int and not isinstance(value, F):
        raise ValueError("use integer or Fraction hyperparameters")
    value = F(value)
    if value <= 0:
        raise ValueError("hyperparameters must be positive")
    return value

def count(value):
    if type(value) is not int or value < 0:
        raise ValueError("counts must be nonnegative integers")
    return value

def beta_update(a, b, successes, failures):
    return positive(a)+count(successes), positive(b)+count(failures)

def dirichlet_update(alpha, counts):
    a = tuple(positive(x) for x in alpha)
    n = tuple(count(x) for x in counts)
    if len(a) < 2 or len(a) != len(n):
        raise ValueError("matching vectors with at least two categories required")
    return tuple(x+y for x,y in zip(a,n))

def gamma_poisson_update(shape, rate, counts, exposures):
    a, b = positive(shape), positive(rate)
    y = tuple(count(x) for x in counts)
    t = tuple(positive(x) for x in exposures)
    if len(y) != len(t):
        raise ValueError("one strictly positive exposure per count required")
    return a+sum(y), b+sum(t)

a,b = beta_update(2,2,3,1)
assert (a,b) == (5,3)
assert a/(a+b) == F(5,8)
assert beta_update(*beta_update(2,2,1,1),2,0) == (a,b)
assert dirichlet_update((1,2,1),(2,0,3)) == (3,2,4)
g_shape,g_rate = gamma_poisson_update(2,1,(1,4),(1,2))
assert (g_shape,g_rate) == (7,4)
assert g_shape/g_rate == F(7,4)
assert gamma_poisson_update(2,1,(),()) == (2,1)
print((a,b), (g_shape,g_rate))

The Beta update takes O(1)O(1) arithmetic and storage once the counts are available. The Dirichlet update takes O(K)O(K) operations and output storage. The Gamma update takes O(n)O(n) operations and, as written, O(n)O(n) storage because it validates copied tuples. Accumulating count and exposure totals in a streaming reader would need only constant extra storage. These are rational arithmetic counts; bit costs grow with the integer sizes.

Sequential updates and one batch update agree because these sufficient statistics add. Changing observation order changes neither result. This relies on the stated fixed-parameter, conditionally independent observation model. A copied log entry must not count as a new independent trial; the program cannot infer that from the supplied totals.

Convenient algebra is a modeling restriction

A larger posterior concentration does not imply that every realized update reduces posterior variance. A Beta(1,99) prior has variance 99/(1002⋅101)99/(100^2\cdot101). After one success it becomes Beta(2,99), with variance 198/(1012⋅102)198/(101^2\cdot102), which is larger. The mean has moved away from the boundary. The variance decreases with concentration when the mean is held fixed; a data update generally changes both.

All priors here are proper. Zero or negative shapes are not ordinary members of these families. Using an improper limiting prior requires a separate proof that the posterior normalizes for the observed data, especially an empty or one-sided sample. Positive shapes also exclude a literal point mass at p=0p=0 or p=1p=1; if exact impossibility is part of the hypothesis, that needs an explicit discrete component.

Conjugacy belongs to the chosen likelihood. Replacing a common Bernoulli probability with logistic regression coefficients does not preserve the simple Beta update. Different groups may need different probabilities, and a changing event rate may require a time-dependent model. Pooling their totals is a substantive assumption about shared parameters, not a benefit that comes free with the formula.

In an exponential-family model, likelihood multiplication often just adds sufficient statistics to a compatible prior kernel. This explains many conjugate constructions, but normalizability and computational usefulness still need checking. MIT, Section 3.1 derives the kernel construction and notes that its normalizing integral need not be easy to compute. Do not read family closure as a guarantee that every Bayesian task becomes a few additions.

Update the assumptions as carefully as the counts

  1. Start with Beta(2,2), then observe three successes and one failure. What are the posterior and its mean? Answer: Beta(5,3), with mean 5/85/8. Applying a batch of one success and one failure, followed by two successes, gives the same result.
  2. With Dirichlet prior (1,2,1)(1,2,1) and counts (2,0,3)(2,0,3), does the second category receive posterior probability zero? Answer: no. The posterior shapes are (3,2,4)(3,2,4) and its mean weight is 2/92/9. Zero observed count is not zero underlying probability.
  3. Gamma prior shape 2, rate 1 is updated with counts (1,4)(1,4) over exposures (1,2)(1,2). Which posterior rate is correct: 3 or 4? Answer: 4. Exposure totals 3, which adds to the prior rate 1; the posterior shape is 7. In shape–scale notation the posterior scale is 1/41/4.
  4. A success contradicts a prior concentrated near zero. Must its posterior variance decrease? Answer: no. Beta(1,99) becomes Beta(2,99); the variance ratio is 20000/10302>120000/10302>1. Increased concentration alone does not account for the changing mean.

Use closed forms to check harder inference

Conjugate cases make useful reference problems for numerical integration and sampling. Compare a numerical posterior’s normalization, moments, and sequential update against the exact answer before trusting it on a model without a closed form. Then check whether the prior produces plausible observations and whether the fitted observation model reproduces relevant features of the data. Posterior prediction is the next step: it integrates the observation law against this entire posterior, rather than treating its mean as a known parameter.

Make a prediction, then check

A Gamma prior has shape 2 and rate 1; counts 1 and 4 are observed over exposures 1 and 2. What are the posterior parameters?

Choose one answer

Learning objectives

  • Identify conjugacy relative to a likelihood family and distinguish posterior and observation distributions.
  • Derive Beta, Dirichlet and exposure-aware Gamma-Poisson updates and explain prior strength and rate convention.
  • Check sequential updates, valid parameter domains and a counterexample to posterior variance shrinking after every observation.

Prerequisites & connections

Explore related knowledge →

References

  1. Mathematics for Machine Learning — mathematical foundations (2024-01-15 draft)
    Marc Peter Deisenroth; A. Aldo Faisal; Cheng Soon Ong · 2020
  2. 15.097 — Probabilistic Modeling and Bayesian Analysis
    Ben Letham; Cynthia Rudin · 2012

Version1 · Editorial status: Recorded technical checks completed

View technical check record (AI)

Codex · 2026-09-05 · Codex multi-agent technical check: primary-source verification, derivation and numerical assertions, bilingual comparison, and review by another agent or the parent; no independent human peer review.

  • Read MML and MIT sources and re-derived all three conjugate kernels, normalizer relations and the Gamma shape–rate/exposure update.
  • Independently checked Beta, Dirichlet and Gamma updates by density ratios and integration, including empty data, sequential updates, unit changes and invalid inputs.
  • Recalculated the variance increase from Beta(1,99) to Beta(2,99) and compared all bilingual equations, code and four answered exercises.
  • Independent cross-review checked Gamma mean and variance scaling after changing exposure units; Chinese terminology was standardized to proper/improper priors to avoid confusion with normal distributions.
  • The parent executed all 30 new checks and all 55 combined probability/inference tests; bilingual code, display equations, six main anchors, citations and four answered exercises were additionally compared.

Source locations checked:

  • Mathematics for Machine Learning — mathematical foundations (2024-01-15 draft) · 2024-01-15 draft, PDF 214–216 / printed 208–210, Definition 6.13, Examples 6.11–6.12 and Table 6.2: closure, Beta-Bernoulli/Binomial kernels, multinomial–Dirichlet pairing. PDF 213 / printed 207, equations 6.98–6.101: Beta/Gamma normalization and variance; local text actually read in this task family.
  • 15.097 — Probabilistic Modeling and Bayesian Analysis · PDF pp.9–14, Section 3 definition 3 and equations 13–15 (conditional prediction and Beta posterior), p.12 conjugate table including Gamma-Poisson rate update, Section 3.1 construction and warning that the normalizer may remain difficult. Actual fetched text read. Did not repeat unconditional consistency assertions or the broad converse claim on p.14; exposure generalization and variance counterexample independently derived.

Related topics

No matches. Try a synonym or acronym.

0 results shown

Wrap the whole query in double quotes for a phrase match.