AI Wiki中文/EN

Categorical and multinomial distributions

类别与多项分布

Separate one label from a count vector, derive the counting factor and negative covariance, and compute exact small probabilities.

On this pageIntuitionMathematics & methodImplementationLimitationsExercisesResearch connections

Three labels, two different questions

Imagine a deliberately simple request router. Each request goes to a cache, a calculator, or a search service with probabilities 1/21/2, 1/31/3, and 1/61/6. Assume that requests choose independently and keep these same probabilities. These are invented numbers for the example, not measurements of a deployed system.

One request asks for a category. Three requests can instead ask for counts: how likely are two cache requests, one calculator request, and no search requests? The ordered sequence cache–cache–calculator has probability 1/121/12. But cache–calculator–cache and calculator–cache–cache qualify too. Adding their probabilities gives 1/41/4.

The categorical distribution describes one label. The multinomial distribution describes a vector of counts from a fixed number of repeated categorical draws. Distinguishing these outcomes prevents a missing factor of three in this example.

Assigning the labels codes 0, 1, and 2 helps a program store them. It does not mean search is twice calculator or that cache is closer to calculator. A category code is an identifier unless the problem supplies a meaningful order or distance. A one-hot vector records a category without claiming such numerical spacing.

Count the sequences, then remove their order

Let K≥1K\ge1 be the number of mutually exclusive, exhaustive categories. Their probabilities satisfy pi≥0p_i\ge0 and ∑ipi=1\sum_i p_i=1. A categorical variable YY takes values in these categories; its one-hot representation ZZ has Zi=1Z_i=1 if Y=iY=i and zero otherwise. Thus P(Y=i)=piP(Y=i)=p_i and exactly one component of ZZ equals one.

For nn independent draws with the same vector pp, write Xi=∑r=1nZriX_i=\sum_{r=1}^n Z_{ri}. The count vector has a multinomial distribution. Fixed nn, independence, and unchanged category probabilities are assumptions of this construction. Berkeley, multinomial model

X∼Multinomial⁡(n,p),P(X=x)=n!∏i=1Kxi!∏i=1Kpixi,xi∈{0,1,…},∑i=1Kxi=n.X\sim\operatorname{Multinomial}(n,p),\qquad P(X=x)=\frac{n!}{\prod_{i=1}^K x_i!}\prod_{i=1}^K p_i^{x_i},\qquad x_i\in\{0,1,\ldots\},\quad\sum_{i=1}^K x_i=n.

Outside that support the mass is zero. Every ordered sequence with counts xx has probability ∏ipixi\prod_i p_i^{x_i}. Choose the x1x_1 positions occupied by category 1, then the x2x_2 positions from those left, and continue. Multiplying these choices cancels the intermediate factorials and leaves the coefficient n!/∏ixi!n!/\prod_i x_i!. This coefficient counts disjoint sequences; it is not an extra probability. The multinomial theorem shows normalization: summing the formula over all valid count vectors gives (∑ipi)n=1(\sum_i p_i)^n=1. Pishro-Nik, Section 2.1.3, multinomial coefficients

Use the empty-product convention 00=10^0=1 in this probability formula. A category of probability zero contributes no penalty when its count is zero, but any positive count in that category makes the whole mass zero. When n=0n=0, the all-zero vector has probability one. When n=1n=1, the only possible vectors are one-hot vectors, recovering the categorical distribution. SciPy, multinomial support and parameters

Independent draws do not make the counts independent. Derive their moments from indicators. A single indicator has mean pip_i and variance pi(1−pi)p_i(1-p_i). Within one draw, ZriZrj=0Z_{ri}Z_{rj}=0 for distinct categories, so its cross-covariance is −pipj-p_ip_j. Terms from different draws have zero covariance by independence. Summing gives:

E[Xi]=npi,Var⁡(Xi)=npi(1−pi),Cov⁡(Xi,Xj)=−npipj(i≠j).\mathbb E[X_i]=np_i,\qquad \operatorname{Var}(X_i)=np_i(1-p_i),\qquad \operatorname{Cov}(X_i,X_j)=-np_ip_j\quad(i\ne j).

For the router, n=3n=3 gives expected counts (3/2,1,1/2)(3/2,1,1/2) and cache–calculator covariance −1/2-1/2. The expected counts need not themselves be a possible integer observation. More cache requests leave fewer of the fixed three slots for calculator requests. If a category has probability zero or one, some counts are constant and their covariance vanishes; dependence claims need this qualification.

In matrix notation the covariance is n(diag⁡(p)−pp⊤)n(\operatorname{diag}(p)-pp^\top), where diag⁡(p)\operatorname{diag}(p) places pp on the diagonal. Multiplying this matrix by the all-ones vector gives zero. Its singularity is expected: the total count has no randomness. When n>0n>0, K≥2K\ge2, and every category has positive probability, dropping any one coordinate leaves a nonsingular covariance for the remaining counts. This removes the fixed-total redundancy when an algorithm needs an inverse.

Compute one small count event exactly

This complete program accepts integer or Fraction probabilities and checks their sum exactly. It builds the multinomial coefficient by choosing remaining positions. No random sampling, floating-point normalization, or third-party library is needed. Malformed parameters raise an error; integer count vectors outside the support return zero.

from fractions import Fraction as F
from math import comb

def multinomial_pmf(n, counts, probabilities):
    if type(n) is not int or n < 0:
        raise ValueError("n must be a nonnegative integer")
    counts, probabilities = tuple(counts), tuple(probabilities)
    if not probabilities or len(counts) != len(probabilities):
        raise ValueError("matching nonempty vectors required")
    if any(type(p) not in (int, F) for p in probabilities):
        raise TypeError("use integers or exact Fraction probabilities")
    p = tuple(F(v) for v in probabilities)
    if any(v < 0 for v in p) or sum(p) != 1:
        raise ValueError("nonnegative probabilities must sum exactly to one")
    if any(type(c) is not int for c in counts):
        raise ValueError("counts must be integers")
    if any(c < 0 for c in counts) or sum(counts) != n:
        return F(0)
    result, remaining = F(1), n
    for c, probability in zip(counts, p):
        result *= comb(remaining, c) * probability ** c
        remaining -= c
    return result

p = (F(1,2), F(1,3), F(1,6))
assert multinomial_pmf(3, (2,1,0), p) == F(1,4)
assert p[0] * p[0] * p[1] == F(1,12)
assert multinomial_pmf(3, (2,2,0), p) == 0
assert multinomial_pmf(0, (0,0,0), p) == 1
assert multinomial_pmf(2, (1,1,0), (1,0,0)) == 0
assert multinomial_pmf(2, (2,0,0), (1,0,0)) == 1
print("count probability:", multinomial_pmf(3, (2,1,0), p))

There are KK combination and exponentiation calls, plus O(K)O(K) validation work and storage. These are arbitrary-precision integer and rational operations: their bit cost grows with nn and with numerator and denominator lengths. It would be misleading to call the whole computation constant-cost O(K)O(K) arithmetic. Enumerating all KnK^n ordered sequences is much more expensive and is useful only as an independent check on small cases.

For large counts, computing log mass with log-gamma terms avoids constructing factorials. Zero probabilities still need explicit treatment before taking logarithms. SciPy offers logpmf; its documented handling of a probability vector that does not sum to one can replace the last entry with a remainder. The teaching code deliberately rejects such vectors so a data error is visible. Check the library version and parameter convention when replacing this implementation. SciPy, Notes and methods

A histogram can hide the wrong experiment

The histogram cache–cache–calculator is the same as cache–calculator–cache. If repeated requests depend on the previous route, these sequences may have different probabilities. Their count distribution is not justified by an independent-draw multinomial model merely because the histogram has three entries.

Sampling without replacement from a finite inventory changes the probabilities after each draw. Multiple labels per observation also violate the one-category-per-draw setup. Grouping categories is safe: merging calculator and search makes their total count binomial with probability 1/21/2. Dropping search observations is different: it changes the sample or conditions on its composition, so the original fixed nn and probabilities cannot simply be retained.

A fitted probability of zero assigns zero likelihood to any future appearance of that category. With limited data, an unobserved category need not be impossible. Priors or smoothing can encode that distinction, but the chosen prior is an added modeling assumption.

Keep the event visible

  1. In the router model, what is the probability of exactly one request to each service among three? Answer: each ordering has probability 1/361/36 and there are 3!=63!=6 orderings, so the result is 1/61/6.
  2. What happens at p=(1,0,0)p=(1,0,0) with n=4n=4? Answer: only (4,0,0)(4,0,0) has positive mass, equal to one. Every count is constant, so all variances and covariances are zero.
  3. For two draws with p=(1/2,1/2)p=(1/2,1/2), can the two counts be independent? Answer: no. Each has probability 1/41/4 of equaling 2, but both cannot equal 2. Their joint probability is zero rather than 1/161/16.
  4. The three labels are renamed and their probability and count coordinates permuted together. Does the count-event probability change? Answer: no. Both products and the coefficient are unchanged. A model that changes merely because category identifiers were renumbered is using additional numerical structure.

From a label probability to a learning objective

For observed ordered labels y1,…,yny_1,\ldots,y_n, the log likelihood is ∑rlog⁡pyr=∑ixilog⁡pi\sum_r\log p_{y_r}=\sum_i x_i\log p_i. For their unordered count vector, add log⁡(n!/∏ixi!)\log(n!/\prod_i x_i!). That term is constant as a function of pp for fixed observed counts, so both likelihoods have the same maximizers, even though they assign probabilities to different events.

This calculation explains why categorical negative log likelihood connects to cross-entropy. A classifier can make pp depend on the input; then observations generally have different probability vectors, so their aggregate counts need not have one ordinary multinomial distribution. Dirichlet priors, multinomial logistic regression, and models for dependent categorical observations develop different parts of this foundation. Keep the sampling story attached to the formula as those models become more elaborate.

Make a prediction, then check

Draw independently n times from the same category probability vector. How are different category counts related?

Choose one answer

Learning objectives

  • Distinguish one label, an ordered sequence, and a count event, and derive the multinomial coefficient.
  • Derive means, variances, and negative covariances from indicators, including zero probabilities and zero draws.
  • Compute small count probabilities with exact fractions and identify changing probabilities, dependence, and category-encoding errors.

Prerequisites & connections

Explore related knowledge →

References

  1. SticiGui — The Multinomial Distribution and the Chi-Squared Test for Goodness of Fit
    Philip B. Stark
  2. Introduction to Probability, Statistics, and Random Processes — Section 2.1.3: Multinomial coefficients
    Hossein Pishro-Nik · 2014
  3. SciPy — scipy.stats.multinomial
    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.

  • Re-derived the multinomial coefficient, normalization, and indicator moments; checked zero probabilities, n=0, one category, and covariance degeneracies.
  • Enumerated all ordered sequences for every three-category probability vector with denominator 4 and n=0…6; compared each exact Fraction mass.
  • Checked means, full covariance, relabeling invariance, and merged-category binomial marginals from independent enumeration, plus invalid-input checks.
  • Compared bilingual arguments, examples, and four answered exercises; display equations and Python code match exactly.
  • The parent reviewed single-category draws, fixed total count, negative covariance, conditions for dropping a coordinate, and exact-Fraction code with its bit-cost caveat.
  • The parent executed all 25 independent probability checks; bilingual code, display equations, main anchors, sources and exercises were additionally compared.
  • Static rendering found unprocessed answer emphasis adjacent to Chinese text; explicit strong tags now preserve all answer text, values and formulas.

Source locations checked:

Related topics

No matches. Try a synonym or acronym.

0 results shown

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