Bayesian inference
贝叶斯推断
How evidence changes a belief: derive a posterior and distinguish priors, likelihoods, and base rates.
bayes-theoremIntuition: an alarm does not guarantee a fault
Suppose 1% of a population of machines is faulty. A sensor alarms on 90% of faulty machines and produces a false alarm on 5% of healthy machines. These are hypothetical teaching values. After an alarm, the probability of a fault is not 90%: many healthy machines can also trigger the sensor.
Imagine 10,000 machines. The 100 faulty machines are expected to produce 90 alarms. The 9,900 healthy machines are expected to produce 495 false alarms. Only 90 of the resulting 585 alarms indicate a fault, giving approximately 15.4%. Natural frequencies help distinguish “alarm given fault” from “fault given alarm.”
Mathematics: from joint probability to a posterior
Let denote a fault and an alarm. Express the joint probability in two ways:
For , rearranging gives:
is the prior, the likelihood, and the posterior. A likelihood treats observed evidence as fixed and compares its support for alternative hypotheses. It need not sum to one over hypotheses. With two exhaustive hypotheses, the denominator is:
Substitution yields . This derivation follows from the definition of conditional probability. For the mathematical foundations, see MML, Section 6.3 and Deep Learning, Section 3.11.
In odds form, posterior odds equal prior odds multiplied by a likelihood ratio. The same evidence can therefore produce very different posterior probabilities when base rates differ. With continuous parameters, the sum in the denominator becomes an integral. Its computational difficulty motivates sampling, numerical integration, and variational approximations.
When and both likelihoods are positive, divide the posterior for by the posterior for its complement; the evidence cancels:
Here the prior odds are and the likelihood ratio is 18. Posterior odds are , which convert to probability . Odds and probability use different denominators. The direct implementation is intended for representable products; extremely small probabilities may require log-space computation rather than interpreting underflow as an impossible event.
A minimal implementation with boundary checks
This complete Python example takes a prior, a true-positive rate, and a false-positive rate. Each input must lie between zero and one.
import math
def posterior_alarm(prior, sensitivity, false_positive):
if any(not math.isfinite(p) or not 0 <= p <= 1
for p in (prior,sensitivity,false_positive)):
raise ValueError("finite probabilities in [0,1] required")
true_alarm = prior*sensitivity
evidence = true_alarm+(1-prior)*false_positive
if evidence == 0:
raise ValueError("zero or numerically underflowed evidence")
return true_alarm/evidence
answer = posterior_alarm(0.01,0.9,0.05)
assert abs(answer-2/13) < 1e-12
assert abs(posterior_alarm(0.1,0.9,0.05)-2/3) < 1e-12
assert posterior_alarm(0.2,0.8,0) == 1
assert posterior_alarm(0,0.9,0.1) == 0
assert posterior_alarm(1,0.9,0.1) == 1
for args in [(0,1,0),(1,0,0.2),(float('nan'),0.9,0.1),(-0.1,0.9,0.1)]:
try:
posterior_alarm(*args)
except ValueError:
pass
else:
raise AssertionError("invalid conditioning input accepted")
The binary calculation uses constant time and space. For many independent observations, multiplying small likelihoods can underflow. Accumulate log-likelihoods and normalize with log-sum-exp instead. Multiplication requires conditional independence given the hypothesis. Two messages are not automatically two independent pieces of evidence.
Limitations: a correct formula cannot repair a wrong model
If the prior describes a different population, or environmental changes alter the sensor’s false-positive rate, 15.4% no longer describes the current situation. Bayesian inference delivers a conclusion conditional on the model and evidence, not an unconditional guarantee.
A zero prior remains zero after standard updating. Extreme priors can rule out hypotheses that later observations should have allowed us to learn about. Check selection bias, correlated evidence, parameter uncertainty, and possibilities outside the model. Bayesian inference is also broader than naive Bayes classification, which adds conditional-independence assumptions about the features.
Experiments and exercises
-
Keep the sensor unchanged but increase fault prevalence to 10%. Answer: the posterior becomes .
-
Set the false-positive rate to zero while keeping the prior and sensitivity positive. Answer: an alarm implies posterior probability one, conditional on the strong assumption that a false alarm is impossible.
-
Two alerts are copies of the same forwarded log entry. May their likelihoods be multiplied as independent observations? Answer: no; this would count the same evidence twice.
-
What are the posterior odds in the opening example? Answer: , corresponding to probability . Odds compare fault with no fault; probability compares fault with all outcomes.
In the interactive experiment, vary the prior and false-positive rate separately. Predict the direction of the change before checking the result. You should be able to calculate a binary posterior, explain both terms in its denominator, and identify at least one data condition that invalidates the result.
Research connections
Continue with maximum a posteriori estimation, posterior prediction, Bayesian networks, and approximate inference. A point estimate retains one parameter value; posterior prediction averages over parameter uncertainty. This distinction helps determine whether an apparently confident prediction represents a concentrated predictive distribution or simply ignores uncertain parameters.
Make a prediction, then check
With 1% prevalence, 90% sensitivity, and 5% false positives, what is the posterior after an alarm?
Learning objectives
- Derive a binary posterior from joint probability and calculate its denominator.
- Identify the effects of base rates, correlated evidence, and model errors.
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 - Deep Learning — Chapter 3: Probability and Information Theory
Ian Goodfellow; Yoshua Bengio; Aaron Courville · 2016
Version2 · Editorial status: Recorded technical checks completed
View technical check record (AI)
Codex · 2026-09-05 · Codex technical check: cited-source comparison, re-derivation and recalculation, bilingual argument comparison, and executed Python assertions; no independent human peer review.
- Recomputed 2/13, 2/3, and odds from joint counts; checked every positive-evidence case on an 11³ parameter grid against exact rational arithmetic.
- Checked probability boundaries, zero evidence, underflow, and zero-prior limitations.
- Compared the main claims, assumptions, examples, exercises, and citations across languages; structural checks additionally compare display equations, code, and source IDs. This is an AI technical check, not independent human peer review.
Source locations checked:
- Mathematics for Machine Learning — mathematical foundations (2024-01-15 draft) · §6.3, printed pp.185–186, PDF pp.191–192; 2024-01-15 draft
- Deep Learning — Chapter 3: Probability and Information Theory · §3.11, Eq.3.42 and evidence marginalization
Related topics