Sign in

Conditional probability

The probability of one event once another is known to have happened, with Bayes' theorem, the law of total probability and tables estimated from data.

Overview

Learning that an event BB happened shrinks the world to the outcomes inside BB. The conditional probability of AA is the share of that smaller world in which AA 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

  1. Fix the event BB you condition on. It must have positive probability.
  2. Find the probability that AA and BB both happen, then divide by P(B)P(B) to get P(A∣B)P(A \mid B).
  3. When the causes A1,…,AkA_1, \dots, A_k split the world into non-overlapping parts, get P(B)P(B) by summing P(B∣Ai) P(Ai)P(B \mid A_i)\,P(A_i) over the parts.
  4. Reverse the direction with Bayes' theorem: multiply each prior P(Ai)P(A_i) by its likelihood P(B∣Ai)P(B \mid A_i) and divide by P(B)P(B).
  5. From paired observations, count how often each pair (x,y)(x, y) occurs. Dividing each row by its total gives P(Y∣X)P(Y \mid X), and dividing each column by its total gives P(X∣Y)P(X \mid Y).
  6. 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

  • P(A∣B)P(A \mid B) and P(B∣A)P(B \mid A) 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 XX causes YY.

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

IfUse instead
The condition does not change the probability, so the events are independentBasic probability, multiplying the two probabilities
The unknown is a model parameter, not an eventBayesian inference
You condition on many variables and the table cells become too sparseNaive Bayes or logistic regression

Math foundations

  1. Definition

    P(A∣B)=P(A∩B)P(B),P(B)>0P(A \mid B) = \frac{P(A \cap B)}{P(B)}, \qquad P(B) > 0

    Restrict attention to the outcomes in BB and ask what share of them also lie in AA. Dividing by P(B)P(B) rescales that smaller world to total probability 1.

  2. Multiplication rule

    P(A∩B)=P(A∣B) P(B)=P(B∣A) P(A)P(A \cap B) = P(A \mid B)\,P(B) = P(B \mid A)\,P(A)

    The definition rearranged, and written both ways round. Setting the two right-hand sides equal is all that Bayes' theorem needs.

  3. Law of total probability

    P(B)=∑i=1kP(B∣Ai) P(Ai)P(B) = \sum_{i=1}^{k} P(B \mid A_i)\,P(A_i)

    If the events AiA_i do not overlap and together cover everything, then BB splits into its pieces inside each AiA_i. Their probabilities add.

  4. Bayes' theorem

    P(Ai∣B)=P(B∣Ai) P(Ai)∑j=1kP(B∣Aj) P(Aj)P(A_i \mid B) = \frac{P(B \mid A_i)\,P(A_i)}{\sum_{j=1}^{k} P(B \mid A_j)\,P(A_j)}

    The prior P(Ai)P(A_i) is reweighted by how well AiA_i explains the evidence BB, then normalized. The function posterior returns this for every ii at once.

  5. Estimate from counts, with smoothing

    P^(Y=y∣X=x)=nxy+λnx+λ K\hat{P}(Y = y \mid X = x) = \frac{n_{xy} + \lambda}{n_{x} + \lambda\,K}

    The share of the observations with X=xX = x that also have Y=yY = y. With λ=0\lambda = 0 it is the raw frequency. With λ=1\lambda = 1 every one of the KK values of YY gets one extra imagined observation.

Symbols

A, BA,\ B
events
A1,…,AkA_1, \dots, A_k
a partition: events that do not overlap and together cover every outcome
P(A∣B)P(A \mid B)
the probability of AA given that BB happened
P(Ai)P(A_i)
the prior probability of cause AiA_i
P(Ai∣B)P(A_i \mid B)
the posterior probability of cause AiA_i after seeing BB
nxyn_{xy}
the number of observations with X=xX = x and Y=yY = y
nxn_{x}
the number of observations with X=xX = x
λ\lambda
the smoothing count added to every cell (smoothing in the config)
KK
the number of distinct values of YY

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?

P(+)=0.95×0.01+0.05×0.99=0.0095+0.0495=0.059P(+) = 0.95 \times 0.01 + 0.05 \times 0.99 = 0.0095 + 0.0495 = 0.059
P(sick∣+)=0.95×0.010.059=0.00950.059≈0.161P(\text{sick} \mid +) = \frac{0.95 \times 0.01}{0.059} = \frac{0.0095}{0.059} \approx 0.161

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, yes
Read 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

  1. 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.

  2. 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.

  3. If P(A∣B)=P(A)P(A \mid B) = P(A), what must P(B∣A)P(B \mid A) 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.

  4. You estimate P(Y∣X)P(Y \mid X) from 20 observations where YY has 50 possible values. What does smoothing with λ=1\lambda = 1 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.

  5. 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.