AI Wiki中文/EN

Posterior predictive distributions

后验预测

Integrate parameter uncertainty into future observations, derive Beta-binomial dependence, and distinguish predictive checks from future evaluation.

On this pageIntuitionMathematics & methodImplementationLimitationsExercisesResearch connections

The next four trials are not the unknown probability

After three successes and one failure, a Beta(2,2) prior becomes a Beta(5,3) posterior for an unknown success probability pp. Its mean is 5/85/8. You now need to plan for the next four trials. Should you act as if their success probability were known to be exactly 5/85/8?

That substitution gets the expected count right: 4×5/8=2.54\times5/8=2.5. It misses part of the count’s uncertainty. A posterior predictive calculation gives variance 5/45/4, whereas a binomial distribution with fixed probability 5/85/8 gives 15/1615/16. If a higher-than-average pp is plausible, it affects all four future trials together. This shared uncertainty changes the chance of extreme counts.

A posterior distribution concerns unknown parameters. A posterior predictive distribution concerns new observations, averaging their observation law over those parameters. MML, Section 8.4.2 explains prediction by marginalizing parameters; Stan’s prediction guide states the predictive integral.

Integrate the whole observation law

Let DD be observed data, θ\theta a parameter, and Y~\widetilde Y the future observation or future vector. The general conditional-probability rule gives

p(y~∣D)=∫p(y~∣θ,D)π(θ∣D) dθ.p(\widetilde y\mid D)=\int p(\widetilde y\mid\theta,D)\pi(\theta\mid D)\,d\theta.

When future and past observations are conditionally independent given θ\theta, the first factor reduces to p(y~∣θ)p(\widetilde y\mid\theta). This assumption must follow from the model; a time series may retain dependence on its observed history. For discrete parameters, use a sum. With a proper posterior and a normalized observation model, the predictive distribution normalizes because integrating over all future outcomes first gives one.

Now let p∣D∼Beta⁡(a,b)p\mid D\sim\operatorname{Beta}(a,b) with a,b>0a,b>0, and let KK count successes in mm future trials that are conditionally independent with the same pp. Given pp, KK is binomial. Integrating its PMF against the Beta density gives

P(K=k∣D)=(mk)B(a+k,b+m−k)B(a,b),k=0,…,m.P(K=k\mid D)=\binom mk\frac{B(a+k,b+m-k)}{B(a,b)},\qquad k=0,\ldots,m.

This is the Beta-binomial distribution. The Beta function is B(u,v)=Γ(u)Γ(v)/Γ(u+v)B(u,v)=\Gamma(u)\Gamma(v)/\Gamma(u+v); its arguments must be positive. Multiplication adds the observed future-success and future-failure exponents, and the remaining integral is exactly that Beta normalizer. The PMF agrees with Stan’s versioned Beta-binomial reference, Section 12.3.1. For m=0m=0, the count is zero with probability one.

Write s=a+bs=a+b and μ=a/s\mu=a/s. The law of total expectation gives E[K∣D]=mμE[K\mid D]=m\mu. The law of total variance separates randomness at fixed pp from uncertainty about pp:

Var⁡(K∣D)=E[mp(1−p)∣D]+Var⁡(mp∣D)=mμ(1−μ)+m(m−1)Var⁡(p∣D).\operatorname{Var}(K\mid D)=E[mp(1-p)\mid D]+\operatorname{Var}(mp\mid D)=m\mu(1-\mu)+m(m-1)\operatorname{Var}(p\mid D).

Since Var⁡(p∣D)=μ(1−μ)/(s+1)\operatorname{Var}(p\mid D)=\mu(1-\mu)/(s+1), this becomes

Var⁡(K∣D)=mμ(1−μ)s+ms+1.\operatorname{Var}(K\mid D)=m\mu(1-\mu)\frac{s+m}{s+1}.

For m>1m>1, this exceeds the plug-in binomial variance by m(m−1)Var⁡(p∣D)m(m-1)\operatorname{Var}(p\mid D). For m=1m=1, both predictive laws are simply Bernoulli(μ\mu); retaining parameter uncertainty does not create a larger variance than a Bernoulli variable can have at that mean. This equality for one trial should not be extrapolated to a whole future batch.

Indeed, for distinct future indicators B~i,B~j\widetilde B_i,\widetilde B_j, conditional independence gives E[B~iB~j∣p,D]=p2E[\widetilde B_i\widetilde B_j\mid p,D]=p^2. Subtracting the product of their marginal means gives

Cov⁡(B~i,B~j∣D)=Var⁡(p∣D),Corr⁡(B~i,B~j∣D)=1s+1(i≠j).\operatorname{Cov}(\widetilde B_i,\widetilde B_j\mid D)=\operatorname{Var}(p\mid D),\qquad \operatorname{Corr}(\widetilde B_i,\widetilde B_j\mid D)=\frac1{s+1}\quad(i\ne j).

They are independent conditional on pp, but dependent after averaging over it. This is uncertainty about a shared parameter, not a claim that one trial physically causes another. In the opening example, the covariance is 5/1925/192 and correlation is 1/91/9.

The exact masses at counts 0 through 4 are (3,10,18,21,14)/66(3,10,18,21,14)/66. Thus all four succeed with probability 7/337/33, compared with (5/8)4=625/4096(5/8)^4=625/4096 under the plug-in model. Both distributions have mean 2.5. Their different tail probabilities can matter when staffing, stock, or retries depend on the whole batch.

An exact predictive table without sampling

For small examples, exact fractions make a useful reference. Let (x)m=x(x+1)⋯(x+m−1)(x)_m=x(x+1)\cdots(x+m-1) be the rising factorial, with (x)0=1(x)_0=1. The probability of zero successes is (b)m/(a+b)m(b)_m/(a+b)_m. Dividing successive Beta-binomial masses and canceling Gamma factors yields

q(k+1)q(k)=m−kk+1a+kb+m−k−1,k=0,…,m−1.\frac{q(k+1)}{q(k)}=\frac{m-k}{k+1}\frac{a+k}{b+m-k-1},\qquad k=0,\ldots,m-1.

Every denominator is positive for valid inputs. The complete program evaluates this recurrence, computes moments, and finds discrete quantiles. The quantile helper assumes an ordered, valid count PMF returned by predictive_pmf.

from fractions import Fraction as F

def parameters(m, a, b):
    if type(m) is not int or not 0 <= m <= 2000:
        raise ValueError("integer future size in [0,2000] required")
    if any(type(v) is not int and not isinstance(v, F) for v in (a,b)):
        raise ValueError("use integer or Fraction shapes")
    a,b = F(a),F(b)
    if a <= 0 or b <= 0:
        raise ValueError("positive posterior shapes required")
    return a,b

def predictive_pmf(m, a, b):
    a,b = parameters(m,a,b)
    first = F(1)
    for j in range(m):
        first *= (b+j)/(a+b+j)
    mass = [first]
    for k in range(m):
        mass.append(mass[-1]*F(m-k,k+1)*(a+k)/(b+m-k-1))
    assert sum(mass) == 1
    return mass

def predictive_moments(m, a, b):
    a,b = parameters(m,a,b)
    total = a+b
    mu = a/total
    return m*mu, m*mu*(1-mu)*(total+m)/(total+1)

def quantile(mass, q):
    if type(q) is not int and not isinstance(q,F):
        raise ValueError("use an integer or Fraction quantile")
    q = F(q)
    if not 0 <= q <= 1:
        raise ValueError("quantile must lie in [0,1]")
    # mass is a valid, ordered count PMF from predictive_pmf.
    cumulative = F(0)
    for k,p in enumerate(mass):
        cumulative += p
        if cumulative >= q:
            return k
    raise ValueError("mass does not reach requested quantile")

mass = predictive_pmf(4,5,3)
assert mass == [F(v,66) for v in (3,10,18,21,14)]
assert predictive_moments(4,5,3) == (F(5,2),F(5,4))
assert predictive_pmf(1,5,3) == [F(3,8),F(5,8)]
assert predictive_pmf(0,5,3) == [1]
low,high = quantile(mass,F(1,20)),quantile(mass,F(19,20))
assert (low,high) == (1,4)
assert sum(mass[low:high+1]) == F(21,22)
print(mass, (low,high))

The table requires O(m)O(m) rational operations and O(m)O(m) storage; quantile lookup also scans at most m+1m+1 entries. Exact fraction bit costs grow with the sizes of the shapes and the future batch. The 2,000-trial limit is a teaching implementation restriction. A production library normally uses specialized log probabilities, recurrences, or sampling for larger problems.

The 5th and 95th percentiles in this example are 1 and 4. That discrete interval contains probability 21/2221/22, about 95.45%, rather than exactly 90%. Discrete quantiles can include extra probability at their endpoints. This interval describes a future count under the model, not a credible interval for pp.

When integration is unavailable, sample a parameter from the posterior and then sample the entire future vector conditional on that draw. Repeat both steps to obtain predictive draws. Drawing a new independent pp before every trial changes the joint model and loses the shared uncertainty derived above. Averaging conditional probabilities is another way to estimate an event probability. Stan’s sampling and computation sections describe these two operations. The logarithm of an average probability is not the average log probability; log-sum-exp is useful for the former.

Model checking and future evaluation answer different questions

A posterior predictive check draws replicated data with the original design and compares a chosen feature of those replications with the actual data. For a service log, total successes may be reproduced easily while the length of failure streaks is not. Choose discrepancies that address the model’s intended use. The procedure is described in Stan’s predictive-check guide.

Those comparisons reuse the data that formed the posterior. They help locate model mismatch; they are not measurements of performance on genuinely unseen outcomes. A posterior predictive tail probability also need not be uniformly distributed under the model, so it is not automatically a classical calibrated p-value. The same guide’s posterior p-value section makes that distinction explicit.

For future evaluation, lock a predictive distribution using training data, then score held-out or subsequently observed outcomes under a stated split or time protocol. Report predictive coverage and sharpness, relevant event probabilities, and scores such as log loss. A useful posterior check does not replace that assessment. Likewise, Bayes’ rule does not guarantee calibrated forecasts under a wrong prior, wrong likelihood, changing population, or inaccurate numerical inference.

Even a correct Beta-binomial calculation can answer the wrong deployment question. Four trials from one shared service differ from four trials, each from an unrelated service with its own rate. If future conditions change, state what connects them to the parameters learned from past data before copying the predictive formula.

Predict a batch, not just its mean

  1. With posterior Beta(5,3), what is the probability of success on one future trial? Does a fixed p=5/8p=5/8 model disagree? Answer: both give 5/85/8. A Bernoulli mixture has success probability equal to the mean of its mixing probability.
  2. For four future trials sharing that pp, compare the variances and the probability of four successes. Answer: predictive variance is 5/45/4, versus plug-in variance 15/1615/16; the all-success probabilities are 7/337/33 and 625/4096625/4096. Mean counts are both 5/25/2.
  3. Instead, independently draw a fresh pi∼Beta⁡(5,3)p_i\sim\operatorname{Beta}(5,3) for each future trial. Is the total still Beta-binomial? Answer: no. Integrating each independent parameter separately makes the trials independent Bernoulli(5/85/8), so the total is binomial. This is a different model for how probabilities are shared.
  4. Replicated training-size logs reproduce the observed success count. Does that establish accurate forecasts next month? Answer: no. Check other relevant features, such as streaks, and evaluate predictions on genuinely new or held-out observations under the intended time protocol. The training-data check neither tests distribution shift nor supplies a future-performance guarantee.

Keep the uncertainty that the decision needs

Conjugate models offer closed-form predictive distributions; more elaborate models use numerical integration or Monte Carlo. Both need the same definition of the future unit: one measurement, a vector sharing a latent effect, an existing group, or a new group. Changing that unit changes which unknowns are shared or resampled. Continue with hierarchical modeling, probabilistic scoring, and posterior predictive checks to connect the distribution to the decisions and failure modes that matter for the application.

Make a prediction, then check

With posterior Beta(5,3), four future trials share the same unknown p. Compared with a binomial model fixing p=5/8, which statement is correct?

Choose one answer

Learning objectives

  • Distinguish a parameter posterior from future observations and state the conditional-independence assumptions behind prediction.
  • Derive Beta-binomial masses, variance and marginal future dependence and compare plug-in prediction.
  • Compute an exact predictive table and discrete interval and distinguish predictive checks, future evaluation and calibration claims.

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. Stan User’s Guide — Posterior Predictive Sampling
    Stan Development Team
  3. Stan Functions Reference 2.23 — Beta-Binomial Distribution
    Stan Development Team
  4. Stan User’s Guide 2.39 — Posterior and Prior Predictive Checks
    Stan Development Team

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 the predictive integral, Beta-binomial PMF and predictive-check sources and stated the general conditional model and shared-parameter assumptions.
  • Independently checked the recurrence by direct mixture integration and exhaustive reinforced-urn paths, including one/zero trials, exact moments, future covariance and discrete quantiles.
  • Recalculated the Beta(5,3) four-trial table and interval mass 21/22, compared bilingual equations, code and four answers, and made no automatic Bayesian calibration claim.
  • Another agent independently checked 216 discrete quantile minimality cases, tail-swap symmetry and at-least-nominal interval mass, and reviewed shared-parameter future covariance and predictive-check scope.
  • 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 p.280 / printed 274, Section 8.4.2 equations 8.22–8.23: posterior and prediction by marginalizing parameters. Actual local PDF text read.
  • Stan User’s Guide — Posterior Predictive Sampling · Posterior predictive distribution, Computing the posterior predictive distribution, Sampling from the posterior predictive distribution, fetched lines 115–129; sections on Poisson example and prediction, lines 134–168 and 195–200. Read integral, average probabilities/log-sum-exp, two-stage sampling and future-data separation; no Stan code copied.
  • Stan Functions Reference 2.23 — Beta-Binomial Distribution · Version 2.23, Section 12.3.1, line 5: PMF binomial coefficient times Beta-function ratio for positive shapes. Deliberately linked the version actually read; no current API compatibility claim. Recurrence, moments and shared-parameter covariance derived independently.
  • Stan User’s Guide 2.39 — Posterior and Prior Predictive Checks · Version 2.39, lines 112–145: replication with original design; Posterior p-values, lines 182–186: not generally classically calibrated/uniform; Which statistics to test, lines 208–212. Only these checked claims used; source examples and code not copied.

Related topics

No matches. Try a synonym or acronym.

0 results shown

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