Overview
Learning that an event happened shrinks the world to the outcomes inside . The conditional probability of is the share of that smaller world in which also holds. Bayes' theorem turns the question around: from how likely the evidence is under each cause, it gives how likely each cause is given the evidence. The law of total probability supplies the missing piece, the overall chance of the evidence, by adding up over all causes. From data, a conditional probability is a row of a table of counts divided by that row's total.
A short history
The idea of revising a probability when new information arrives appears in the work of Abraham de Moivre in the early 1700s. Thomas Bayes' essay, published in 1763, and Pierre-Simon Laplace's later work gave the rule for reversing a condition, now called Bayes' theorem. Andrey Kolmogorov's 1933 axioms gave the definition used today: the joint probability divided by the probability of the condition.
How it works
- Fix the event you condition on. It must have positive probability.
- Find the probability that and both happen, then divide by to get .
- When the causes split the world into non-overlapping parts, get by summing over the parts.
- Reverse the direction with Bayes' theorem: multiply each prior by its likelihood and divide by .
- From paired observations, count how often each pair occurs. Dividing each row by its total gives , and dividing each column by its total gives .
- Optionally add a small count to every cell first (Laplace smoothing) so that a pair never seen does not get probability exactly zero.
Watch out for
- and are different numbers. A test that is positive in 95% of sick people does not make a positive person 95% likely to be sick.
- Ignoring the base rate gives wildly wrong posteriors. When a condition is rare, most positive results come from the large healthy group.
- A row with no observations has an undefined conditional distribution. The template returns NaN for it unless smoothing is above zero.
- Smoothing changes every estimate, not only the empty cells. With few observations and many categories it can dominate the data.
- A conditional probability estimated from data shows association. It does not show that causes .
Use cases
When to use it
Reasoning from evidence to causes, such as reading a medical test or a spam filter score, and whenever a model needs a table of how one categorical variable depends on another.
In industry
- Medical screening
- Doctors combine a test's sensitivity and false positive rate with how common the disease is to get the chance that a positive patient is truly ill.
- Credit risk
- Lenders estimate the probability of default given income band, past arrears and loan type from tables of historical loans.
- Retail
- Market basket analysis reports the chance a customer buys one product given another is already in the basket, which drives shelf and recommendation choices.
Choosing it: what must hold
- A conditioning event with probability above zero, and enough data in that slice to estimate from.
- Counts or probabilities for the two events together, not only for each alone.
- For Bayes' theorem, a base rate for the event of interest. Without it the reversed probability cannot be found.
When to choose something else
| If | Use instead |
|---|---|
| The condition does not change the probability, so the events are independent | Basic probability, multiplying the two probabilities |
| The unknown is a model parameter, not an event | Bayesian inference |
| You condition on many variables and the table cells become too sparse | Naive Bayes or logistic regression |
Math foundations
Definition
Restrict attention to the outcomes in and ask what share of them also lie in . Dividing by rescales that smaller world to total probability 1.
Multiplication rule
The definition rearranged, and written both ways round. Setting the two right-hand sides equal is all that Bayes' theorem needs.
Law of total probability
If the events do not overlap and together cover everything, then splits into its pieces inside each . Their probabilities add.
Bayes' theorem
The prior is reweighted by how well explains the evidence , then normalized. The function posterior returns this for every at once.
Estimate from counts, with smoothing
The share of the observations with that also have . With it is the raw frequency. With every one of the values of gets one extra imagined observation.
Symbols
- events
- a partition: events that do not overlap and together cover every outcome
- the probability of given that happened
- the prior probability of cause
- the posterior probability of cause after seeing
- the number of observations with and
- the number of observations with
- the smoothing count added to every cell (smoothing in the config)
- the number of distinct values of
Worked by hand
A condition affects 1% of people. A test is positive for 95% of those who have it and for 5% of those who do not. Someone tests positive: how likely is it that they have the condition?
Only about 16% of positive results belong to people with the condition. The healthy group is 99 times larger, so its 5% of false alarms outnumber the true detections.
Visual example
Loading the example.
Try this
- Choose given a positive test and count the colours that remain: most are healthy people.
- Raise P(sick) to 0.2 and the same test becomes trustworthy.
- Bring P(+ | healthy) down to 0.01 and compare it with raising P(+ | sick): the false alarm rate matters more.
Code sample
from impl import ConditionalProbability, posterior
posterior([0.99, 0.05], [0.01, 0.99]) # [0.1667, 0.8333]: ill or healthy given a positive test
weather = ["rain", "rain", "sun", "sun", "sun", "rain"]
late = ["yes", "yes", "no", "no", "yes", "no"]
cp = ConditionalProbability().fit(weather, late)
cp.prob("yes", given_x="rain") # 2/3
cp.p_y_given_x() # rows: rain, sun; columns: no, yesRead the implementation (141 lines)
"""Conditional probability.
Scalar helpers apply the definition P(A | B) = P(A and B) / P(B), Bayes' theorem and the law of total
probability. `ConditionalProbability` estimates conditional probability tables P(Y | X) and P(X | Y) from paired
observations or from a table of counts, with optional Laplace smoothing.
"""
from __future__ import annotations
import numpy as np
try:
from .config import ConditionalProbabilityConfig
except ImportError: # run from the template's own folder
from config import ConditionalProbabilityConfig
def _check_probability(value: float, name: str) -> float:
value = float(value)
if not 0.0 <= value <= 1.0:
raise ValueError(f"{name} must lie in [0, 1], got {value}")
return value
def conditional(p_a_and_b: float, p_b: float) -> float:
"""P(A | B) = P(A and B) / P(B)."""
p_ab = _check_probability(p_a_and_b, "p_a_and_b")
p_b = _check_probability(p_b, "p_b")
if p_b == 0:
raise ValueError("cannot condition on an event of probability zero")
if p_ab > p_b + 1e-12:
raise ValueError("P(A and B) cannot exceed P(B)")
return p_ab / p_b
def total_probability(p_b_given_a, p_a) -> float:
"""P(B) = sum_i P(B | A_i) P(A_i) for a partition A_1..A_k. Both arguments are arrays (k,)."""
p_b_given_a = np.asarray(p_b_given_a, dtype=float)
p_a = np.asarray(p_a, dtype=float)
if p_b_given_a.shape != p_a.shape:
raise ValueError("p_b_given_a and p_a must have the same shape")
if abs(p_a.sum() - 1.0) > 1e-9:
raise ValueError("the partition probabilities p_a must sum to 1")
return float(np.dot(p_b_given_a, p_a))
def posterior(p_b_given_a, p_a) -> np.ndarray:
"""P(A_i | B) for every part of a partition, array (k,): Bayes' theorem with the evidence summed out."""
evidence = total_probability(p_b_given_a, p_a)
if evidence == 0:
raise ValueError("B has probability zero")
return np.asarray(p_b_given_a, dtype=float) * np.asarray(p_a, dtype=float) / evidence
def bayes(p_b_given_a: float, p_a: float, p_b: float) -> float:
"""Bayes' theorem for two events: P(A | B) = P(B | A) P(A) / P(B)."""
p_b = _check_probability(p_b, "p_b")
if p_b == 0:
raise ValueError("cannot condition on an event of probability zero")
return _check_probability(p_b_given_a, "p_b_given_a") * _check_probability(p_a, "p_a") / p_b
class ConditionalProbability:
"""Conditional probability tables estimated from data.
After `fit(x, y)` or `fit_counts(counts)`:
counts array (n_x, n_y), how often each pair was seen
x_labels list of the n_x distinct x values (row order)
y_labels list of the n_y distinct y values (column order)
"""
def __init__(self, config: ConditionalProbabilityConfig | None = None) -> None:
self.config = config or ConditionalProbabilityConfig()
self.counts: np.ndarray | None = None
self.x_labels: list = []
self.y_labels: list = []
def fit(self, x, y) -> "ConditionalProbability":
"""Count pairs. x and y are equal-length sequences of sortable, hashable labels."""
x, y = list(x), list(y)
if len(x) != len(y) or not x:
raise ValueError("x and y must be non-empty and of equal length")
self.x_labels, self.y_labels = sorted(set(x)), sorted(set(y))
xi = {v: i for i, v in enumerate(self.x_labels)}
yi = {v: i for i, v in enumerate(self.y_labels)}
counts = np.zeros((len(xi), len(yi)))
for a, b in zip(x, y):
counts[xi[a], yi[b]] += 1
self.counts = counts
return self
def fit_counts(self, counts, x_labels=None, y_labels=None) -> "ConditionalProbability":
"""Use a ready table of counts or joint probabilities, array (n_x, n_y)."""
counts = np.asarray(counts, dtype=float)
if counts.ndim != 2 or np.any(counts < 0) or counts.sum() <= 0:
raise ValueError("counts must be a 2-D non-negative array with a positive total")
self.counts = counts
self.x_labels = list(x_labels) if x_labels is not None else list(range(counts.shape[0]))
self.y_labels = list(y_labels) if y_labels is not None else list(range(counts.shape[1]))
if (len(self.x_labels), len(self.y_labels)) != counts.shape:
raise ValueError("labels do not match the shape of counts")
return self
def _table(self) -> np.ndarray:
if self.counts is None:
raise ValueError("call fit or fit_counts first")
return self.counts
def joint(self) -> np.ndarray:
"""P(X = x, Y = y), array (n_x, n_y), from raw frequencies."""
counts = self._table()
return counts / counts.sum()
def p_x(self) -> np.ndarray:
"""Marginal P(X = x), array (n_x,)."""
return self.joint().sum(axis=1)
def p_y(self) -> np.ndarray:
"""Marginal P(Y = y), array (n_y,)."""
return self.joint().sum(axis=0)
def p_y_given_x(self) -> np.ndarray:
"""P(Y = y | X = x), array (n_x, n_y). Each row sums to 1; a row never observed is NaN unless smoothed."""
counts = self._table() + self.config.smoothing
with np.errstate(invalid="ignore", divide="ignore"):
return counts / counts.sum(axis=1, keepdims=True)
def p_x_given_y(self) -> np.ndarray:
"""P(X = x | Y = y), array (n_x, n_y). Each column sums to 1."""
counts = self._table() + self.config.smoothing
with np.errstate(invalid="ignore", divide="ignore"):
return counts / counts.sum(axis=0, keepdims=True)
def prob(self, y, given_x) -> float:
"""P(Y = y | X = given_x) for one pair of labels."""
value = self.p_y_given_x()[self.x_labels.index(given_x), self.y_labels.index(y)]
if np.isnan(value):
raise ValueError(f"X = {given_x!r} was never observed, the conditional probability is undefined")
return float(value)
def independent(self, atol: float = 1e-9) -> bool:
"""True when P(X, Y) = P(X) P(Y) in every cell, within atol."""
return bool(np.allclose(self.joint(), np.outer(self.p_x(), self.p_y()), atol=atol))- Repository
- Not published yet
- Needs
- Python 3.10 and NumPy
- Tests
- 7, run with
python3 -m unittest -v
Practice
Call posterior([0.95, 0.05], [0.01, 0.99]) to reproduce the worked example, then raise the prevalence to 0.10 and see how the answer moves. Next make two short lists of labels, weather and umbrella, fit ConditionalProbability on them, and print p_y_given_x and p_x_given_y. Refit with ConditionalProbabilityConfig(smoothing=1.0) and compare the rows.
Check on learning
- In the worked example, which change helps more: raising the detection rate from 95% to 99%, or cutting the false positive rate from 5% to 1%? Why?
A way to think about it
Recompute the denominator both ways. Notice which of its two terms is larger and which change shrinks it.
- A second, independent test also comes back positive. How would you use the first answer to get the new probability?
A way to think about it
The posterior after the first test, 0.161, becomes the prior for the second. Apply the same formula again.
- If , what must equal, and what is this situation called?
A way to think about it
Substitute into the multiplication rule and cancel. You should recover the product definition of independence.
- You estimate from 20 observations where has 50 possible values. What does smoothing with do to the estimates, and is that reasonable?
A way to think about it
Compare the 50 imagined counts per row with the real counts in that row. Think about which one decides the result.
- p_y_given_x has rows that sum to 1 and p_x_given_y has columns that sum to 1. Why can you not get one from the other by transposing?
A way to think about it
Each is the same count table divided by different totals. Bayes' theorem tells you which extra quantities link them.