On a rainy day, most people carry an umbrella. Does it follow that most people carrying an umbrella are out in the rain? Not necessarily: both statements sound alike, but they answer different questions, and mixing them up is one of the most common mistakes in reasoning about data. (In the table below, the second number comes out to , which happens to exceed ; it is still a different number from , and it could have been small.)
To keep such questions apart you need a way to describe two random quantities at once, and a precise meaning for “given”. This lesson builds both from a single small table, so every number can be checked by hand.
Two variables at once: the joint distribution
Pick a random day. Let be the weather (sunny, cloudy or rainy) and whether a randomly chosen person carries an umbrella (no or yes). Each of the six combinations has a probability. The joint probability mass function (joint PMF) gives it:
The comma means “and”: both things happen. With one row per value of and one column per value of , the joint PMF is a table. Here is a made-up one:
| = No | = Yes | Total | |
|---|---|---|---|
| = Sunny | |||
| = Cloudy | |||
| = Rainy | |||
| Total |
The six inside entries are the joint distribution. Like any PMF (P1.D2), the entries are at least and add to : . The entry says that on of occasions it is rainy and the person has an umbrella. The sums in the last row and column are explained next.
Marginals: add up a row or a column
Suppose you only care about the weather and not about umbrellas. The probability of rain is the total of the rainy row: . In symbols, the marginal distribution of is
and the marginal of is . Adding over the variable you do not care about is called marginalizing it out. This is the rule “ is the sum of the probabilities of the disjoint pieces of ” from P1.D1, applied to the pieces “rainy and no umbrella” and “rainy and umbrella”.
The name is usually explained by the table: the totals are written in its margins, the last column and the last row, as above. The marginals are ordinary distributions: for the weather and for the umbrella.
The joint determines the marginals, but not the other way round. Two coins that both land heads with probability can be unrelated (all four cells ) or always agree (cells ). Both tables have marginals and . The marginals say how each variable behaves alone; the joint also says how they behave together.
Try the table below. The bars on the right edge and bottom edge are the marginals.
Conditional probability: restrict, then renormalize
Roll a fair die. Let be “the roll is even” and be “the roll is at least ”. Without any information, . Now someone tells you happened: the roll was , or . Only these three outcomes remain possible, and they are still equally likely. Two of them are even ( and ), so the probability of is now . Learning changed your probability of .
That is the idea of conditional probability: throw away everything outside (restrict the sample space), then rescale what is left so it adds to again (renormalize). The rescaling divides by the probability of what you kept:
Read as “the probability of given ”. In the die example , so . The formula is defined only when , because it divides by : you cannot condition on something impossible.
Conditioning on produces a new valid probability assignment: the numbers are at least , the whole sample space has probability , and all the rules of P1.D1 hold inside it.
Conditional distributions: a normalized slice
For random variables, conditioning on takes the row of the table with that value of and divides it by the row total. The result is the conditional distribution
For rainy days, the row is and its total is , so
On a rainy day, of people carry an umbrella. The other rows give for sunny days and for cloudy days. Each one adds to , so each is a proper distribution, different for each value of .
Conditioning on a column works the same way, using the other marginal: . For people with an umbrella (), the column becomes for (sunny, cloudy, rainy), rounded.
Now use the heatmap. Tap the row label “Rainy”: its cells show the joint number and, underneath, the conditional number, and the pink bars below the table show beside the marginal .
What to try:
- Weather and umbrella. Condition on each row in turn. The conditional bars move (umbrellas are rare when sunny, common when rainy), so the weather tells you something about umbrellas.
- Independent. Condition on any row: the pink bars have the same shape as the marginal bars. Knowing changes nothing about . The independence check reads .
- Dependent (diagonal). Condition on row : the conditional puts on , though the marginal of is flat at . The independence check reads about .
- Y = X squared. Condition on the row : all the probability goes to . Condition on the column : half goes to and half to .
- Hours and score. Condition on each row: the slice means rise with the hours (the readout shows them; they are worked out below).
- Edit a cell. Select a cell and press . The whole table renormalizes, and the readouts follow. Set the whole “Yes” column to (press on each of its cells until they read ): the umbrella is then always “No”, a constant, and a constant is independent of the weather. Then watch the independence check read .
Reading the table by rows gives “what does do, given ?” and by columns “what does do, given ?”. These are different questions with different answers.
Conditional expectation: the mean of a slice
A conditional distribution is a distribution, so it has a mean (P1.D4). Take the mean of the slice and you get the conditional expectation,
It answers “what value of should I expect, once I know ?”. A small numeric table shows it. Let be the hours a student studied (, or ) and the exam score (, or ). The joint probabilities are made up:
| Total | ||||
|---|---|---|---|---|
For one hour, the slice is and its total is , so and
The same steps give (slice ) and (slice ). So is a function of : , , . It is different for each unless the slices all have the same mean. (The heatmap’s “Hours and score” table has these numbers; its readouts show the mean of the slice you condition on. The weather table has no numbers to average, so it shows none.)
The link to machine learning. P1.D4 showed that, among constant guesses, the mean has the smallest expected squared error. Apply that to each slice: if you must predict from and are scored by squared error, the best guess is . A regression model trained with squared error aims at exactly this function (P3.A2). With the table above: guessing (the overall mean) for every student has expected squared error , which is ; guessing , or according to the hours brings it down to .
The law of total expectation. Averaging the slice means, with the probabilities of the slices as weights, gives back the overall mean:
Here . Directly from the marginal of , , the mean is as well. This is the law of total probability applied to a mean, and it is useful the same way: split a hard average into easy cases.
The product rule and the chain rule
Multiply the definition of conditional probability by and you get the product rule:
It builds a joint probability from a marginal and a conditional: first happens, then given . In the table, , the entry we started with. Since equals , the roles can also be swapped: . Setting the two expressions equal and dividing is the idea of Bayes’ rule, , the subject of P1.D6.
Apply the product rule repeatedly and you get the chain rule of probability for any number of events (all conditioning events must have positive probability):
Each factor is the probability of the next event given everything before it. Draw three cards from a -card deck without putting any back. The chance that all three are hearts is : after one heart, hearts remain among cards, and so on. The factors differ because the cards affect each other.
For random variables the same rule reads . This is how a language model works: it gives the probability of a sentence as a product, one factor per word, each conditioned on the words before it,
Here stands for all the words before position .
With invented numbers , and , the three-word sentence “the cat sat” has probability . N-gram models (P6.2) estimate each factor by counting, and large language models (P10.A1) estimate it with a neural network. The chain rule is exact, with no assumption, and it holds for any ordering of the variables.
The law of total probability
Sometimes you know the probability of inside each case and want its overall probability. If has the possible values (exactly one of which happens), then adding over the cases, with the product rule, gives the law of total probability. The sum runs over the values with :
It is a weighted average of the conditionals, with the probabilities of the cases as weights. For the umbrella table:
which matches the column total. The overall rate () lies between the smallest and largest conditional rates ( and ), as a weighted average must. The law is the marginal rule written with conditionals, and it is the tool for splitting a hard probability into easy cases.
Independence: the table with identical rows
Sometimes knowing tells you nothing about : . By the product rule, that is the same as
Events satisfying this are independent. The product form is the definition because it needs no condition on and treats and symmetrically; the form is the meaning, valid when . Example: roll a die, = “even” () and = “at most ” (). Then has probability , so the events are independent: learning that the roll is or leaves it just as likely to be even.
Independence is how this course has already justified multiplying. Flip a coin that lands heads with probability three times, with flips that do not affect each other. The sequence H, H, T has probability , which is how the binomial formula in P1.D3 counts sequences. Roll a die four times: independence makes each of the sequences have probability , so all sequences are equally likely and counting them is legitimate (P1.D1). And the gambler’s fallacy fails because the flips are independent: after six heads, for a fair coin.
Independent is not the same as mutually exclusive. Mutually exclusive events cannot both happen: . Roll a die with and . They are mutually exclusive, but , so they are dependent: if happened, certainly did not. In general, two mutually exclusive events that both have positive probability are dependent. Independent events overlap exactly as much as chance predicts, like “even” and “at most ” above.
Independent random variables
Random variables and are independent when the events “” and “” are independent for every pair of values:
In a table, the joint is the product of its marginals. Equivalently, for each with : every row, once divided by its total, is the same distribution (the marginal of ). That is why the heatmap’s independent preset has pink bars that match the blue ones in every row, and a check of . Two fair dice are independent: each of the cells is .
To test a table, compute the marginals and compare each cell with the product of its row total and column total. For the weather table, the cell (Rainy, Yes) is but , so rain and umbrellas are dependent; the gaps are , and in the three rows, and the largest gap is . The product table with the same marginals (which would be independent) has and in the sunny row, and and in each of the other two rows.
Consequences for expectation and variance. If and are independent, then . This is what removes the cross term in P1.D4: independent variables have covariance , and their variances add. The Go-deeper box below shows why. The converse is false, as the next box and the “” table show.
Go deeper Independence gives zero covariance, but zero covariance is weaker
For independent and ,
So the quantity , which is the covariance (P1.D7) and is the cross term in (P1.D4), is .
The converse fails. Let take the values with probability each, and let . Then and by symmetry, so . But is a function of , so they are as dependent as can be: , while . So “zero covariance” is weaker than “independent”. This is the last preset of the heatmap, and its independence check reads .
Conditional independence
Two quantities can be independent only after you know a third. and are conditionally independent given when
for every with . Independence and conditional independence are different properties; neither implies the other.
Dependent, but independent given . A box holds two coins: a fair coin (heads with probability ) and a biased coin (heads with probability ). Pick one at random, then flip the picked coin twice. Given which coin it is, the two flips are independent: both heads has probability for the fair coin and for the biased one. But without knowing the coin, the flips are dependent. and , but . A first head is a hint that you hold the biased coin, which makes a second head more likely: , up from .
Independent, but dependent given . Flip two fair coins separately, so they are independent. Let be the event “the two coins match”. Given , if the first coin is heads the second must be heads too: , but . Learning made two unrelated coins related. The same happens given “the coins differ”.
In machine learning, naive Bayes (P3.B2) assumes the features are independent given the class: for a spam filter, once you know whether the message is spam, the presence of one word is assumed not to tell you about another. That assumption is rarely exactly true, but it replaces a joint table with one entry for every combination of words by a short product, .
Go deeper Pairwise independence is weaker than mutual independence
Several events are mutually independent when the product rule holds for every subset of them: every pair, every triple, and so on. Checking every pair is pairwise independence and is weaker.
Flip two fair coins. Let = “the first is heads”, = “the second is heads” and = “the coins match”. Each has probability . Any two of them are independent: , the same as the product of the two probabilities. But all three together have probability (the single outcome heads, heads), while . Knowing any one of the three tells you nothing about another, but knowing two tells you the third. The word “independent” for a list of events or variables means mutual independence, which is what the i.i.d. assumption below requires.
Independent and identically distributed (i.i.d.)
Most of machine learning starts from one assumption about data. A data set is i.i.d., independent and identically distributed, when:
- independent: the examples are mutually independent, so one example tells you nothing about another;
- identically distributed: every example is drawn from the same distribution .
Then the joint probability of the whole data set is a product, . For a coin with unknown heads probability , three flips H, H, T have probability . Maximum likelihood (P1.D10) picks the parameters that make this product as large as possible, and it works with a product only because of independence. The same assumption makes the average of draws behave as P1.D4 showed (spread ), and it justifies using a random mini-batch as a stand-in for the whole training set (P1.F4).
Common practice tries to produce i.i.d.-like data. Shuffling the data before cutting mini-batches, and splitting it at random into training and test sets (P3.A1), aim to make the test set look like a fresh independent sample from the same distribution, which, when the assumption holds, is why test error estimates performance on new data. Standard dropout (P4.17) switches off each unit with its own independent random draw.
The assumption can fail, and a model evaluated as if it held can look better than it is: consecutive days of a time series are related; several photos of the same patient may be split across the training and test sets; near-duplicate documents leak from one set into the other; and data collected next year may follow a different distribution.
Go deeper Simpson’s paradox: when the total reverses the parts
A made-up example. Two treatments are compared on patients with mild or severe cases. The counts are (recovered)/(patients):
- Treatment A: mild , severe , overall .
- Treatment B: mild , severe , overall .
Within the mild cases, A is better ( against ). Within the severe cases, A is also better ( against ). Yet over all patients, B looks far better ( against ). The aggregated comparison and the stratified comparison point in opposite directions.
The law of total probability explains it. Write for recovery and for the severity. Then , a weighted average with weights that differ between the treatments. A treated mostly severe cases (weight on severe) and B treated mostly mild cases (weight on mild). Treatment A’s overall rate is , and B’s is . When the weights differ, the order of the overall averages need not match the order inside each group.
Which comparison is right depends on how the data arose. If severity affects both which treatment a patient got and whether they recover, the stratified comparison is the fair one; if severity were itself changed by the treatment, it would not be. Statistics alone cannot settle this, which is why P1.D13 returns to causation versus correlation.
Go deeper Joint densities for continuous variables
For continuous variables, the joint table becomes a joint density , a surface over the plane. Probabilities are volumes under it, and the total volume is : . The marginal is found by integrating out the other variable,
and the conditional density is , the slice of the surface at rescaled to have area . Independence still means .
Example: let be uniform on the triangle . The density is there, since the triangle has area . The marginal of is on , and it integrates to . Given , the conditional density of is on : uniform between and . This conditional depends on , so the variables are dependent. Joint densities of several variables with a bell shape are the multivariate Gaussian of P1.D7. Conditioning on an exact value of a continuous variable (a probability-zero event) works through this ratio of densities, not through .
Intuition
A joint table is a map of how probability is spread over pairs. Adding along a row or a column squashes the map onto one axis: that is a marginal. Conditioning cuts out one strip, then blows it up until it holds probability . The strip’s shape tells you what you now believe about the other variable.
Independence means the map is a multiplication table: every strip, once renormalized, has the same shape. Dependence means different strips have different shapes, so learning one variable moves your belief about the other.
The “restrict and renormalize” picture is exact for discrete tables. It breaks down only for continuous variables, where a single exact value has probability and conditioning must use a ratio of densities.
Math
The symbol means “independent”:
The second line holds for each with . The symbol means “independent given ”:
Code
A joint table is a NumPy array. Marginals are sums along an axis, a conditional is a row divided by its sum, and independence means the table equals the outer product of its marginals.
import numpy as np
J = np.array([[36, 4], [20, 10], [6, 24]]) / 100
px, py = J.sum(axis=1), J.sum(axis=0) # marginals
cond = J / px[:, None] # p(y | x), one row per x
independent = np.allclose(J, np.outer(px, py))Try it: tables, slices and independence in code
The first cell works with the weather table: marginals, the conditional table, the product rule, the law of total probability, the reversed conditional against , and the independence check. The second cell uses exact fractions to check the two-coin examples (pairwise but not mutual independence, and dependence given a match), the random-coin example, Simpson’s paradox and the three-hearts chain rule. Predict first: what will be for the random coin?
Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).
The cell prints the marginals and , the conditional rows , and , and the largest gap for the weather table, then shows that the product table with the same marginals has gap . Challenge: change the entries so that the table becomes independent, for instance to the product table, and check that every conditional row then equals .
Runs real Python in your browser. First run downloads about 6 MB (once; your browser keeps it).
Challenge: change the biased coin’s heads probability from to , so both coins are fair, and check that now equals .
Common mistakes
Check your understanding
In the umbrella table, the rainy row is (no umbrella, umbrella) and . What is ?
Divide the joint entry by the row total: . The value is the joint probability of rain and an umbrella, which has not been divided by the probability of rain. The value is , the conditional with the roles reversed. The value is the marginal probability of rain.
, and . Which statement is correct?
Independence needs , but it is . Equivalently, differs from . A positive overlap is not evidence of independence, and where falls relative to and is irrelevant. Mutually exclusive events would have overlap .
Events and are mutually exclusive, with and . Are they independent?
Independence needs the overlap to equal the product , but the overlap is . Having no outcome in common is the opposite of independence: if happened, then did not. The equation would need , which is not the case. The information given is enough to decide.
A model sees short texts ( of inputs) and long texts (). It is right on of short texts and of long ones. What is its overall accuracy?
The law of total probability weights each conditional accuracy by the probability of its case: . The value is the plain average of and , which ignores that short texts are more common. The value multiplies the two accuracies, which has no meaning here. The value is only the accuracy on short texts.
You know , and . What is ?
The chain rule multiplies the factors: . The value stops after two factors, which is . The value multiplies and and skips the middle factor. The value adds the numbers, and no probability can exceed .
Exercises
- In the umbrella table, find .
Show answer
Divide the cell by the column total: . - Compute and , then use the law of total probability with and to recover .
Show answer
and . Then . - Two cards are dealt from a -card deck without replacement. What is the probability that both are aces?
Show answer
By the chain rule, . - and are independent with and . Find .
Show answer
by independence, so . - A coin lands heads with probability , and flips are independent. Find the probability of H, T, H in that order, and the probability of at least one head in three flips.
Show answer
. For at least one head, use the complement: . - The joint table of and has rows and . Are and independent?
Show answer
The marginals are for and for . The product for the first cell is , not , so they are dependent. - Build an independent joint table for with marginal and with marginal .
Show answer
Multiply: the rows are and . - A language model gives , and (invented numbers). Find , and say why multiplying the three marginal probabilities would be wrong.
Show answer
The chain rule gives . Multiplying the marginals assumes the words are independent, but a word depends on the words before it. - In a spam filter, and (invented). Assuming the words are conditionally independent given spam, what is the probability that a spam message has both words?
Show answer
. Without the conditional independence assumption this product would not be justified. - Which of these are plausibly i.i.d.: (a) the outcomes of successive die rolls; (b) the temperature at noon on consecutive days; (c) photos chosen at random, one per person, from a large collection of people?
Show answer
(a) and (c) are plausibly i.i.d. Consecutive daily temperatures in (b) are related (warm days tend to follow warm days), so they are not independent. - Show that if with and , then .
Show answer
By the product rule, . Then . Independence is symmetric. - In the Simpson’s paradox box, the weights on severe cases are for A and for B. Compute each treatment’s overall recovery rate as a weighted average.
Show answer
A: . B: . - Using the hours and score table, find (the mean hours among students who scored ).
Show answer
The column has total , so the conditional probabilities are for , and .
Next: P1.D6 turns the product rule around into Bayes’ theorem and shows how to update a belief when evidence arrives. P1.D7 measures dependence with covariance and correlation and shows the multivariate Gaussian, whose marginals and conditionals are again Gaussian. P1.D10 uses the i.i.d. product to define the likelihood, and P3.B2 builds naive Bayes on conditional independence.