Skip to main content

2  Conditioning, Bayes’ rule and independence

A probability can change when we learn something about the outcome. Conditional probability describes this change without changing the underlying experiment. It forms the foundation of Bayesian inference, probabilistic classifiers and many scientific decisions.

2.1 Restricting the sample space

Given an event \(B\) with \(\Pr(B)>0\), define

\[ \Pr(A\mid B)=\frac{\Pr(A\cap B)}{\Pr(B)}. \]

For fixed \(B\), the function \(A\mapsto\Pr(A\mid B)\) is itself a probability measure. It is nonnegative; its mass on \(\Omega\) is \(\Pr(B)/\Pr(B)=1\); and for disjoint \(A_i\), their intersections with \(B\) are disjoint, so countable additivity follows from that of \(\Pr\). Conditional probability thus gives a mathematically consistent probability space after restriction.

2.1.1 Worked example: a diagnostic log

During 800 program runs, 160 have a slow response, 100 produce a retry, and 64 have both properties. Let \(S\) denote slow response and \(R\) denote retry.

Retry No retry Total
Slow 64 96 160
Not slow 36 604 640
Total 100 700 800

Under uniform sampling of a recorded run, \(\Pr(R\mid S)=64/160=0.40\), whereas \(\Pr(S\mid R)=64/100=0.64\). The numerator is the same, but the denominator changes. One asks about retry frequency among slow runs; the other asks about slow-run frequency among retries.

Always read the event written after the conditioning bar as the given information, not as the event being predicted.

2.2 The multiplication and chain rules

Rearrange the definition to obtain

\[ \Pr(A\cap B)=\Pr(B)\Pr(A\mid B). \]

For events \(A_1,\ldots,A_k\) whose conditioning intersections have positive probability, apply this repeatedly:

\[ \Pr\left(\bigcap_{i=1}^k A_i\right) =\Pr(A_1)\prod_{j=2}^k \Pr\left(A_j\mid\bigcap_{i=1}^{j-1}A_i\right). \]

Proof by induction. For \(k=2\) this is the multiplication rule. Assume the product holds through \(k-1\). Treat \(B=\bigcap_{i=1}^{k-1}A_i\) as one event and multiply \(\Pr(B)\) by \(\Pr(A_k\mid B)\). Substitution yields the next product.

2.2.1 Worked example: adaptive routing

A dispatcher sends a randomly selected package through route A with probability \(0.55\), B with probability \(0.30\), or C with probability \(0.15\). The probabilities of a delay given the routes are respectively \(0.03,0.09,0.20\). The event that a package takes B and is delayed has probability \(0.30(0.09)=0.027\).

flowchart TB
  S["Package"] -->|0.55| A["Route A"]
  S -->|0.30| B["Route B"]
  S -->|0.15| C["Route C"]
  A -->|0.03 delayed| AD["0.0165 joint"]
  B -->|0.09 delayed| BD["0.0270 joint"]
  C -->|0.20 delayed| CD["0.0300 joint"]

Each complete path has the product of its branch probabilities. Different route-and-delay paths are disjoint, a fact that lets us add their masses.

2.3 The law of total probability

Let \(B_1,\ldots,B_m\) partition \(\Omega\) and have positive probabilities. For any event \(A\), the events \(A\cap B_i\) partition \(A\). Additivity and the multiplication rule imply

\[ \Pr(A)=\sum_{i=1}^m \Pr(A\mid B_i)\Pr(B_i). \]

The law can be read as a weighted average of conditional probabilities. It is often useful when the marginal event is difficult to calculate directly but its probability is known under different regimes.

For the package example, \(\Pr(D)=0.0165+0.027+0.030=0.0735\). Even though route C has the highest conditional delay probability, it handles only 15% of packages. The calculation combines both facts.

2.4 Bayes’ theorem

The multiplication rule gives two expressions for the same intersection:

\[ \Pr(A\mid B)\Pr(B)=\Pr(B\mid A)\Pr(A). \]

Divide by \(\Pr(A)>0\) and substitute the law of total probability when \(B_1,\ldots,B_m\) form a partition:

\[ \boxed{\Pr(B_j\mid A)= \frac{\Pr(A\mid B_j)\Pr(B_j)} {\sum_{i=1}^m\Pr(A\mid B_i)\Pr(B_i)}}. \]

This is Bayes’ theorem. The prior \(\Pr(B_j)\) describes uncertainty before the observed event \(A\); the likelihood \(\Pr(A\mid B_j)\) tells how probable the observation is under a candidate explanation; and the denominator normalizes the updated probabilities. The result \(\Pr(B_j\mid A)\) is a posterior probability.

For the package that is known to be delayed,

\[ \Pr(C\mid D)=\frac{0.0300}{0.0735}=\frac{20}{49}\approx0.4082. \]

The prior weight of C was \(0.15\); the delayed observation raises this to about \(0.408\). It does not establish C with certainty. Routes A and B can also cause delays.

Grouped bar chart comparing prior route probabilities 0.55, 0.30, 0.15 to posterior probabilities after a delay.

Prior route probabilities and their posterior probabilities after observing a delay.

The Bayesian denominator has a convenient diagnostic role. If every candidate model assigns the observation zero likelihood, there is no posterior update using these candidates: the stated model cannot explain what happened.

2.4.1 The odds formulation

For mutually exclusive alternatives \(H\) and \(H^c\), if denominators are positive, posterior odds satisfy

\[ \frac{\Pr(H\mid A)}{\Pr(H^c\mid A)} = \frac{\Pr(A\mid H)}{\Pr(A\mid H^c)} \frac{\Pr(H)}{\Pr(H^c)}. \]

The likelihood ratio multiplies the prior odds. This form is convenient when observations arrive sequentially. If observations \(A_1\) and \(A_2\) are conditionally independent under each hypothesis, their joint likelihood is a product, so their likelihood ratios multiply. Taking logarithms transforms the sequence into additive evidence.

2.4.2 Worked example: an unusual reading

A factory has a rare calibration fault on 1% of operating shifts. A monitor warns on 90% of faulty shifts and on 4% of normal shifts. After a warning,

\[ \Pr(F\mid W)=\frac{0.90(0.01)} {0.90(0.01)+0.04(0.99)} =\frac{0.009}{0.0486}\approx0.1852. \]

A sensitive monitor can have a relatively low proportion of true faults among warnings when the underlying fault is rare. The result differs from the sensitivity \(\Pr(W\mid F)=0.90\).

If a second independently calibrated monitor has the same conditional rates and emits a warning, the joint conditional likelihoods become \(0.90^2\) and \(0.04^2\). The new posterior is \(0.0081/(0.0081+0.001584)\approx0.8364\). The conditional independence assumption is critical: two screens displaying identical readings are not two independent sources of evidence.

2.5 Independence

Events \(A\) and \(B\) are independent if

\[ \Pr(A\cap B)=\Pr(A)\Pr(B). \]

If \(\Pr(B)>0\), this is equivalent to \(\Pr(A\mid B)=\Pr(A)\). The product criterion also handles zero-probability events without needing division. Independence is symmetric, although a conditional statement need not be.

Complement property. If \(A\) and \(B\) are independent, then \(A\) and \(B^c\) are independent. To prove it,

\[ \begin{aligned} \Pr(A\cap B^c) &=\Pr(A)-\Pr(A\cap B)\\ &=\Pr(A)\{1-\Pr(B)\}=\Pr(A)\Pr(B^c). \end{aligned} \]

For \(m\) events, mutual independence requires the product rule for every nonempty subcollection. Checking only all pairs is insufficient.

2.5.1 Pairwise independence need not be mutual

Choose one of \(\{00,01,10,11\}\) uniformly. Let \(A\) mean the first bit is zero, \(B\) mean the second bit is zero, and \(C\) mean the two bits agree. All three have probability \(1/2\). Every pair has intersection probability \(1/4\), so they are pairwise independent. But \(A\cap B\cap C=\{00\}\), which has probability \(1/4\), different from \((1/2)^3=1/8\).

This counterexample shows why a claim of “independent observations” cannot generally be justified by reporting only zero pairwise correlation or pairwise tests of independence.

2.5.2 Conditional independence

We say \(A\) and \(B\) are conditionally independent given \(C\) if

\[ \Pr(A\cap B\mid C)=\Pr(A\mid C)\Pr(B\mid C). \]

Conditional independence and marginal independence are different. Consider random requests from two data centers, selected with equal probability. At the first, each of two independent requests fails with probability \(0.02\); at the second, the failure probability is \(0.20\). Within a given center, failures are independent. Without knowing the center,

\[ \Pr(F_1)=\Pr(F_2)=0.11,\qquad \Pr(F_1\cap F_2)=\tfrac12(0.02^2+0.20^2)=0.0202. \]

The product of marginals is \(0.0121\), not \(0.0202\). Sharing an unobserved regime produces dependence after the regime is averaged out.

2.6 Python experiment: simulate a Bayesian update

Use the route model above. We draw the latent route first and generate a delay with the corresponding probability. This mirrors the factorization \(\Pr(R,D)=\Pr(R)\Pr(D\mid R)\).

import numpy as np

rng = np.random.default_rng(202)
prior = np.array([.55, .30, .15])
likelihood = np.array([.03, .09, .20])
joint = prior * likelihood
posterior = joint / joint.sum()

N = 250_000
route = rng.choice(3, size=N, p=prior)
delayed = rng.random(N) < likelihood[route]
empirical = np.bincount(route[delayed], minlength=3) / delayed.sum()
print("Analytic posterior:", posterior.round(4))
print("Conditional frequencies:", empirical.round(4))
assert np.max(np.abs(empirical - posterior)) < .02

The conditional sample size is the number of delayed packages, not the total \(N\). For rare observations, simulations may need many repetitions to make the conditional-frequency estimate precise. In a finite model, the direct calculation is often simpler and more accurate.

2.7 Practice problems

Work in your browser with Google Colab, or download the notebooks for Jupyter.

Practice notebook

Open in Colab Download .ipynb

Worked solutions

Open in Colab Download .ipynb

2.7.1 Exercise 1: A sequential inventory experiment

A bag contains 6 standard and 4 premium components. Draw three without replacement. Find the probability of the ordered pattern premium, standard, premium. Then find the probability of exactly two premium items regardless of order.

The ordered pattern has probability \((4/10)(6/9)(3/8)=1/10\). The three placements of the one standard selection have equal probability; the total is \(3/10\). Equivalently, \(\binom42\binom61/\binom{10}3=36/120=3/10\).

2.7.2 Exercise 2: Inverting an imperfect indicator

Thirty percent of devices use a new firmware version \(N\). A timeout is reported in 8% of new-version sessions and 2% of old-version sessions. Find the marginal probability of timeout and the probability of \(N\) given a timeout. Is timeout more likely under \(N\) than under the old version?

The marginal timeout probability is \(0.3(0.08)+0.7(0.02)=0.038\). The posterior is \(0.024/0.038=12/19\approx0.632\). Timeout has a likelihood ratio \(0.08/0.02=4\) in favor of \(N\). The posterior exceeds the prior because the timeout is more likely under \(N\).

2.7.3 Exercise 3: Independence from a probability table

Let \(\Pr(A)=0.45\), \(\Pr(B)=0.60\) and \(\Pr(A\cup B)=0.78\). Determine whether \(A\) and \(B\) are independent. Compute \(\Pr(A^c\mid B)\) and \(\Pr(B^c\mid A)\).

The intersection is \(0.45+0.60-0.78=0.27\). This equals \(0.45(0.60)\), hence the events are independent. \(\Pr(A^c\mid B)=1-0.45=0.55\), and \(\Pr(B^c\mid A)=1-0.60=0.40\).

2.7.4 Exercise 4: Python — how base rates change evidence

For a monitor with sensitivity \(0.92\) and false-positive rate \(0.06\), vary the prior fault probability from \(0.001\) to \(0.50\). Derive the posterior probability given a warning as a function of the prior. Calculate the prior that makes the posterior exactly \(0.5\). Plot the function, then simulate at prior \(0.02\) and compare.

Write \(g(p)=0.92p/[0.92p+0.06(1-p)]\). Setting \(g(p)=1/2\) gives \(0.92p=0.06(1-p)\), so \(p=0.06/0.98\approx0.06122\).

import numpy as np
import matplotlib.pyplot as plt

def posterior(p, sens=.92, fpr=.06):
    p = np.asarray(p)
    return sens*p / (sens*p + fpr*(1-p))

p_star = .06 / (.92 + .06)
assert np.isclose(posterior(p_star), .5)
rng = np.random.default_rng(82)
fault = rng.random(300_000) < .02
warn = rng.random(fault.size) < np.where(fault, .92, .06)
print("At p=.02:", posterior(.02), fault[warn].mean())
grid = np.linspace(.001, .5, 400)
plt.plot(grid, posterior(grid), label="Posterior given warning")
plt.plot(grid, grid, "--", color="gray", label="No change")
plt.scatter([p_star], [.5], c="tab:orange")
plt.xlabel("Prior fault probability")
plt.ylabel("Posterior fault probability")
plt.legend()
plt.show()

When the prior is \(0.02\), only a minority of warnings are true faults, even though sensitivity is high. The situation changes as the prior grows.

2.7.5 Exercise 5: Python — latent groups create dependence

A workload is easy or difficult, with probabilities \(0.7\) and \(0.3\). Two independently running workers finish successfully with probability \(0.95\) on an easy workload and \(0.65\) on a difficult one. Both workers share the same workload. Derive all four joint outcome probabilities. Simulate 200,000 workloads and compare \(\Pr(S_1,S_2)\) with \(\Pr(S_1)\Pr(S_2)\). Then repeat with a separate independent difficulty draw for each worker.

For a shared difficulty, the mass of two successes is \(0.7(0.95)^2+0.3(0.65)^2=0.7585\). A success has marginal probability \(0.86\). Each mixed outcome has probability \(0.86-0.7585=0.1015\), and two failures have mass \(1-0.7585-2(0.1015)=0.0385\). The independent product is \(0.86^2=0.7396\).

import numpy as np

rng = np.random.default_rng(94)
N = 200_000
shared = rng.random(N) < .3
probs = np.where(shared, .65, .95)
s1, s2 = (rng.random(N) < probs for _ in range(2))
print("Shared: joint", (s1 & s2).mean(),
      "product", s1.mean()*s2.mean())
groups = rng.random((N, 2)) < .3
ind = rng.random((N, 2)) < np.where(groups, .65, .95)
print("Separate: joint", ind.all(axis=1).mean(),
      "product", ind.mean(axis=0).prod())
assert abs((s1 & s2).mean() - .7585) < .006
assert abs(ind.all(axis=1).mean() - .7396) < .006

Separate difficulty variables remove the common cause. Conditional independence with a shared cause, however, does not imply unconditional independence.