Beta and Dirichlet distributions
Beta 与 Dirichlet 分布
Model uncertainty about probabilities, derive simplex moments, and separate concentration from mean proportions.
beta-dirichletA probability can itself be uncertain
Imagine a three-button interface. You need probabilities for the next click, but a week of observations may not justify treating one estimated vector as exact. The categorical model describes which button gets clicked. A Dirichlet distribution describes uncertainty about the whole probability vector. These are different random objects: one click is a category; one Dirichlet draw is a list of proportions that sums to one.
For two outcomes, keeping the first proportion is enough because the second is its complement. This gives the Beta distribution. A Beta(2,2) model favors probabilities near one half, yet still allows values throughout the interval. Its density at one half is 1.5. Nothing has a 150% chance: a density becomes a probability only after integration over an interval.
From a normalizing integral to a distribution on a simplex
Let . For , the Beta density is
Here and . Positive shapes make the endpoint singularities integrable. These definitions and the Beta mean and variance appear in MML, Example 6.10; the standardized density is also specified in SciPy’s Beta documentation.
The normalizer can be derived rather than memorized. In the product of two Gamma integrals, substitute , . The absolute Jacobian is . The integral separates into a Gamma integral in and a Beta integral in , giving .
Endpoint behavior depends on the exponents. Near zero, the density tends to infinity if , tends to if , and tends to zero if . At one, exchange and . Even an infinite limiting density gives zero probability to that exact endpoint: the Beta law has no atoms. Its closed support is , while a draw lies in with probability one. Beta(1,1) is uniform; both shapes below one favor the two ends; both above one give an interior mode .
For , let every and write . A Dirichlet vector has and almost surely. Its density is
This is a density with respect to the first coordinates, with ; it is not a full-dimensional density on . The support’s closure includes the faces, but the distribution assigns them zero probability. SciPy’s Dirichlet documentation gives the simplex restriction and Gamma normalizer. For , substitution of recovers Beta().
The same change of variables explains the higher-dimensional normalizer. Put in a product of Gamma integrals. The absolute Jacobian is . The radial integral contributes , leaving the simplex integral . This also shows why normalizing independent Gamma variables with shapes and a shared scale produces a Dirichlet vector. No sampling algorithm is needed for the density calculation below.
Multiplying the integrand by merely increases one exponent. Thus its expectation is , where increases coordinate by one. Increasing two exponents similarly gives the second moments:
Here is one when the indices agree and zero otherwise. The negative covariances follow from sharing a fixed total. Each covariance row sums to zero, so the full covariance matrix is singular: the vector cannot vary in the all-ones direction.
The mean proportions and total concentration have separate roles. Compare with : both have mean , but the first-coordinate variance falls from to . A larger total concentrates draws near the same mean when those proportions are held fixed. Increasing only one shape also changes the mean. Calling all shapes “confidence” obscures this difference.
Evaluate the log density and its moments
The complete standard-library example accepts strictly interior coordinates. Log Gamma avoids forming enormous Gamma values and multiplying tiny powers. For a Beta input, floating-point rounding of can reach an endpoint; the function then rejects it instead of claiming to evaluate a boundary limit. Coordinates must sum to one within an absolute tolerance of ; they are never silently renormalized.
import math
def shapes(alpha):
a = tuple(float(x) for x in alpha)
if len(a) < 2 or any(not math.isfinite(x) or not 0 < x <= 10_000
for x in a):
raise ValueError("at least two finite shapes in (0, 10000] required")
return a
def dirichlet_logpdf(x, alpha):
a = shapes(alpha)
x = tuple(float(v) for v in x)
if len(x) != len(a) or any(not math.isfinite(v) or not 0 < v < 1
for v in x):
raise ValueError("matching, strictly interior coordinates required")
if not math.isclose(math.fsum(x), 1.0, rel_tol=0, abs_tol=1e-12):
raise ValueError("coordinates must sum to one")
normalizer = math.lgamma(math.fsum(a)) - math.fsum(math.lgamma(v) for v in a)
return normalizer + math.fsum((v-1)*math.log(p) for v, p in zip(a, x))
def beta_logpdf(x, a, b):
return dirichlet_logpdf((x, 1-x), (a, b))
def dirichlet_moments(alpha):
a = shapes(alpha)
total = math.fsum(a)
mean = [v/total for v in a]
covariance = [[p*((1 if i == j else 0)-q)/(total+1)
for j, q in enumerate(mean)] for i, p in enumerate(mean)]
return mean, covariance
assert math.isclose(math.exp(beta_logpdf(0.5, 2, 2)), 1.5)
assert math.isclose(math.exp(dirichlet_logpdf((0.2, 0.3, 0.5), (1, 1, 1))), 2)
mean, covariance = dirichlet_moments((2, 3, 5))
assert all(math.isclose(x, y) for x, y in zip(mean, (0.2, 0.3, 0.5)))
assert math.isclose(covariance[0][0], 0.16/11)
assert math.isclose(covariance[0][1], -0.06/11)
print(round(math.exp(beta_logpdf(0.5, 2, 2)), 6), mean)
The output starts with 1.5 and the mean [0.2, 0.3, 0.5]. A log-density call uses arithmetic and storage; constructing the covariance uses time and storage because it returns every entry. These costs treat library special-function calls as constant-cost operations. The shape ceiling of 10,000 is an instructional restriction, not part of the probability law. Log-space calculation still suffers cancellation for extreme shapes or values near boundaries; this example is not a general-purpose special-functions library.
Try keeping the proportions fixed and multiplying all shapes by ten. Inspect the changed covariance before evaluating either density at its mean. Peak height and uncertainty are related through the full distribution; one point’s density is not an interval probability.
What the shape family cannot express
A proper Dirichlet has strictly positive shapes. Setting one to zero does not give another ordinary member of this family; lower-dimensional limiting distributions need separate definitions. With , a density may diverge on an approached face while remaining integrable. Real data containing exact zeros may reflect rounding, structural absence, or a separate mass at zero, and require an observation model that explains which.
The Dirichlet also imposes negative pairwise covariances between its components. A sum-to-one constraint alone does not force every pair to be negatively correlated when : two components can rise together at a third’s expense. Such behavior cannot be captured by this single Dirichlet family. Mixtures or a model defined through transformed unconstrained variables can allow more flexible dependence.
For categorical observations with counts , multiplication by the likelihood changes each exponent from to . The resulting posterior is Dirichlet(), conditional on that likelihood and prior; the two-category result is Beta updating. MML, Section 6.6.1 derives the Beta case and identifies the multinomial–Dirichlet pair. The convenient count update does not establish that a chosen prior fits a real population.
Experiments and exercises
- Beta(2,2) has density . What is the probability of ? Answer: integrate to obtain . The density 1.5 at the midpoint is not this probability.
- Compare Dirichlet(2,3,5) and Dirichlet(20,30,50). Which has the same mean, and by what factor does its first variance shrink? Answer: both have mean ; the second variance is times the first.
- For Dirichlet(1,1,1), the density is 2. Why does it normalize? Answer: in coordinates the domain is the triangle , of area . Density times area is one. Its mean is ; a constant density does not make that point occur with positive probability.
- A colleague proposes for uniform on and claims it must be Dirichlet because the components sum to one. Is that true? Answer: no. The first two coordinates have positive covariance , and the vector lies on a line inside the simplex. Both facts rule out a proper three-component Dirichlet.
Connections to probability models
Beta and Dirichlet distributions are useful building blocks when a probability or a mixture weight needs its own uncertainty model. Continue with conjugate priors for the complete update calculation, posterior prediction for future outcomes, and hierarchical models when different groups should share information. Distinguish the distribution over weights from the observation distribution at every step: averaging plausible weights and selecting one weight vector need not produce the same uncertainty about a collection of future observations.
Make a prediction, then check
What changes when Dirichlet(2,3,5) becomes Dirichlet(20,30,50)?
Learning objectives
- Distinguish categorical outcomes from uncertainty about probability vectors and explain densities above one.
- Derive normalizers and moments using Gamma integrals and separate total concentration from mean proportions.
- Compute interior log densities and covariances and identify boundary, dependence and implementation limitations.
Prerequisites & connections
Explore related knowledge →References
- Mathematics for Machine Learning — mathematical foundations (2024-01-15 draft)
Marc Peter Deisenroth; A. Aldo Faisal; Cheng Soon Ong · 2020 - SciPy — scipy.stats.beta
SciPy developers - SciPy — scipy.stats.dirichlet
SciPy developers
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 SciPy sources; checked positive shapes, normalizers and limited conjugacy claims; independently derived Gamma substitutions, coordinate measure, moments and covariances.
- Compared bilingual arguments, four answered exercises, equations and code; this check is not independent human peer review.
- Ran polynomial and triangle integration and domain checks; verified Beta probability 11/16, Dirichlet moments, concentration scaling and the K=2 case.
- A second Codex agent checked closed-form densities for Beta(1/2,1/2) and Dirichlet(1/2,1/2,1/2), and reviewed the common Gamma scale and shapes.
- The parent executed all 25 independent probability checks; bilingual code, display equations, main anchors, sources and exercises were additionally compared.
Source locations checked:
- Mathematics for Machine Learning — mathematical foundations (2024-01-15 draft) · 2024-01-15 draft, PDF pages 212–216 (printed 206–210), Example 6.10 equations 6.98–6.101: Beta shapes, Gamma normalization, mean and variance; Section 6.6.1, Examples 6.11–6.12 and Table 6.2: Beta update and multinomial–Dirichlet pairing. Actual local PDF text read.
- SciPy — scipy.stats.beta · Notes, standardized Beta PDF and positive-shape domain, lines 58–69 of fetched page. No code copied; general Gamma normalization derivation independently expanded.
- SciPy — scipy.stats.dirichlet · Notes, simplex constraints and Gamma/Beta normalizer, lines 58–74; Methods mean, var and cov lines 53–55. Coordinate-density convention and moment ratios re-derived in article; no API-dependent code reused.
Related topics