TExcelTAD
Home › Math for Machine Learning › Sum Rule, Product Rule and Bayes' Theorem

Sum Rule, Product Rule and Bayes' Theorem

Two rules generate all of probabilistic machine learning. The sum rule removes a variable you do not care about; the product rule factors a joint distribution into simpler pieces. Combined, they give Bayes' theorem, which turns "how likely is the data under each hypothesis" into "how likely is each hypothesis given the data".

The two rules

p(x)=∑yp(x,y)or∫p(x,y) dysum rule (marginalization)p(x,y)=p(y∣x) p(x)=p(x∣y) p(y)product rule\begin{aligned} p(\mathbf{x}) &= \sum_{\mathbf{y}} p(\mathbf{x}, \mathbf{y}) \quad \text{or} \quad \int p(\mathbf{x}, \mathbf{y})\,d\mathbf{y} && \text{sum rule (marginalization)} \\ p(\mathbf{x}, \mathbf{y}) &= p(\mathbf{y} \mid \mathbf{x})\,p(\mathbf{x}) = p(\mathbf{x} \mid \mathbf{y})\,p(\mathbf{y}) && \text{product rule} \end{aligned}

The product rule extends to a chain: p(x1,…,xn)=p(x1) p(x2∣x1)⋯p(xn∣x1,…,xn−1)p(x_1, \ldots, x_n) = p(x_1)\,p(x_2 \mid x_1)\cdots p(x_n \mid x_1, \ldots, x_{n-1}). Language models are built on exactly this factorization: the probability of a sentence is a product of next-token probabilities.

Bayes' theorem

Equate the two forms of the product rule and divide:

p(θ∣x)⏟posterior=p(x∣θ)⏞likelihood  p(θ)⏞priorp(x)⏟evidence,p(x)=∫p(x∣θ) p(θ) dθ\underbrace{p(\boldsymbol{\theta} \mid \mathbf{x})}_{\text{posterior}} = \frac{\overbrace{p(\mathbf{x} \mid \boldsymbol{\theta})}^{\text{likelihood}}\;\overbrace{p(\boldsymbol{\theta})}^{\text{prior}}}{\underbrace{p(\mathbf{x})}_{\text{evidence}}}, \qquad p(\mathbf{x}) = \int p(\mathbf{x} \mid \boldsymbol{\theta})\,p(\boldsymbol{\theta})\,d\boldsymbol{\theta}

The evidence is a normalizing constant computed with the sum rule. It is often the hard part, so many methods work with the unnormalized product p(x∣θ) p(θ)p(\mathbf{x} \mid \boldsymbol{\theta})\,p(\boldsymbol{\theta}).

The base-rate trap

A test for a rare condition (1% prevalence) has 95% sensitivity and a 5% false-positive rate. Given a positive test, what is the chance of the condition?

P(D∣+)=0.95⋅0.010.95⋅0.01+0.05⋅0.99=0.00950.059≈0.161P(D \mid +) = \frac{0.95 \cdot 0.01}{0.95 \cdot 0.01 + 0.05 \cdot 0.99} = \frac{0.0095}{0.059} \approx 0.161

Only about 16%. The prior matters: most positives come from the large healthy group. The same logic explains why a 99%-accurate fraud model can still produce mostly false alarms.

python · try it yourself
import numpy as np

prior, sens, fpr = 0.01, 0.95, 0.05
post = sens * prior / (sens * prior + fpr * (1 - prior))
print(f"P(condition | positive) = {post:.4f}")
# check by simulation
rng = np.random.default_rng(0)
n = 1_000_000
sick = rng.uniform(size=n) < prior
positive = np.where(sick, rng.uniform(size=n) < sens, rng.uniform(size=n) < fpr)
print(f"simulated: {sick[positive].mean():.4f}")
# a second positive test (independent given the condition) updates again
post2 = sens * post / (sens * post + fpr * (1 - post))
print(f"after two positive tests: {post2:.4f}")
P(condition | positive) = 0.1610
simulated: 0.1612
after two positive tests: 0.7848

Yesterday's posterior is today's prior: Bayes' theorem can be applied sequentially as data arrives.

A Bayesian update over a grid

The same computation works for a continuous parameter. Estimate a coin's bias μ\mu from 7 heads in 10 flips, with a uniform prior, by evaluating prior times likelihood on a grid and normalizing:

python · try it yourself
import numpy as np

mu = np.linspace(0, 1, 1001)
prior = np.ones_like(mu)
heads, flips = 7, 10
likelihood = mu**heads * (1 - mu)**(flips - heads)
unnorm = likelihood * prior
dmu = mu[1] - mu[0]
posterior = unnorm / (unnorm.sum() * dmu)          # sum rule gives the evidence
print("posterior mode:", round(float(mu[np.argmax(posterior)]), 4))
print("posterior mean:", round(float((mu * posterior).sum() * dmu), 4), " (exact 8/12 =", round(8 / 12, 4), ")")
print("P(mu > 0.5 | data):", round(float(posterior[mu > 0.5].sum() * dmu), 4))
posterior mode: 0.7
posterior mean: 0.6667  (exact 8/12 = 0.6667 )
P(mu > 0.5 | data): 0.8861

In software

  • Naive Bayes classifiers apply Bayes' theorem with a product of per-feature likelihoods (Naive Bayes).
  • Spam filters, A/B-test dashboards and medical decision tools report posteriors, not likelihoods.
  • Probabilistic programming libraries (PyMC, NumPyro, Stan) approximate posteriors when the evidence integral is intractable.

Exercises

Exercise 1: Marginalize

p(x,y)p(x, y) for x,y∈{0,1}x, y \in \{0, 1\} is p(0,0)=0.3p(0,0) = 0.3, p(0,1)=0.2p(0,1) = 0.2, p(1,0)=0.1p(1,0) = 0.1, p(1,1)=0.4p(1,1) = 0.4. Find p(y=1)p(y = 1) and p(x=1∣y=1)p(x = 1 \mid y = 1).

Answer

p(y=1)=0.6p(y = 1) = 0.6; p(x=1∣y=1)=23p(x = 1 \mid y = 1) = \frac{2}{3}.

Solution

Sum rule: 0.2+0.4=0.60.2 + 0.4 = 0.6. Product rule: p(x=1∣y=1)=0.4/0.6=23p(x = 1 \mid y = 1) = 0.4/0.6 = \frac{2}{3}.

Exercise 2: Two boxes

Box A holds 3 red and 1 blue ball; box B holds 1 red and 3 blue. A box is chosen by a fair coin and a red ball is drawn. What is the probability it came from box A?

Answer

34\frac{3}{4}.

Solution
P(A∣R)=34⋅1234⋅12+14⋅12=3/84/8=34P(A \mid R) = \frac{\frac{3}{4} \cdot \frac{1}{2}}{\frac{3}{4} \cdot \frac{1}{2} + \frac{1}{4} \cdot \frac{1}{2}} = \frac{3/8}{4/8} = \frac{3}{4}

Exercise 3: Prevalence matters (code)

Repeat the test calculation with prevalence 10% instead of 1%.

Answer

About 0.679.

Solution
python · try it yourself
prior, sens, fpr = 0.10, 0.95, 0.05
print(round(sens * prior / (sens * prior + fpr * (1 - prior)), 4))
0.6786

0.095/(0.095+0.045)=0.095/0.14≈0.6790.095 / (0.095 + 0.045) = 0.095/0.14 \approx 0.679: with a less rare condition, a positive test is much more convincing.

Test yourself

In Bayes' theorem, p(x∣θ)p(\mathbf{x} \mid \boldsymbol{\theta}) is called…

  1. the prior
  2. the likelihood
  3. the posterior
  4. the evidence

The evidence p(x)p(\mathbf{x}) is computed with…

  1. the product rule only
  2. the sum rule: integrating likelihood times prior over θ\boldsymbol{\theta}
  3. the maximum of the likelihood
  4. the derivative of the prior

A language model computes the probability of a sentence as a product of next-token probabilities. Which rule justifies this?

  1. The sum rule
  2. The chain (product) rule
  3. The law of large numbers
  4. Independence of all tokens