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 ( test images) to 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 times in tosses, should we suspect that it is biased? Even a fair coin rarely lands on heads exactly times, so we must ask whether a deviation of 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 ( heads in 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 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 Multinomial1.6.1 Sampling#
1.6.1.1 Simulated Coin Tosses#
For a fair coin, symmetry between heads and tails implies . Drawing realizations from a random process is called sampling: below, we simulate tosses first by testing whether uniform draws from exceed , and then using our framework's multinomial sampler with and probabilities :
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 gives the empirical frequency , an estimator of the true probability . Repeating the 100-toss experiment five times simultaneously produces a matrix of empirical frequencies that fluctuate noticeably around :
Multinomial(100, fair_probs).sample((5,)) / 100tensor([[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 tosses shrinks the typical sampling error by , pulling the empirical head and tail frequencies much closer to :
Multinomial(10000, fair_probs).sample() / 10000tensor([0.4959, 0.5041])
Tracking the running frequency after every toss from to via cumsum illustrates the law of large numbers (Section 24.5), which guarantees that as :
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 settles—and whether 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 (for one die roll, ). An event is any subset (such as "rolling an even number," , or "at least ," ). A probability function assigns a real number to every event subject to Kolmogorov's three axioms (Kolmogorov, 1933):
- Nonnegativity: ;
- Normalization: ;
- Countable additivity: for mutually exclusive events ( for ), .
From these axioms follow the complement rule , , and the inclusion--exclusion formula (Figure 1.6.1):
Two events and in a sample space . The sum counts the overlap twice.
1.6.2.2 Random Variables and Distributions#
A random variable maps outcomes in to numerical values (for example, the number of heads in coin tosses maps sequences to ). A discrete random variable assigns probability mass to each value (its distribution ). A continuous random variable (such as a person's exact height) is described instead by a probability density (Figure 1.6.2), where the probability of landing in is the area under the density curve, (Section 24.1).
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 of two random variables gives the probability that and occur together. For example, for rain () and carrying an umbrella () on a random day:
| umbrella | no umbrella | |
|---|---|---|
| rain | 0.25 | 0.05 |
| no rain | 0.10 | 0.60 |
Summing out one variable recovers the marginal distribution of the other (marginalization, Figure 1.6.3):
so and .
A joint distribution as a table. Summing a row or a column gives a marginal distribution. Dividing a row by its sum gives a conditional distribution, here .
Two random variables and are independent () if their joint distribution factorizes into the product of their marginals:
Successive coin tosses are independent, whereas rain and umbrellas are not ().
1.6.3 Expectation and Variance#
1.6.3.1 Expectation#
The expectation (or mean) of a discrete random variable is its probability-weighted average:
and for any function , . For an investment returning with probability , with probability , and with probability , . For a coin-toss indicator , .
Expectation is always linear: holds whether or not and are independent. Consequently, the sample frequency satisfies , making an unbiased estimator of .
1.6.3.2 Variance and Sums of Independent Variables#
To measure spread around , the variance averages the squared deviations, and the standard deviation restores the original units:
For our investment, , so (). For a single coin-toss indicator , , so , which reaches its maximum at . When estimating variance from observations around their sample mean as in Section 1.2, dividing by (Bessel's correction) compensates for the slight downward bias of dividing by .
For a sum of two random variables, expanding gives
where the covariance and dimensionless correlation measure linear co-movement (Figure 1.6.4). More generally, for a random vector with mean , collecting all pairwise covariances forms the symmetric covariance matrix , and any linear combination has variance .
Samples of three pairs of random variables, with positive, near-zero, and negative covariance.
When and are independent, their expectation factorizes so , and variances of independent variables add:
Zero covariance does not, however, imply independence: if takes with equal probability and , then is completely determined by , yet by symmetry and , giving .
1.6.4 Estimation Error#
1.6.4.1 The Standard Error of a Frequency#
Because independent coin tosses each have variance , their sum has variance , and dividing by scales the variance by :
Taking the square root gives the standard error of : , which for a fair coin () is ( at ; at ). Because of the rate, halving the error requires the data. More generally, the average of any independent draws with variance has standard error . Simulating repetitions at each confirms the line of slope :
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 tosses, is standard errors from ; in tosses, the same frequency ( heads) is standard errors away. Simulating 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 or more heads, so is no evidence of bias, whereas zero out of fair 10,000-toss runs come anywhere near . Two general theorems quantify these tail probabilities: Chebyshev's inequality (Section 24.1) guarantees 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 standard errors about of the time. The same arithmetic governs model evaluation: a classifier with true accuracy has standard error on a single -image minibatch (so swings are ordinary noise), versus across a -image test set.
Notice finally that collecting more data shrinks epistemic uncertainty (uncertainty about the model parameter , decaying as ), 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 () and renormalizing defines the conditional probability of given :
In our weather table, conditioning on rain rescales the rain row by to give (versus unconditionally). Writing the joint probability in both orders, , and dividing by yields Bayes' theorem (Bayes, 1763):
For a hypothesis and observed data , Bayes' theorem updates the prior via the likelihood and evidence to produce the posterior .
Two variables and are conditionally independent given () if . Conditioning can either remove or introduce dependence (Figure 1.6.5): observing a common cause (such as a child's age) removes the correlation between shoe size and reading level, and observing the present state in a Markov chain renders past and future independent; conversely, conditioning on a common effect (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.
Conditioning changes dependence. A common cause makes and dependent, and observing removes the dependence. In a chain, and are independent given . A common effect makes its independent causes dependent once is observed.
1.6.5.2 Example: Diagnostic Testing#
Suppose a patient takes an HIV screening test with true HIV status . The test has sensitivity and a false-positive rate:
| (HIV) | (healthy) | |
|---|---|---|
| test positive, | 1.00 | 0.01 |
| test negative, | 0.00 | 0.99 |
If the population prevalence is () and the patient tests positive (), marginalizing gives , and Bayes' theorem gives
Out of people (Figure 1.6.6), all infected people test positive, but so do of the healthy people ( false alarms), leaving only of positive tests truly infected.
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 (with and false-positive rate ) also comes back positive. Assuming and are conditionally independent given , the joint false-positive rate drops to while sensitivity is . Marginalizing gives , and Bayes' theorem raises the posterior probability of infection (Figure 1.6.7) to
Simulating two million virtual patients yields an empirical fraction around , within two standard errors () of the exact value across the double-positive patients:
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.8307tensor(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 marginalize by summing out variables and factorize as when variables are independent. Expectation is always linear, while variance adds across independent variables, giving the average of independent draws standard error : measuring deviations in standard errors shows why heads ( standard errors) is routine chance whereas ( standard errors) is decisive, and why collecting more data shrinks epistemic uncertainty as while leaving aleatoric uncertainty unchanged. Finally, Bayes' theorem updates prior beliefs in light of evidence, explaining why a single positive test for a rare condition ( prevalence, false-positive rate) yields only a posterior until a second conditionally independent test raises it to .
1.6.7 Exercises#
-
Portfolio return and risk. Assume that you manage a portfolio of stocks whose returns are random with mean and covariance matrix . You invest a fraction of your capital in stock , with .
- Compute the expected return and the variance of the return of the portfolio .
- Assume that every stock has variance and that every pair of distinct stocks has correlation . Compute the variance of the equally weighted portfolio and its limit as . Compare the case with (1.6.7).
- (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.
-
[code] Chebyshev for the coin-toss estimator. (1.6.7) gives the variance of the frequency of heads after tosses.
- For a fair coin and , use Chebyshev's inequality to bound .
- Estimate the same probability by simulating 10,000 repetitions of 100 tosses, compare it with the bound, and account for the gap.
- Determine how many tosses Chebyshev's inequality requires to guarantee for a fair coin, and compare with the at which the standard error itself equals .
-
Comparing two classifiers. ● Two classifiers are evaluated on the same test set of images. Classifier A labels 9,050 images correctly and classifier B labels 9,000 correctly. Treat the test images as independent draws.
- Compute the standard error of each accuracy.
- Assume that the two accuracies are independent and compute the standard error of their difference. Is the difference of large compared with the noise?
- 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 , let if only A is correct, if only B is correct, and otherwise, so that the difference in accuracy is the average of the . Compute the standard error of this average and compare it with your answer to the previous part.
- Use to explain the difference. What sign does the covariance between the two classifiers' correctness on an image have, and why?
-
Factorizing a chain. Let , , and be random variables such that is conditionally independent of given , as in the chain of Figure 1.6.5.
- Write the joint probability as a product of factors that each involve at most two of the variables.
- Generalize to a sequence in which each depends on the earlier variables only through . How many numbers specify the joint distribution if every takes values, compared with an arbitrary joint distribution of such variables?
-
Conditioning on a common effect. Toss two independent fair coins, and let indicate heads on each. Let indicate that at least one coin came up heads. Compute , , and . Use these values to decide whether and are conditionally independent given , and relate the change from the second value to the third to Figure 1.6.5.
-
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%:
For , the joint distribution factorizes as . For , the outcomes are coupled through . The baseline probability is as before.
-
Work out the joint probability table for and given .
-
Derive the probability that the patient has HIV after the first test returns positive, before the second test is run.
-
Derive the probability that the patient has HIV after both tests return positive.
-
Repeat the previous calculation for tests that are conditionally independent given as well, and explain why the two posteriors differ.
-
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 for "the suspect murdered his wife," for "his wife was killed," and for "he had a history of abusing her."
- 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.
- 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 . Compute the posterior probability of guilt and compare it with the lawyer's figure.
Adapted from MIT 18.05, problem set 7, Problem 4.