1.6 Probability and Statistics

Machine learning is all about reasoning under uncertainty: predicting how likely a patient is to suffer a heart attack, judging whether a sensor reading is anomalous, or telling whether an accuracy difference from 0.900.90 (230/256230/256 test images) to 0.870.87 on the next minibatch reflects a real change or random sampling fluctuation.

Probability theory's cleanest thought experiment is still the coin toss: if a coin lands on heads 5656 times in 100100 tosses, should we suspect that it is biased? Even a fair coin rarely lands on heads exactly 5050 times, so we must ask whether a deviation of 66 heads is larger than chance routinely produces. Probability reasons forward from a known model (a fair coin) to the likelihood of outcomes, while statistics reasons backward from observed data (5656 heads in 100100 tosses) to infer properties of the underlying process.

In this section, we simulate coin tosses to watch sampling fluctuations unfold, introduce sample spaces, events, random variables, joint distributions, and independence, and derive the standard error σ/n\sigma/\sqrt{n} via expectation and variance to settle the coin question. We then develop conditional probability and Bayes' theorem on a two-step medical diagnostic test.

import random
from torch.distributions.multinomial import Multinomial

1.6.1 Sampling#

1.6.1.1 Simulated Coin Tosses#

For a fair coin, symmetry between heads and tails implies P(heads)=0.5P(\textrm{heads}) = 0.5. Drawing realizations from a random process is called sampling: below, we simulate 100100 tosses first by testing whether uniform draws from [0,1)[0, 1) exceed 0.50.5, and then using our framework's multinomial sampler with n=100n = 100 and probabilities (0.5,0.5)(0.5, 0.5):

num_tosses = 100
heads = sum([random.random() > 0.5 for _ in range(num_tosses)])
tails = num_tosses - heads
print("heads, tails: ", [heads, tails])
heads, tails:  [45, 55]
fair_probs = torch.tensor([0.5, 0.5])
Multinomial(100, fair_probs).sample()
tensor([48., 52.])

1.6.1.2 Frequencies and Probabilities#

Dividing the observed counts by nn gives the empirical frequency p^\hat{p}, an estimator of the true probability p=P(heads)=0.5p = P(\textrm{heads}) = 0.5. Repeating the 100-toss experiment five times simultaneously produces a 5×25 \times 2 matrix of empirical frequencies that fluctuate noticeably around 0.50.5:

Multinomial(100, fair_probs).sample((5,)) / 100
tensor([[0.5000, 0.5000],
        [0.4500, 0.5500],
        [0.5000, 0.5000],
        [0.4900, 0.5100],
        [0.5800, 0.4200]])

Increasing the sample size a hundredfold to n=10,000n = 10{,}000 tosses shrinks the typical sampling error by 100=10\sqrt{100} = 10, pulling the empirical head and tail frequencies much closer to (0.5,0.5)(0.5, 0.5):

Multinomial(10000, fair_probs).sample() / 10000
tensor([0.4959, 0.5041])

Tracking the running frequency after every toss from 11 to 10,00010{,}000 via cumsum illustrates the law of large numbers (Section 24.5), which guarantees that p^→p\hat{p} \to p as n→∞n \to \infty:

n = 10000
tosses = (torch.rand(n) < 0.5).to(torch.float32)  # 1 is heads, 0 is tails
estimates = tosses.cumsum(dim=0) / torch.arange(1, n + 1)
d2l.plot(torch.arange(1, n + 1), [estimates, torch.full((n,), 0.5)],
         'tosses', 'frequency of heads',
         legend=['running frequency', 'P(heads)'], xscale='log',
         figsize=(4.5, 3))

To know how fast p^\hat{p} settles—and whether 56/10056/100 is suspicious—we now formalize random variables and their spread.

1.6.2 Events and Random Variables#

1.6.2.1 Sample Spaces and Events#

The set of all possible outcomes of a random experiment is its sample space S\mathcal{S} (for one die roll, S={1,2,3,4,5,6}\mathcal{S} = \{1, 2, 3, 4, 5, 6\}). An event is any subset A⊆S\mathcal{A} \subseteq \mathcal{S} (such as "rolling an even number," A={2,4,6}\mathcal{A} = \{2, 4, 6\}, or "at least 55," B={5,6}\mathcal{B} = \{5, 6\}). A probability function PP assigns a real number to every event A⊆S\mathcal{A} \subseteq \mathcal{S} subject to Kolmogorov's three axioms (Kolmogorov, 1933):

  • Nonnegativity: P(A)≥0P(\mathcal{A}) \geq 0;
  • Normalization: P(S)=1P(\mathcal{S}) = 1;
  • Countable additivity: for mutually exclusive events A1,A2,…\mathcal{A}_1, \mathcal{A}_2, \ldots (Ai∩Aj=∅\mathcal{A}_i \cap \mathcal{A}_j = \emptyset for i≠ji \neq j), P(⋃iAi)=∑iP(Ai)P(\bigcup_i \mathcal{A}_i) = \sum_i P(\mathcal{A}_i).

From these axioms follow the complement rule P(A′)=1−P(A)P(\mathcal{A}') = 1 - P(\mathcal{A}), P(∅)=0P(\emptyset) = 0, and the inclusion--exclusion formula (Figure 1.6.1):

P(A∪B)=P(A)+P(B)−P(A∩B).(1.6.1)P(\mathcal{A} \cup \mathcal{B}) = P(\mathcal{A}) + P(\mathcal{B}) - P(\mathcal{A} \cap \mathcal{B}). \tag{1.6.1}
Figure 1.6.1:

Two events A\mathcal{A} and B\mathcal{B} in a sample space S\mathcal{S}. The sum P(A)+P(B)P(\mathcal{A}) + P(\mathcal{B}) counts the overlap A∩B\mathcal{A} \cap \mathcal{B} twice.

1.6.2.2 Random Variables and Distributions#

A random variable XX maps outcomes in S\mathcal{S} to numerical values (for example, the number of heads in 100100 coin tosses maps 21002^{100} sequences to {0,…,100}\{0, \ldots, 100\}). A discrete random variable assigns probability mass P(X=v)P(X = v) to each value vv (its distribution P(X)P(X)). A continuous random variable (such as a person's exact height) is described instead by a probability density p(x)p(x) (Figure 1.6.2), where the probability of landing in [a,b][a, b] is the area under the density curve, P(a≤X≤b)=∫abp(x) dxP(a \leq X \leq b) = \int_a^b p(x)\,dx (Section 24.1).

Figure 1.6.2:

A discrete random variable puts probability on individual values (left). A continuous random variable has a density, and the probability of an interval is the area under the density (right).

1.6.2.3 Joint, Marginal, and Independent Distributions#

The joint distribution P(X=x,Y=y)P(X = x, Y = y) of two random variables gives the probability that X=xX = x and Y=yY = y occur together. For example, for rain (XX) and carrying an umbrella (YY) on a random day:

P(X,Y)P(X, Y)umbrellano umbrella
rain0.250.05
no rain0.100.60

Summing out one variable recovers the marginal distribution of the other (marginalization, Figure 1.6.3):

P(X=x)=∑yP(X=x,Y=y),(1.6.2)P(X = x) = \sum_y P(X = x, Y = y), \tag{1.6.2}

so P(rain)=0.25+0.05=0.30P(\textrm{rain}) = 0.25 + 0.05 = 0.30 and P(umbrella)=0.25+0.10=0.35P(\textrm{umbrella}) = 0.25 + 0.10 = 0.35.

Figure 1.6.3:

A joint distribution P(X,Y)P(X, Y) as a table. Summing a row or a column gives a marginal distribution. Dividing a row by its sum gives a conditional distribution, here P(Y∣X=x2)P(Y \mid X = x_2).

Two random variables XX and YY are independent (X⊥YX \perp Y) if their joint distribution factorizes into the product of their marginals:

P(X,Y)=P(X)P(Y).(1.6.3)P(X, Y) = P(X) P(Y). \tag{1.6.3}

Successive coin tosses are independent, whereas rain and umbrellas are not (0.25≠0.30⋅0.35=0.1050.25 \neq 0.30 \cdot 0.35 = 0.105).

1.6.3 Expectation and Variance#

1.6.3.1 Expectation#

The expectation (or mean) of a discrete random variable XX is its probability-weighted average:

E[X]=∑xx P(X=x),(1.6.4)\mathbb{E}[X] = \sum_x x \, P(X = x), \tag{1.6.4}

and for any function ff, E[f(X)]=∑xf(x) P(X=x)\mathbb{E}[f(X)] = \sum_x f(x)\,P(X = x). For an investment returning 0×0\times with probability 0.50.5, 2×2\times with probability 0.40.4, and 10×10\times with probability 0.10.1, E[X]=0.5(0)+0.4(2)+0.1(10)=1.8\mathbb{E}[X] = 0.5(0) + 0.4(2) + 0.1(10) = 1.8. For a coin-toss indicator X=1(heads)∈{0,1}X = \mathbf{1}(\textrm{heads}) \in \{0, 1\}, E[X]=1⋅p+0⋅(1−p)=p\mathbb{E}[X] = 1\cdot p + 0\cdot(1-p) = p.

Expectation is always linear: E[aX+bY]=a E[X]+b E[Y]\mathbb{E}[aX + bY] = a\,\mathbb{E}[X] + b\,\mathbb{E}[Y] holds whether or not XX and YY are independent. Consequently, the sample frequency p^=1n∑i=1nXi\hat{p} = \frac{1}{n}\sum_{i=1}^n X_i satisfies E[p^]=1n∑i=1nE[Xi]=p\mathbb{E}[\hat{p}] = \frac{1}{n}\sum_{i=1}^n \mathbb{E}[X_i] = p, making p^\hat{p} an unbiased estimator of pp.

1.6.3.2 Variance and Sums of Independent Variables#

To measure spread around μ=E[X]\mu = \mathbb{E}[X], the variance averages the squared deviations, and the standard deviation σ=Var(X)\sigma = \sqrt{\textrm{Var}(X)} restores the original units:

Var(X)=E[(X−μ)2]=E[X2]−μ2,Var(aX+b)=a2 Var(X).(1.6.5)\textrm{Var}(X) = \mathbb{E}\left[(X - \mu)^2\right] = \mathbb{E}[X^2] - \mu^2, \qquad \textrm{Var}(aX + b) = a^2\,\textrm{Var}(X). \tag{1.6.5}

For our investment, E[X2]=0.5(0)+0.4(4)+0.1(100)=11.6\mathbb{E}[X^2] = 0.5(0) + 0.4(4) + 0.1(100) = 11.6, so Var(X)=11.6−1.82=8.36\textrm{Var}(X) = 11.6 - 1.8^2 = 8.36 (σ≈2.9\sigma \approx 2.9). For a single coin-toss indicator X∈{0,1}X \in \{0, 1\}, X2=XX^2 = X, so Var(X)=p−p2=p(1−p)\textrm{Var}(X) = p - p^2 = p(1 - p), which reaches its maximum 1/41/4 at p=0.5p = 0.5. When estimating variance from nn observations around their sample mean as in Section 1.2, dividing by n−1n - 1 (Bessel's correction) compensates for the slight downward bias of dividing by nn.

For a sum of two random variables, expanding E[(X−μX+Y−μY)2]\mathbb{E}[(X - \mu_X + Y - \mu_Y)^2] gives

Var(X+Y)=Var(X)+Var(Y)+2 Cov(X,Y),Cov(X,Y)=E[(X−μX)(Y−μY)],\begin{aligned} \textrm{Var}(X + Y) &= \textrm{Var}(X) + \textrm{Var}(Y) + 2\,\textrm{Cov}(X, Y), \\ \textrm{Cov}(X, Y) &= \mathbb{E}\left[(X - \mu_X)(Y - \mu_Y)\right], \end{aligned}

where the covariance Cov(X,Y)\textrm{Cov}(X, Y) and dimensionless correlation ρ=Cov(X,Y)/(σXσY)∈[−1,1]\rho = \textrm{Cov}(X, Y)/(\sigma_X\sigma_Y) \in [-1, 1] measure linear co-movement (Figure 1.6.4). More generally, for a random vector x∈Rd\mathbf{x} \in \mathbb{R}^d with mean μ=E[x]\boldsymbol{\mu} = \mathbb{E}[\mathbf{x}], collecting all pairwise covariances Σij=Cov(xi,xj)\Sigma_{ij} = \textrm{Cov}(x_i, x_j) forms the symmetric d×dd \times d covariance matrix Σ=E[(x−μ)(x−μ)⊤]\boldsymbol{\Sigma} = \mathbb{E}[(\mathbf{x}-\boldsymbol{\mu})(\mathbf{x}-\boldsymbol{\mu})^\top], and any linear combination v⊤x\mathbf{v}^\top\mathbf{x} has variance Var(v⊤x)=v⊤Σv\textrm{Var}(\mathbf{v}^\top\mathbf{x}) = \mathbf{v}^\top\boldsymbol{\Sigma}\mathbf{v}.

Figure 1.6.4:

Samples of three pairs of random variables, with positive, near-zero, and negative covariance.

When XX and YY are independent, their expectation factorizes so Cov(X,Y)=E[X−μX]E[Y−μY]=0\textrm{Cov}(X, Y) = \mathbb{E}[X - \mu_X]\mathbb{E}[Y - \mu_Y] = 0, and variances of independent variables add:

Var(X+Y)=Var(X)+Var(Y).(1.6.6)\textrm{Var}(X + Y) = \textrm{Var}(X) + \textrm{Var}(Y). \tag{1.6.6}

Zero covariance does not, however, imply independence: if XX takes −1,0,+1-1, 0, +1 with equal probability and Y=X2Y = X^2, then YY is completely determined by XX, yet by symmetry E[X]=0\mathbb{E}[X] = 0 and E[XY]=E[X3]=0\mathbb{E}[XY] = \mathbb{E}[X^3] = 0, giving Cov(X,Y)=0\textrm{Cov}(X, Y) = 0.

1.6.4 Estimation Error#

1.6.4.1 The Standard Error of a Frequency#

Because nn independent coin tosses each have variance p(1−p)p(1 - p), their sum has variance np(1−p)np(1 - p), and dividing by nn scales the variance by 1/n21/n^2:

Var(p^)=p(1−p)n.(1.6.7)\textrm{Var}(\hat{p}) = \frac{p(1-p)}{n}. \tag{1.6.7}

Taking the square root gives the standard error of p^\hat{p}: p(1−p)/n\sqrt{p(1-p)/n}, which for a fair coin (p=0.5p = 0.5) is 0.5/n0.5/\sqrt{n} (0.050.05 at n=100n = 100; 0.0050.005 at n=10,000n = 10{,}000). Because of the 1/n1/\sqrt{n} rate, halving the error requires 4×4\times the data. More generally, the average of any nn independent draws with variance σ2\sigma^2 has standard error σ/n\sigma/\sqrt{n}. Simulating 10001000 repetitions at each n∈{10,100,1000,10000}n \in \{10, 100, 1000, 10000\} confirms the 0.5/n0.5/\sqrt{n} line of slope −1/2-1/2:

ns = [10, 100, 1000, 10000]
stds = [float((torch.rand(1000, n) < 0.5).to(torch.float32)
              .mean(dim=1).std()) for n in ns]
d2l.plot(ns, [stds, [0.5 / n ** 0.5 for n in ns]], 'tosses n',
         'std of frequency', legend=['simulation', r'$0.5/\sqrt{n}$'],
         xscale='log', yscale='log', fmts=('o', '-'))

1.6.4.2 Testing for Bias and Uncertainty#

We can now answer our coin question. In 100100 tosses, p^=0.56\hat{p} = 0.56 is 0.06/0.05=1.20.06 / 0.05 = 1.2 standard errors from 0.50.5; in 10,00010{,}000 tosses, the same frequency p^=0.56\hat{p} = 0.56 (5,6005{,}600 heads) is 0.06/0.005=120.06 / 0.005 = 12 standard errors away. Simulating 10001000 fair-coin experiments shows how often a fair coin strays at least that far (estimating the p-value):

def fraction_as_far(heads, n, num_experiments=1000):
    """Fraction of fair-coin experiments at least as far from n/2 as heads."""
    counts = (torch.rand(num_experiments, n) < 0.5).sum(dim=1)
    far = (counts - n / 2).abs() >= abs(heads - n / 2)
    return far.to(torch.float32).mean()

fraction_as_far(56, 100), fraction_as_far(5600, 10000)
(tensor(0.2820), tensor(0.))

Roughly a quarter of fair 100-toss runs deviate by 66 or more heads, so 56/10056/100 is no evidence of bias, whereas zero out of 10001000 fair 10,000-toss runs come anywhere near 5,6005{,}600. Two general theorems quantify these tail probabilities: Chebyshev's inequality (Section 24.1) guarantees P(∣X−μ∣≥kσ)≤1/k2P(|X - \mu| \geq k\sigma) \leq 1/k^2 for any distribution with finite variance, while the central limit theorem (Section 24.3) shows that averages of independent draws approach a Gaussian bell curve, landing within 22 standard errors about 95%95\% of the time. The same arithmetic governs model evaluation: a classifier with true accuracy 0.90.9 has standard error 0.9⋅0.1/256≈0.019\sqrt{0.9 \cdot 0.1 / 256} \approx 0.019 on a single 256256-image minibatch (so ±2%\pm 2\% swings are ordinary noise), versus 0.0030.003 across a 10,00010{,}000-image test set.

Notice finally that collecting more data shrinks epistemic uncertainty (uncertainty about the model parameter pp, decaying as 1/n1/\sqrt{n}), but never reduces aleatoric uncertainty (the intrinsic 50/50 randomness of the next coin toss itself, or an inherently ambiguous image) (Der Kiureghian and Ditlevsen, 2009).

1.6.5 Conditional Probability#

1.6.5.1 Conditioning, Bayes' Theorem, and Conditional Independence#

Restricting attention to outcomes where X=xX = x (P(X=x)>0P(X = x) > 0) and renormalizing defines the conditional probability of Y=yY = y given X=xX = x:

P(Y=y∣X=x)=P(X=x,Y=y)P(X=x)⟹P(X,Y)=P(Y∣X)P(X).(1.6.8)P(Y = y \mid X = x) = \frac{P(X = x, Y = y)}{P(X = x)} \quad \Longrightarrow \quad P(X, Y) = P(Y \mid X) P(X). \tag{1.6.8}

In our weather table, conditioning on rain rescales the rain row (0.25,0.05)(0.25, 0.05) by 0.300.30 to give P(umbrella∣rain)=0.25/0.30≈0.83P(\textrm{umbrella} \mid \textrm{rain}) = 0.25/0.30 \approx 0.83 (versus 0.350.35 unconditionally). Writing the joint probability in both orders, P(X,Y)=P(Y∣X)P(X)=P(X∣Y)P(Y)P(X, Y) = P(Y \mid X)P(X) = P(X \mid Y)P(Y), and dividing by P(Y)=∑xP(Y∣X=x)P(X=x)P(Y) = \sum_x P(Y \mid X = x)P(X = x) yields Bayes' theorem (Bayes, 1763):

P(X∣Y)=P(Y∣X)P(X)P(Y).(1.6.9)P(X \mid Y) = \frac{P(Y \mid X) P(X)}{P(Y)}. \tag{1.6.9}

For a hypothesis HH and observed data DD, Bayes' theorem updates the prior P(H)P(H) via the likelihood P(D∣H)P(D \mid H) and evidence P(D)P(D) to produce the posterior P(H∣D)∝P(D∣H)P(H)P(H \mid D) \propto P(D \mid H)P(H).

Two variables XX and YY are conditionally independent given ZZ (X⊥Y∣ZX \perp Y \mid Z) if P(X,Y∣Z)=P(X∣Z)P(Y∣Z)P(X, Y \mid Z) = P(X \mid Z)P(Y \mid Z). Conditioning can either remove or introduce dependence (Figure 1.6.5): observing a common cause ZZ (such as a child's age) removes the correlation between shoe size and reading level, and observing the present state YY in a Markov chain X→Y→ZX \to Y \to Z renders past XX and future ZZ independent; conversely, conditioning on a common effect ZZ (explaining away) couples two independent causes, as when learning that a hospitalized patient has a broken bone lowers the probability they were admitted for lung cancer.

Figure 1.6.5:

Conditioning changes dependence. A common cause ZZ makes XX and YY dependent, and observing ZZ removes the dependence. In a chain, XX and ZZ are independent given YY. A common effect ZZ makes its independent causes dependent once ZZ is observed.

1.6.5.2 Example: Diagnostic Testing#

Suppose a patient takes an HIV screening test D1∈{0,1}D_1 \in \{0, 1\} with true HIV status H∈{0,1}H \in \{0, 1\}. The test has 100%100\% sensitivity and a 1%1\% false-positive rate:

P(D1∣H)P(D_1 \mid H)H=1H=1 (HIV)H=0H=0 (healthy)
test positive, D1=1D_1 = 11.000.01
test negative, D1=0D_1 = 00.000.99

If the population prevalence is P(H=1)=0.0015P(H = 1) = 0.0015 (P(H=0)=0.9985P(H = 0) = 0.9985) and the patient tests positive (D1=1D_1 = 1), marginalizing gives P(D1=1)=0.01(0.9985)+1(0.0015)=0.011485P(D_1 = 1) = 0.01(0.9985) + 1(0.0015) = 0.011485, and Bayes' theorem gives

P(H=1∣D1=1)=P(D1=1∣H=1)P(H=1)P(D1=1)=0.00150.011485=0.1306.(1.6.10)P(H = 1 \mid D_1 = 1) = \frac{P(D_1=1 \mid H=1) P(H=1)}{P(D_1=1)} = \frac{0.0015}{0.011485} = 0.1306. \tag{1.6.10}

Out of 10,00010{,}000 people (Figure 1.6.6), all 1515 infected people test positive, but so do 1%1\% of the 9,9859{,}985 healthy people (≈100\approx 100 false alarms), leaving only 15/115≈13%15 / 115 \approx 13\% of positive tests truly infected.

Figure 1.6.6:

The HIV test applied to 10,000 people. The 15 infected people test positive, and so do about 100 of the 9,985 healthy people, so only 15 of about 115 positive results are correct.

Now suppose a follow-up test D2D_2 (with P(D2=1∣H=1)=0.98P(D_2 = 1 \mid H = 1) = 0.98 and false-positive rate P(D2=1∣H=0)=0.03P(D_2 = 1 \mid H = 0) = 0.03) also comes back positive. Assuming D1D_1 and D2D_2 are conditionally independent given HH, the joint false-positive rate drops to 0.01⋅0.03=0.00030.01 \cdot 0.03 = 0.0003 while sensitivity is 1⋅0.98=0.981 \cdot 0.98 = 0.98. Marginalizing gives P(D1=1,D2=1)=0.0003(0.9985)+0.98(0.0015)=0.00176955P(D_1 = 1, D_2 = 1) = 0.0003(0.9985) + 0.98(0.0015) = 0.00176955, and Bayes' theorem raises the posterior probability of infection (Figure 1.6.7) to

P(H=1∣D1=1,D2=1)=0.98⋅0.00150.00176955=0.8307.(1.6.11)P(H = 1 \mid D_1 = 1, D_2 = 1) = \frac{0.98 \cdot 0.0015}{0.00176955} = 0.8307. \tag{1.6.11}

Simulating two million virtual patients yields an empirical fraction around 0.82–0.830.82\text{--}0.83, within two ±0.006\pm 0.006 standard errors (0.83⋅0.17/3500\sqrt{0.83 \cdot 0.17 / 3500}) of the exact value 0.83070.8307 across the ≈3,500\approx 3{,}500 double-positive patients:

Figure 1.6.7:

The probability that the patient has HIV: the prior, after one positive test, and after two conditionally independent positive tests.

n = 2000000
H = torch.rand(n) < 0.0015
D1 = torch.rand(n) < torch.where(H, 1.00, 0.01)
D2 = torch.rand(n) < torch.where(H, 0.98, 0.03)
H[D1 & D2].to(torch.float32).mean()  # Exact value: 0.8307
tensor(0.8220)

1.6.6 Summary#

Probability reasons forward from a model to the likelihood of outcomes, whereas statistics reasons backward from observed data to infer properties of the underlying process. Built on Kolmogorov's three axioms, joint distributions P(X,Y)P(X, Y) marginalize by summing out variables and factorize as P(X)P(Y)P(X)P(Y) when variables are independent. Expectation E[X]\mathbb{E}[X] is always linear, while variance Var(X)=E[(X−μ)2]\textrm{Var}(X) = \mathbb{E}[(X-\mu)^2] adds across independent variables, giving the average of nn independent draws standard error σ/n\sigma/\sqrt{n}: measuring deviations in standard errors shows why 56/10056/100 heads (1.21.2 standard errors) is routine chance whereas 5,600/10,0005{,}600/10{,}000 (1212 standard errors) is decisive, and why collecting more data shrinks epistemic uncertainty as 1/n1/\sqrt{n} while leaving aleatoric uncertainty unchanged. Finally, Bayes' theorem P(H∣D)=P(D∣H)P(H)/P(D)P(H \mid D) = P(D \mid H)P(H)/P(D) updates prior beliefs in light of evidence, explaining why a single positive test for a rare condition (0.15%0.15\% prevalence, 1%1\% false-positive rate) yields only a 13.1%13.1\% posterior until a second conditionally independent test raises it to 83.1%83.1\%.

1.6.7 Exercises#

  1. Portfolio return and risk. Assume that you manage a portfolio of nn stocks whose returns s∈Rn\mathbf{s} \in \mathbb{R}^n are random with mean μ=E[s]\boldsymbol{\mu} = \mathbb{E}[\mathbf{s}] and covariance matrix Σ\boldsymbol{\Sigma}. You invest a fraction αi≥0\alpha_i \geq 0 of your capital in stock ii, with ∑iαi=1\sum_i \alpha_i = 1.

    1. Compute the expected return and the variance of the return of the portfolio α\boldsymbol{\alpha}.
    2. Assume that every stock has variance σ2\sigma^2 and that every pair of distinct stocks has correlation ρ≥0\rho \geq 0. Compute the variance of the equally weighted portfolio αi=1/n\alpha_i = 1/n and its limit as n→∞n \to \infty. Compare the case ρ=0\rho = 0 with (1.6.7).
    3. (Optional.) Formulate an optimization problem that maximizes the expected return while constraining the variance to an upper bound. This is the Markowitz portfolio problem (Markowitz, 1952). Methods for constrained problems of this kind are developed in Section 23.6.
  2. [code] Chebyshev for the coin-toss estimator. (1.6.7) gives the variance of the frequency p^\hat{p} of heads after nn tosses.

    1. For a fair coin and n=100n = 100, use Chebyshev's inequality to bound P(∣p^−p∣≥0.1)P(|\hat{p} - p| \geq 0.1).
    2. Estimate the same probability by simulating 10,000 repetitions of 100 tosses, compare it with the bound, and account for the gap.
    3. Determine how many tosses Chebyshev's inequality requires to guarantee P(∣p^−p∣≥0.01)≤0.05P(|\hat{p} - p| \geq 0.01) \leq 0.05 for a fair coin, and compare with the nn at which the standard error p(1−p)/n\sqrt{p(1-p)/n} itself equals 0.010.01.
  3. Comparing two classifiers. ● Two classifiers are evaluated on the same test set of n=10,000n = 10{,}000 images. Classifier A labels 9,050 images correctly and classifier B labels 9,000 correctly. Treat the test images as independent draws.

    1. Compute the standard error of each accuracy.
    2. Assume that the two accuracies are independent and compute the standard error of their difference. Is the difference of 0.0050.005 large compared with the noise?
    3. The two accuracies are measured on the same images, so they are not independent. Suppose that the classifiers disagree on 300 images, A being correct on 175 of them and B on 125. For image ii, let Zi=1Z_i = 1 if only A is correct, Zi=−1Z_i = -1 if only B is correct, and Zi=0Z_i = 0 otherwise, so that the difference in accuracy is the average of the ZiZ_i. Compute the standard error of this average and compare it with your answer to the previous part.
    4. Use Var(X−Y)=Var(X)+Var(Y)−2 Cov(X,Y)\textrm{Var}(X - Y) = \textrm{Var}(X) + \textrm{Var}(Y) - 2\,\textrm{Cov}(X, Y) to explain the difference. What sign does the covariance between the two classifiers' correctness on an image have, and why?
  4. Factorizing a chain. Let XX, YY, and ZZ be random variables such that ZZ is conditionally independent of XX given YY, as in the chain of Figure 1.6.5.

    1. Write the joint probability P(X,Y,Z)P(X, Y, Z) as a product of factors that each involve at most two of the variables.
    2. Generalize to a sequence X1,…,XTX_1, \ldots, X_T in which each XtX_t depends on the earlier variables only through Xt−1X_{t-1}. How many numbers specify the joint distribution if every XtX_t takes kk values, compared with an arbitrary joint distribution of TT such variables?
  5. Conditioning on a common effect. Toss two independent fair coins, and let X,Y∈{0,1}X, Y \in \{0, 1\} indicate heads on each. Let Z=max⁡(X,Y)Z = \max(X, Y) indicate that at least one coin came up heads. Compute P(X=1)P(X = 1), P(X=1∣Z=1)P(X = 1 \mid Z = 1), and P(X=1∣Z=1,Y=1)P(X = 1 \mid Z = 1, Y = 1). Use these values to decide whether XX and YY are conditionally independent given Z=1Z = 1, and relate the change from the second value to the third to Figure 1.6.5.

  6. A second, correlated test. ● Revisit Section 1.6.5.2 with two new tests whose outcomes are conditionally independent for patients with HIV but not for healthy patients. Either test on its own has a false positive rate of 10% and a false negative rate of 1%:

P(Di=1∣H=0)=0.1,P(Di=0∣H=1)=0.01for i=1,2.(1.6.12)P(D_i = 1 \mid H = 0) = 0.1, \quad P(D_i = 0 \mid H = 1) = 0.01 \quad \textrm{for } i = 1, 2. \tag{1.6.12}

For H=1H = 1, the joint distribution factorizes as P(D1,D2∣H=1)=P(D1∣H=1) P(D2∣H=1)P(D_1, D_2 \mid H = 1) = P(D_1 \mid H = 1)\, P(D_2 \mid H = 1). For H=0H = 0, the outcomes are coupled through P(D1=D2=1∣H=0)=0.02P(D_1 = D_2 = 1 \mid H = 0) = 0.02. The baseline probability is P(H=1)=0.0015P(H = 1) = 0.0015 as before.

  1. Work out the joint probability table for D1D_1 and D2D_2 given H=0H = 0.

  2. Derive the probability that the patient has HIV after the first test returns positive, before the second test is run.

  3. Derive the probability that the patient has HIV after both tests return positive.

  4. Repeat the previous calculation for tests that are conditionally independent given H=0H = 0 as well, and explain why the two posteriors differ.

  5. A defense lawyer's statistics. A suspect had a documented history of abusing his now-murdered wife. His lawyer argues that, statistically, only one in a thousand wife-abusers goes on to murder his wife, so the history of abuse is weak evidence and the jury should acquit. Write MM for "the suspect murdered his wife," KK for "his wife was killed," and BB for "he had a history of abusing her."

    1. Express the lawyer's one-in-a-thousand figure and the posterior probability of guilt in these terms, and identify which probability the lawyer has confused with which.
    2. Assume that, over the time span the lawyer's statistic refers to, an abused wife is murdered by someone other than her husband with probability 10−510^{-5}. Compute the posterior probability of guilt and compare it with the lawyer's figure.

    Adapted from MIT 18.05, problem set 7, Problem 4.

Discussions