Settings

Theme
Lite Mode (saves mobile data)

In Lite Mode, animations and videos don't play until you tap them, and their size is shown first. Interactive widgets still work.

Text size

Back up or move your progress →

Part 1: Math FoundationsProbability and Statistics

Joint, marginal and conditional probability

P1.D545 min●●○ IntermediateReviewed Dec 1, 2026

Why this matters for machine learning

A model never sees one random quantity: it sees an input together with a label, or a word together with the words before it. Joint, marginal and conditional probabilities are the vocabulary for how those quantities relate, and independence is the assumption that makes the arithmetic tractable.

  • A classifier models the conditional distribution p(y∣x)p(y\mid x) of the label given the input, while a generative model models the joint p(x,y)p(x,y) or the marginal p(x)p(x) of the data. (P8.1: Generative vs. discriminative models, coming soon)
  • A regression model trained with squared error learns to predict the conditional expectation E[y∣x]\mathbb{E}[y\mid x], the mean of the label given the input. (P3.A2: Linear regression, coming soon)
  • A language model scores a sentence with the chain rule, p(w1,…,wn)=∏tp(wt∣w1,…,wt−1)p(w_1,\dots,w_n)=\prod_t p(w_t\mid w_1,\dots,w_{t-1}), and an n-gram model estimates those conditionals by counting. (P6.2: N-gram language models, coming soon)
  • Naive Bayes assumes the features are independent given the class (conditional independence), which turns a huge joint distribution into a product of small ones. (P3.B2: Naive Bayes, coming soon)
  • When training examples are independent draws from one distribution (i.i.d.), the likelihood of the data is a product of per-example probabilities, which is what maximum likelihood maximizes. (P1.D10: Maximum Likelihood Estimation)
  • Standard dropout switches off each unit by its own independent random draw, and random train and test splits try to make the test set an independent sample like the training set. (P4.17: Regularization for neural nets, coming soon)

Before this: Probability basics, Random variables

After this lesson you can

  • Read a joint probability table, check that it adds to 11, and get the marginal distributions by adding across rows and down columns
  • Compute P(A∣B)=P(A∩B)/P(B)\mathbb{P}(A\mid B)=\mathbb{P}(A\cap B)/\mathbb{P}(B) (for P(B)>0\mathbb{P}(B)\gt0) by restricting to BB and renormalizing, and get a conditional distribution p(y∣x)p(y\mid x) as a normalized row of the table
  • Use the product rule, the chain rule and the law of total probability to build and split probabilities, and compute a conditional expectation E[Y∣X=x]\mathbb{E}[Y\mid X=x] as the mean of a slice
  • Test independence (P(A∩B)=P(A)P(B)\mathbb{P}(A\cap B)=\mathbb{P}(A)\mathbb{P}(B), or joint equals product of marginals), tell it apart from “mutually exclusive” and from conditional independence, and say what i.i.d. means and where machine learning assumes it

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 0.630.63, which happens to exceed 0.50.5; it is still a different number from 0.80.8, 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 XX be the weather (sunny, cloudy or rainy) and YY 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:

p(x,y)=P(X=x, Y=y).p(x,y)=\mathbb{P}(X=x,\,Y=y).

The comma means “and”: both things happen. With one row per value of XX and one column per value of YY, the joint PMF is a table. Here is a made-up one:

YY = NoYY = YesTotal
XX = Sunny0.360.360.040.040.400.40
XX = Cloudy0.200.200.100.100.300.30
XX = Rainy0.060.060.240.240.300.30
Total0.620.620.380.3811

The six inside entries are the joint distribution. Like any PMF (P1.D2), the entries are at least 00 and add to 11: 0.36+0.04+0.20+0.10+0.06+0.24=10.36+0.04+0.20+0.10+0.06+0.24=1. The entry 0.240.24 says that on 24%24\% 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: 0.06+0.24=0.300.06+0.24=0.30. In symbols, the marginal distribution of XX is

p(x)=∑yp(x,y),p(x)=\sum_y p(x,y),

and the marginal of YY is p(y)=∑xp(x,y)p(y)=\sum_x p(x,y). Adding over the variable you do not care about is called marginalizing it out. This is the rule “P(A)\mathbb{P}(A) is the sum of the probabilities of the disjoint pieces of AA” 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: 0.40+0.30+0.30=10.40+0.30+0.30=1 for the weather and 0.62+0.38=10.62+0.38=1 for the umbrella.

The joint determines the marginals, but not the other way round. Two coins that both land heads with probability 12\frac12 can be unrelated (all four cells 0.250.25) or always agree (cells 0.5,0,0,0.50.5, 0, 0, 0.5). Both tables have marginals (0.5,0.5)(0.5,0.5) and (0.5,0.5)(0.5,0.5). 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.

Joint, marginal and conditional probability

Rows are the values of X (weather), columns are the values of Y (umbrella). People carry an umbrella more often when it rains, so the rows are not copies of each other.

Dependent: the largest gap between a cell and (row total × column total) is 0.126, so the rows differ in shape. Tap a row label or a column label to condition on it.
P(X)
0.40
0.30
0.30
P(Y)
0.62
0.38

cell: joint probability, darker = larger marginal conditional (the slice divided by its total; pink, striped)

Numbers are rounded to 2 decimals, so a row or column can look like it adds to 0.99 or 1.01. Bar lengths are scaled to the largest number on that edge, so the bars stretch when you condition.

Selected cell: weather = Rainy, umbrella = Yes
weight 24 of total 100

Every probability is a weight divided by the total, so changing one weight rescales the whole table and it still adds to 1. Arrow keys move between cells; + and − change the weight.

joint P(weather = Rainy, umbrella = Yes) = 0.240 marginal P(weather = Rainy) = 0.300 marginal P(umbrella = Yes) = 0.380 P(umbrella = Yes | weather = Rainy) = joint / P(X) = 0.240 / 0.300 = 0.800 P(weather = Rainy | umbrella = Yes) = joint / P(Y) = 0.240 / 0.380 = 0.632 product of marginals P(X)·P(Y) for this cell = 0.114, the joint is 0.240 conditional means are not shown here: the values of weather and umbrella in this table are not numbers, so there is nothing to average. independence check: the largest |P(x,y) − P(x)·P(y)| over all cells = 0.126 (not zero, so X and Y are dependent)
A joint probability table drawn as a heatmap (darker blue means a larger probability; every cell also shows its number). The bars on the right edge are the marginal of X (the row totals) and the bars on the bottom edge are the marginal of Y (the column totals). Tap a row label or a column label to condition on it: the slice is outlined, the other cells fade, and a striped pink bar next to each marginal bar shows the conditional distribution, which is the slice divided by its total. Tap a cell to read its joint, marginal and conditional numbers, and use + and − to change its weight; every probability is a weight divided by the total, so the table renormalizes itself. The independence check at the bottom shows the largest gap between a cell and the product of its row total and column total. Numbers are rounded to 2 decimals, and bar lengths are scaled to the largest number on their edge, so they stretch when you condition. For the tables whose values are numbers, the readouts also show the mean of the conditioned slice.

Conditional probability: restrict, then renormalize

Roll a fair die. Let AA be “the roll is even” and BB be “the roll is at least 44”. Without any information, P(A)=36=12\mathbb{P}(A)=\frac36=\frac12. Now someone tells you BB happened: the roll was 44, 55 or 66. Only these three outcomes remain possible, and they are still equally likely. Two of them are even (44 and 66), so the probability of AA is now 23\frac23. Learning BB changed your probability of AA.

That is the idea of conditional probability: throw away everything outside BB (restrict the sample space), then rescale what is left so it adds to 11 again (renormalize). The rescaling divides by the probability of what you kept:

P(A∣B)=P(A∩B)P(B).\mathbb{P}(A\mid B)=\frac{\mathbb{P}(A\cap B)}{\mathbb{P}(B)}.

Read P(A∣B)\mathbb{P}(A\mid B) as “the probability of AA given BB”. In the die example A∩B={4,6}A\cap B=\{4,6\}, so P(A∣B)=2/63/6=23\mathbb{P}(A\mid B)=\frac{2/6}{3/6}=\frac23. The formula is defined only when P(B)>0\mathbb{P}(B)\gt0, because it divides by P(B)\mathbb{P}(B): you cannot condition on something impossible.

Conditioning on BB produces a new valid probability assignment: the numbers P(⋅∣B)\mathbb{P}(\cdot\mid B) are at least 00, the whole sample space has probability P(B)P(B)=1\frac{\mathbb{P}(B)}{\mathbb{P}(B)}=1, and all the rules of P1.D1 hold inside it.

Conditional distributions: a normalized slice

For random variables, conditioning on X=xX=x takes the row of the table with that value of xx and divides it by the row total. The result is the conditional distribution

p(y∣x)=P(Y=y∣X=x)=p(x,y)p(x).\begin{aligned} p(y\mid x)&=\mathbb{P}(Y=y\mid X=x)\\ &=\frac{p(x,y)}{p(x)}. \end{aligned}

For rainy days, the row is (0.06, 0.24)(0.06,\,0.24) and its total is 0.300.30, so

p(No∣Rainy)=0.060.30=0.2,p(Yes∣Rainy)=0.240.30=0.8.\begin{aligned} p(\text{No}\mid\text{Rainy})&=\frac{0.06}{0.30}=0.2,\\ p(\text{Yes}\mid\text{Rainy})&=\frac{0.24}{0.30}=0.8. \end{aligned}

On a rainy day, 80%80\% of people carry an umbrella. The other rows give (0.9, 0.1)(0.9,\,0.1) for sunny days and (23, 13)(\frac23,\,\frac13) for cloudy days. Each one adds to 11, so each is a proper distribution, different for each value of xx.

Conditioning on a column works the same way, using the other marginal: p(x∣y)=p(x,y)/p(y)p(x\mid y)=p(x,y)/p(y). For people with an umbrella (p(y)=0.38p(y)=0.38), the column (0.04, 0.10, 0.24)(0.04,\,0.10,\,0.24) becomes (0.105, 0.263, 0.632)(0.105,\,0.263,\,0.632) 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 p(y∣Rainy)p(y\mid\text{Rainy}) beside the marginal p(y)p(y).

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 XX changes nothing about YY. The independence check reads 00.
  • Dependent (diagonal). Condition on row 22: the conditional puts 0.760.76 on Y=2Y=2, though the marginal of YY is flat at 0.250.25. The independence check reads about 0.130.13.
  • Y = X squared. Condition on the row X=−2X=-2: all the probability goes to Y=4Y=4. Condition on the column Y=4Y=4: half goes to X=−2X=-2 and half to X=2X=2.
  • 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 00 (press −- on each of its cells until they read 00): the umbrella is then always “No”, a constant, and a constant is independent of the weather. Then watch the independence check read 00.

Reading the table by rows gives “what does YY do, given XX?” and by columns “what does XX do, given YY?”. 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,

E[Y∣X=x]=∑yy p(y∣x).\mathbb{E}[Y\mid X=x]=\sum_y y\,p(y\mid x).

It answers “what value of YY should I expect, once I know X=xX=x?”. A small numeric table shows it. Let XX be the hours a student studied (11, 22 or 33) and YY the exam score (5050, 7070 or 9090). The joint probabilities are made up:

Y=50Y=50Y=70Y=70Y=90Y=90Total
X=1X=10.200.200.080.080.020.020.300.30
X=2X=20.080.080.200.200.120.120.400.40
X=3X=30.020.020.080.080.200.200.300.30

For one hour, the slice is (0.20, 0.08, 0.02)(0.20,\,0.08,\,0.02) and its total is 0.300.30, so p(y∣x=1)=(23, 415, 115)p(y\mid x=1)=(\frac23,\,\frac4{15},\,\frac1{15}) and

E[Y∣X=1]=50⋅23+70⋅415+90⋅115=58.\begin{aligned} \mathbb{E}[Y\mid X=1]&=50\cdot\tfrac23+70\cdot\tfrac4{15}\\ &\quad+90\cdot\tfrac1{15}=58. \end{aligned}

The same steps give E[Y∣X=2]=72\mathbb{E}[Y\mid X=2]=72 (slice (0.2, 0.5, 0.3)(0.2,\,0.5,\,0.3)) and E[Y∣X=3]=82\mathbb{E}[Y\mid X=3]=82 (slice (115, 415, 23)(\frac1{15},\,\frac4{15},\,\frac23)). So E[Y∣X=x]\mathbb{E}[Y\mid X=x] is a function of xx: 5858, 7272, 8282. It is different for each xx 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 YY from X=xX=x and are scored by squared error, the best guess is E[Y∣X=x]\mathbb{E}[Y\mid X=x]. A regression model trained with squared error aims at exactly this function (P3.A2). With the table above: guessing 70.870.8 (the overall mean) for every student has expected squared error 255.36255.36, which is Var(Y)\mathrm{Var}(Y); guessing 5858, 7272 or 8282 according to the hours brings it down to 168168.

The law of total expectation. Averaging the slice means, with the probabilities of the slices as weights, gives back the overall mean:

E[Y]=∑xE[Y∣X=x] p(x).\mathbb{E}[Y]=\sum_x\mathbb{E}[Y\mid X=x]\,p(x).

Here 0.30⋅58+0.40⋅72+0.30⋅82=17.4+28.8+24.6=70.80.30\cdot58+0.40\cdot72+0.30\cdot82=17.4+28.8+24.6=70.8. Directly from the marginal of YY, (0.30, 0.36, 0.34)(0.30,\,0.36,\,0.34), the mean is 0.30⋅50+0.36⋅70+0.34⋅90=15+25.2+30.6=70.80.30\cdot50+0.36\cdot70+0.34\cdot90=15+25.2+30.6=70.8 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 P(B)\mathbb{P}(B) and you get the product rule:

P(A∩B)=P(A∣B) P(B).\mathbb{P}(A\cap B)=\mathbb{P}(A\mid B)\,\mathbb{P}(B).

It builds a joint probability from a marginal and a conditional: first BB happens, then AA given BB. In the table, P(Rainy,Yes)=p(Yes∣Rainy) p(Rainy)=0.8×0.30=0.24\mathbb{P}(\text{Rainy},\text{Yes})=p(\text{Yes}\mid\text{Rainy})\,p(\text{Rainy})=0.8\times0.30=0.24, the entry we started with. Since A∩BA\cap B equals B∩AB\cap A, the roles can also be swapped: P(A∩B)=P(B∣A) P(A)\mathbb{P}(A\cap B)=\mathbb{P}(B\mid A)\,\mathbb{P}(A). Setting the two expressions equal and dividing is the idea of Bayes’ rule, P(A∣B)=P(B∣A) P(A)/P(B)\mathbb{P}(A\mid B)=\mathbb{P}(B\mid A)\,\mathbb{P}(A)/\mathbb{P}(B), 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):

P(A∩B∩C)=P(A)×P(B∣A)×P(C∣A∩B).\begin{aligned} \mathbb{P}(A\cap B\cap C)&=\mathbb{P}(A)\\ &\quad\times\mathbb{P}(B\mid A)\\ &\quad\times\mathbb{P}(C\mid A\cap B). \end{aligned}

Each factor is the probability of the next event given everything before it. Draw three cards from a 5252-card deck without putting any back. The chance that all three are hearts is 1352⋅1251⋅1150=11850≈0.0129\frac{13}{52}\cdot\frac{12}{51}\cdot\frac{11}{50}=\frac{11}{850}\approx0.0129: after one heart, 1212 hearts remain among 5151 cards, and so on. The factors differ because the cards affect each other.

For random variables the same rule reads p(x1,…,xn)=p(x1) p(x2∣x1)⋯p(xn∣x1,…,xn−1)p(x_1,\dots,x_n)=p(x_1)\,p(x_2\mid x_1)\cdots p(x_n\mid x_1,\dots,x_{n-1}). 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,

p(w1,…,wn)=∏t=1np(wt∣w<t).p(w_1,\dots,w_n)=\prod_{t=1}^{n}p(w_t\mid w_{\lt t}).

Here w<tw_{\lt t} stands for all the words before position tt.

With invented numbers p(the)=0.05p(\text{the})=0.05, p(cat∣the)=0.01p(\text{cat}\mid\text{the})=0.01 and p(sat∣the cat)=0.1p(\text{sat}\mid\text{the cat})=0.1, the three-word sentence “the cat sat” has probability 0.05×0.01×0.1=0.000050.05\times0.01\times0.1=0.00005. 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 YY inside each case and want its overall probability. If XX has the possible values x1,x2,…x_1,x_2,\dots (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 xx with P(X=x)>0\mathbb{P}(X=x)\gt0:

P(Y=y)=∑xP(Y=y∣X=x)×P(X=x).\begin{aligned} \mathbb{P}(Y=y)&=\sum_x\mathbb{P}(Y=y\mid X=x)\\ &\qquad\times\mathbb{P}(X=x). \end{aligned}

It is a weighted average of the conditionals, with the probabilities of the cases as weights. For the umbrella table:

P(Yes)=0.1×0.40+13×0.30+0.8×0.30=0.38,\begin{aligned} \mathbb{P}(\text{Yes})&=0.1\times0.40+\tfrac13\times0.30\\ &\quad+0.8\times0.30=0.38, \end{aligned}

which matches the column total. The overall rate (0.380.38) lies between the smallest and largest conditional rates (0.10.1 and 0.80.8), 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 BB tells you nothing about AA: P(A∣B)=P(A)\mathbb{P}(A\mid B)=\mathbb{P}(A). By the product rule, that is the same as

P(A∩B)=P(A) P(B).\mathbb{P}(A\cap B)=\mathbb{P}(A)\,\mathbb{P}(B).

Events satisfying this are independent. The product form is the definition because it needs no condition on P(B)\mathbb{P}(B) and treats AA and BB symmetrically; the form P(A∣B)=P(A)\mathbb{P}(A\mid B)=\mathbb{P}(A) is the meaning, valid when P(B)>0\mathbb{P}(B)\gt0. Example: roll a die, AA = “even” (12\frac12) and BB = “at most 22” (13\frac13). Then A∩B={2}A\cap B=\{2\} has probability 16=12⋅13\frac16=\frac12\cdot\frac13, so the events are independent: learning that the roll is 11 or 22 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 0.30.3 three times, with flips that do not affect each other. The sequence H, H, T has probability 0.3×0.3×0.7=0.0630.3\times0.3\times0.7=0.063, which is how the binomial formula in P1.D3 counts sequences. Roll a die four times: independence makes each of the 64=12966^4=1296 sequences have probability (16)4=11296(\frac16)^4=\frac1{1296}, 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, P(heads on the next flip∣six heads)=P(heads)=12\mathbb{P}(\text{heads on the next flip}\mid\text{six heads})=\mathbb{P}(\text{heads})=\frac12 for a fair coin.

Independent is not the same as mutually exclusive. Mutually exclusive events cannot both happen: P(A∩B)=0\mathbb{P}(A\cap B)=0. Roll a die with A={1}A=\{1\} and B={2}B=\{2\}. They are mutually exclusive, but P(A)P(B)=136≠0=P(A∩B)\mathbb{P}(A)\mathbb{P}(B)=\frac1{36}\ne0=\mathbb{P}(A\cap B), so they are dependent: if AA happened, BB 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 22” above.

Independent random variables

Random variables XX and YY are independent when the events “X=xX=x” and “Y=yY=y” are independent for every pair of values:

p(x,y)=p(x) p(y)for all x,y.p(x,y)=p(x)\,p(y)\quad\text{for all }x,y.

In a table, the joint is the product of its marginals. Equivalently, p(y∣x)=p(y)p(y\mid x)=p(y) for each xx with p(x)>0p(x)\gt0: every row, once divided by its total, is the same distribution (the marginal of YY). That is why the heatmap’s independent preset has pink bars that match the blue ones in every row, and a check of 00. Two fair dice are independent: each of the 3636 cells is 136=16⋅16\frac1{36}=\frac16\cdot\frac16.

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 0.240.24 but 0.30×0.38=0.1140.30\times0.38=0.114, so rain and umbrellas are dependent; the gaps are 0.1120.112, 0.0140.014 and 0.1260.126 in the three rows, and the largest gap is 0.1260.126. The product table with the same marginals (which would be independent) has 0.2480.248 and 0.1520.152 in the sunny row, and 0.1860.186 and 0.1140.114 in each of the other two rows.

Consequences for expectation and variance. If XX and YY are independent, then E[XY]=E[X] E[Y]\mathbb{E}[XY]=\mathbb{E}[X]\,\mathbb{E}[Y]. This is what removes the cross term in P1.D4: independent variables have covariance 00, and their variances add. The Go-deeper box below shows why. The converse is false, as the next box and the “Y=X2Y=X^2” table show.

Go deeper Independence gives zero covariance, but zero covariance is weaker

For independent XX and YY,

E[XY]=∑x,yxy p(x) p(y)=∑xx p(x)⋅∑yy p(y)=E[X] E[Y].\begin{aligned} \mathbb{E}[XY]&=\sum_{x,y}xy\,p(x)\,p(y)\\ &=\sum_x x\,p(x)\cdot\sum_y y\,p(y)\\ &=\mathbb{E}[X]\,\mathbb{E}[Y]. \end{aligned}

So the quantity E[XY]−E[X] E[Y]\mathbb{E}[XY]-\mathbb{E}[X]\,\mathbb{E}[Y], which is the covariance (P1.D7) and is the cross term in Var(X+Y)\mathrm{Var}(X+Y) (P1.D4), is 00.

The converse fails. Let XX take the values −2,−1,0,1,2-2,-1,0,1,2 with probability 15\frac15 each, and let Y=X2Y=X^2. Then E[X]=0\mathbb{E}[X]=0 and E[XY]=E[X3]=0\mathbb{E}[XY]=\mathbb{E}[X^3]=0 by symmetry, so E[XY]−E[X] E[Y]=0\mathbb{E}[XY]-\mathbb{E}[X]\,\mathbb{E}[Y]=0. But YY is a function of XX, so they are as dependent as can be: P(X=2, Y=0)=0\mathbb{P}(X=2,\,Y=0)=0, while P(X=2) P(Y=0)=0.2×0.2=0.04\mathbb{P}(X=2)\,\mathbb{P}(Y=0)=0.2\times0.2=0.04. So “zero covariance” is weaker than “independent”. This is the last preset of the heatmap, and its independence check reads 0.160.16.

Conditional independence

Two quantities can be independent only after you know a third. XX and YY are conditionally independent given ZZ when

p(x,y∣z)=p(x∣z) p(y∣z)p(x,y\mid z)=p(x\mid z)\,p(y\mid z)

for every zz with p(z)>0p(z)\gt0. Independence and conditional independence are different properties; neither implies the other.

Dependent, but independent given ZZ. A box holds two coins: a fair coin (heads with probability 12\frac12) and a biased coin (heads with probability 910\frac9{10}). Pick one at random, then flip the picked coin twice. Given which coin it is, the two flips are independent: both heads has probability 14\frac14 for the fair coin and (910)2=0.81(\frac9{10})^2=0.81 for the biased one. But without knowing the coin, the flips are dependent. P(first heads)=12⋅12+12⋅910=0.7\mathbb{P}(\text{first heads})=\frac12\cdot\frac12+\frac12\cdot\frac9{10}=0.7 and P(both heads)=12⋅14+12⋅0.81=0.53\mathbb{P}(\text{both heads})=\frac12\cdot\frac14+\frac12\cdot0.81=0.53, but 0.72=0.49≠0.530.7^2=0.49\ne0.53. A first head is a hint that you hold the biased coin, which makes a second head more likely: P(second heads∣first heads)=5370≈0.757\mathbb{P}(\text{second heads}\mid\text{first heads})=\frac{53}{70}\approx0.757, up from 0.70.7.

Independent, but dependent given ZZ. Flip two fair coins separately, so they are independent. Let ZZ be the event “the two coins match”. Given ZZ, if the first coin is heads the second must be heads too: P(both heads∣Z)=12\mathbb{P}(\text{both heads}\mid Z)=\frac12, but P(first heads∣Z)⋅P(second heads∣Z)=12⋅12=14\mathbb{P}(\text{first heads}\mid Z)\cdot\mathbb{P}(\text{second heads}\mid Z)=\frac12\cdot\frac12=\frac14. Learning ZZ 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, p(x1,…,xd∣y)=∏ip(xi∣y)p(x_1,\dots,x_d\mid y)=\prod_i p(x_i\mid y).

Go deeper Pairwise independence is weaker than mutual independence

Several events A1,…,AnA_1,\dots,A_n 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 AA = “the first is heads”, BB = “the second is heads” and MM = “the coins match”. Each has probability 12\frac12. Any two of them are independent: P(A∩B)=P(A∩M)=P(B∩M)=14\mathbb{P}(A\cap B)=\mathbb{P}(A\cap M)=\mathbb{P}(B\cap M)=\frac14, the same as the product of the two probabilities. But all three together have probability P(A∩B∩M)=14\mathbb{P}(A\cap B\cap M)=\frac14 (the single outcome heads, heads), while P(A) P(B) P(M)=18\mathbb{P}(A)\,\mathbb{P}(B)\,\mathbb{P}(M)=\frac18. 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 x1,…,xNx_1,\dots,x_N 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 pp.

Then the joint probability of the whole data set is a product, p(x1,…,xN)=∏ip(xi)p(x_1,\dots,x_N)=\prod_i p(x_i). For a coin with unknown heads probability θ\theta, three flips H, H, T have probability θ⋅θ⋅(1−θ)\theta\cdot\theta\cdot(1-\theta). 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 NN draws behave as P1.D4 showed (spread σ/N\sigma/\sqrt N), 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 9/10=0.909/10=0.90, severe 30/90≈0.33330/90\approx0.333, overall 39/100=0.3939/100=0.39.
  • Treatment B: mild 80/90≈0.88980/90\approx0.889, severe 3/10=0.303/10=0.30, overall 83/100=0.8383/100=0.83.

Within the mild cases, A is better (0.900.90 against 0.8890.889). Within the severe cases, A is also better (0.3330.333 against 0.300.30). Yet over all patients, B looks far better (0.830.83 against 0.390.39). The aggregated comparison and the stratified comparison point in opposite directions.

The law of total probability explains it. Write RR for recovery and ss for the severity. Then P(R∣A)=∑sP(R∣A,s) P(s∣A)\mathbb{P}(R\mid A)=\sum_s\mathbb{P}(R\mid A,s)\,\mathbb{P}(s\mid A), a weighted average with weights that differ between the treatments. A treated mostly severe cases (weight 0.90.9 on severe) and B treated mostly mild cases (weight 0.90.9 on mild). Treatment A’s overall rate is 0.9×0.1 + 13×0.9=0.390.9\times0.1\,+\,\frac13\times0.9=0.39, and B’s is 0.889×0.9+0.3×0.1=0.830.889\times0.9+0.3\times0.1=0.83. 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 p(x,y)p(x,y), a surface over the (x,y)(x,y) plane. Probabilities are volumes under it, and the total volume is 11: ∬p(x,y) dx dy=1\iint p(x,y)\,dx\,dy=1. The marginal is found by integrating out the other variable,

p(x)=∫p(x,y) dy,p(x)=\int p(x,y)\,dy,

and the conditional density is p(y∣x)=p(x,y)/p(x)p(y\mid x)=p(x,y)/p(x), the slice of the surface at xx rescaled to have area 11. Independence still means p(x,y)=p(x) p(y)p(x,y)=p(x)\,p(y).

Example: let (X,Y)(X,Y) be uniform on the triangle 0≤y≤x≤10\le y\le x\le1. The density is 22 there, since the triangle has area 12\frac12. The marginal of XX is p(x)=∫0x2 dy=2xp(x)=\int_0^x2\,dy=2x on [0,1][0,1], and it integrates to ∫012x dx=1\int_0^12x\,dx=1. Given X=xX=x, the conditional density of YY is 2/(2x)=1/x2/(2x)=1/x on [0,x][0,x]: uniform between 00 and xx. This conditional depends on xx, 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 P(A∩B)/P(B)\mathbb{P}(A\cap B)/\mathbb{P}(B).

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 11. 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 00 and conditioning must use a ratio of densities.

Math

p(x)=∑yp(x,y)p(y∣x)=p(x,y)p(x)p(x,y)=p(y∣x) p(x)\begin{aligned} p(x)&=\sum_y p(x,y)\\ p(y\mid x)&=\frac{p(x,y)}{p(x)}\\ p(x,y)&=p(y\mid x)\,p(x) \end{aligned}p(x1,…,xn)=∏k=1np(xk∣x<k)p(x_1,\dots,x_n)=\prod_{k=1}^{n}p(x_k\mid x_{\lt k})p(y)=∑xp(y∣x) p(x)p(y)=\sum_x p(y\mid x)\,p(x)

The symbol X⊥YX\perp Y means “independent”:

X⊥Y  ⟺  p(x,y)=p(x) p(y)  ⟺  p(y∣x)=p(y)\begin{aligned} X\perp Y&\iff p(x,y)=p(x)\,p(y)\\ &\iff p(y\mid x)=p(y) \end{aligned}

The second line holds for each xx with p(x)>0p(x)\gt0. The symbol X⊥Y∣ZX\perp Y\mid Z means “independent given ZZ”:

p(x,y∣z)=p(x∣z)×p(y∣z)\begin{aligned} p(x,y\mid z)&=p(x\mid z)\\ &\quad\times p(y\mid z) \end{aligned}

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 P(Rainy∣Yes)\mathbb{P}(\text{Rainy}\mid\text{Yes}) against P(Yes∣Rainy)\mathbb{P}(\text{Yes}\mid\text{Rainy}), 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 P(second heads∣first heads)\mathbb{P}(\text{second heads}\mid\text{first heads}) be for the random coin?

Try it: marginals, conditionals and the independence check

Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).

The cell prints the marginals (0.4,0.3,0.3)(0.4,0.3,0.3) and (0.62,0.38)(0.62,0.38), the conditional rows (0.9,0.1)(0.9,0.1), (0.667,0.333)(0.667,0.333) and (0.2,0.8)(0.2,0.8), and the largest gap 0.1260.126 for the weather table, then shows that the product table with the same marginals has gap 00. Challenge: change the entries so that the table becomes independent, for instance to the product table, and check that every conditional row then equals (0.62,0.38)(0.62,0.38).

Try it: coins, Simpson’s paradox and the chain rule with exact fractions

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 910\frac9{10} to 12\frac12, so both coins are fair, and check that P(both heads)\mathbb{P}(\text{both heads}) now equals P(first heads)2\mathbb{P}(\text{first heads})^2.

Common mistakes

Check your understanding

  1. In the umbrella table, the rainy row is (0.06, 0.24)(0.06,\,0.24) (no umbrella, umbrella) and P(Rainy)=0.30\mathbb{P}(\text{Rainy})=0.30. What is P(umbrella∣Rainy)\mathbb{P}(\text{umbrella}\mid\text{Rainy})?

  2. P(A)=0.4\mathbb{P}(A)=0.4, P(B)=0.5\mathbb{P}(B)=0.5 and P(A∩B)=0.3\mathbb{P}(A\cap B)=0.3. Which statement is correct?

  3. Events AA and BB are mutually exclusive, with P(A)=0.3\mathbb{P}(A)=0.3 and P(B)=0.2\mathbb{P}(B)=0.2. Are they independent?

  4. A model sees short texts (60%60\% of inputs) and long texts (40%40\%). It is right on 90%90\% of short texts and 70%70\% of long ones. What is its overall accuracy?

  5. You know P(A)=0.5\mathbb{P}(A)=0.5, P(B∣A)=0.4\mathbb{P}(B\mid A)=0.4 and P(C∣A∩B)=0.5\mathbb{P}(C\mid A\cap B)=0.5. What is P(A∩B∩C)\mathbb{P}(A\cap B\cap C)?

Exercises

  1. In the umbrella table, find P(Cloudy∣umbrella)\mathbb{P}(\text{Cloudy}\mid\text{umbrella}).
    Show answerDivide the cell by the column total: 0.10/0.38=519≈0.2630.10/0.38=\frac{5}{19}\approx0.263.
  2. Compute P(umbrella∣Sunny)\mathbb{P}(\text{umbrella}\mid\text{Sunny}) and P(umbrella∣Cloudy)\mathbb{P}(\text{umbrella}\mid\text{Cloudy}), then use the law of total probability with P(Rainy)\mathbb{P}(\text{Rainy}) and P(umbrella∣Rainy)\mathbb{P}(\text{umbrella}\mid\text{Rainy}) to recover P(umbrella)\mathbb{P}(\text{umbrella}).
    Show answer0.04/0.40=0.10.04/0.40=0.1 and 0.10/0.30=130.10/0.30=\frac13. Then 0.1⋅0.4+13⋅0.3+0.8⋅0.3=0.04+0.1+0.24=0.380.1\cdot0.4+\frac13\cdot0.3+0.8\cdot0.3=0.04+0.1+0.24=0.38.
  3. Two cards are dealt from a 5252-card deck without replacement. What is the probability that both are aces?
    Show answerBy the chain rule, 452⋅351=122652=1221≈0.0045\frac4{52}\cdot\frac3{51}=\frac{12}{2652}=\frac1{221}\approx0.0045.
  4. AA and BB are independent with P(A)=12\mathbb{P}(A)=\frac12 and P(B)=13\mathbb{P}(B)=\frac13. Find P(A∪B)\mathbb{P}(A\cup B).
    Show answerP(A∩B)=16\mathbb{P}(A\cap B)=\frac16 by independence, so P(A∪B)=12+13−16=23\mathbb{P}(A\cup B)=\frac12+\frac13-\frac16=\frac23.
  5. A coin lands heads with probability 0.30.3, 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 answer0.3×0.7×0.3=0.0630.3\times0.7\times0.3=0.063. For at least one head, use the complement: 1−0.73=1−0.343=0.6571-0.7^3=1-0.343=0.657.
  6. The joint table of XX and YY has rows (0.1, 0.3)(0.1,\,0.3) and (0.2, 0.4)(0.2,\,0.4). Are XX and YY independent?
    Show answerThe marginals are (0.4,0.6)(0.4,0.6) for XX and (0.3,0.7)(0.3,0.7) for YY. The product for the first cell is 0.4×0.3=0.120.4\times0.3=0.12, not 0.10.1, so they are dependent.
  7. Build an independent joint table for XX with marginal (0.5, 0.5)(0.5,\,0.5) and YY with marginal (0.2, 0.8)(0.2,\,0.8).
    Show answerMultiply: the rows are (0.1, 0.4)(0.1,\,0.4) and (0.1, 0.4)(0.1,\,0.4).
  8. A language model gives p(the)=0.05p(\text{the})=0.05, p(cat∣the)=0.01p(\text{cat}\mid\text{the})=0.01 and p(sat∣the cat)=0.1p(\text{sat}\mid\text{the cat})=0.1 (invented numbers). Find p(the cat sat)p(\text{the cat sat}), and say why multiplying the three marginal probabilities would be wrong.
    Show answerThe chain rule gives 0.05×0.01×0.1=0.000050.05\times0.01\times0.1=0.00005. Multiplying the marginals assumes the words are independent, but a word depends on the words before it.
  9. In a spam filter, P(“offer”∣spam)=0.6\mathbb{P}(\text{“offer”}\mid\text{spam})=0.6 and P(“free”∣spam)=0.3\mathbb{P}(\text{“free”}\mid\text{spam})=0.3 (invented). Assuming the words are conditionally independent given spam, what is the probability that a spam message has both words?
    Show answer0.6×0.3=0.180.6\times0.3=0.18. Without the conditional independence assumption this product would not be justified.
  10. 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.
  11. Show that if P(A∣B)=P(A)\mathbb{P}(A\mid B)=\mathbb{P}(A) with P(A)>0\mathbb{P}(A)\gt0 and P(B)>0\mathbb{P}(B)\gt0, then P(B∣A)=P(B)\mathbb{P}(B\mid A)=\mathbb{P}(B).
    Show answerBy the product rule, P(A∩B)=P(A∣B)P(B)=P(A)P(B)\mathbb{P}(A\cap B)=\mathbb{P}(A\mid B)\mathbb{P}(B)=\mathbb{P}(A)\mathbb{P}(B). Then P(B∣A)=P(A∩B)/P(A)=P(B)\mathbb{P}(B\mid A)=\mathbb{P}(A\cap B)/\mathbb{P}(A)=\mathbb{P}(B). Independence is symmetric.
  12. In the Simpson’s paradox box, the weights on severe cases are 0.90.9 for A and 0.10.1 for B. Compute each treatment’s overall recovery rate as a weighted average.
    Show answerA: 0.1×0.9+0.9×13=0.09+0.30=0.390.1\times0.9+0.9\times\frac13=0.09+0.30=0.39. B: 0.9×89+0.1×0.3=0.8+0.03=0.830.9\times\frac89+0.1\times0.3=0.8+0.03=0.83.
  13. Using the hours and score table, find E[X∣Y=50]\mathbb{E}[X\mid Y=50] (the mean hours among students who scored 5050).
    Show answerThe column (0.20, 0.08, 0.02)(0.20,\,0.08,\,0.02) has total 0.300.30, so the conditional probabilities are (23, 415, 115)(\frac23,\,\frac4{15},\,\frac1{15}) for X=1,2,3X=1,2,3, and E[X∣Y=50]=23+815+315=2115=1.4\mathbb{E}[X\mid Y=50]=\frac23+\frac8{15}+\frac3{15}=\frac{21}{15}=1.4.

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.

Key takeaways

  • A joint distribution of two discrete variables is a table with entries p(x,y)=P(X=x,Y=y)p(x,y)=\mathbb{P}(X=x,Y=y) that are at least 00 and add to 11. The marginal distributions come from adding across a row, p(x)=∑yp(x,y)p(x)=\sum_y p(x,y), or down a column, p(y)=∑xp(x,y)p(y)=\sum_x p(x,y). The marginals are computed from the joint, but the joint cannot be recovered from the marginals alone.
  • The conditional probability of AA given BB is P(A∣B)=P(A∩B)/P(B)\mathbb{P}(A\mid B)=\mathbb{P}(A\cap B)/\mathbb{P}(B), defined only when P(B)>0\mathbb{P}(B)\gt0. It restricts the sample space to BB and renormalizes so the new total is 11. In a table, p(y∣x)p(y\mid x) is the row for X=xX=x divided by its total. In general P(A∣B)≠P(B∣A)\mathbb{P}(A\mid B)\ne\mathbb{P}(B\mid A).
  • The product rule P(A∩B)=P(A∣B) P(B)\mathbb{P}(A\cap B)=\mathbb{P}(A\mid B)\,\mathbb{P}(B) extends to the chain rule P(A1∩⋯∩An)=∏kP(Ak∣A1,…,Ak−1)\mathbb{P}(A_1\cap\dots\cap A_n)=\prod_k\mathbb{P}(A_k\mid A_1,\dots,A_{k-1}). A language model writes the probability of a sentence this way. The law of total probability, P(Y=y)=∑xP(Y=y∣X=x) P(X=x)\mathbb{P}(Y=y)=\sum_x\mathbb{P}(Y=y\mid X=x)\,\mathbb{P}(X=x), averages the conditionals over the cases.
  • The conditional expectation E[Y∣X=x]=∑yy p(y∣x)\mathbb{E}[Y\mid X=x]=\sum_y y\,p(y\mid x) is the mean of the slice for X=xX=x, so it is a function of xx. A regression model trained with squared error aims at E[y∣x]\mathbb{E}[y\mid x] (P3.A2). The law of total expectation says E[Y]=∑xE[Y∣X=x] p(x)\mathbb{E}[Y]=\sum_x\mathbb{E}[Y\mid X=x]\,p(x).
  • AA and BB are independent when P(A∩B)=P(A)P(B)\mathbb{P}(A\cap B)=\mathbb{P}(A)\mathbb{P}(B), equivalently P(A∣B)=P(A)\mathbb{P}(A\mid B)=\mathbb{P}(A) when P(B)>0\mathbb{P}(B)\gt0: learning BB changes nothing about AA. Random variables are independent when p(x,y)=p(x) p(y)p(x,y)=p(x)\,p(y) for all x,yx,y, so every row of the table has the same shape. Independence is not “mutually exclusive”: two events with positive probability that cannot both happen are dependent.
  • Independence makes E[XY]=E[X]E[Y]\mathbb{E}[XY]=\mathbb{E}[X]\mathbb{E}[Y], so the covariance is 00 and variances add (P1.D4). The converse fails: Y=X2Y=X^2 is completely determined by XX and can still have zero covariance. Conditional independence (independent once a third quantity is known) neither implies nor follows from independence, and it is the assumption of naive Bayes.
  • Data are i.i.d. (independent and identically distributed) when each example is drawn independently from the same distribution. Then the probability of the whole data set is a product, which is the starting point of maximum likelihood (P1.D10). Random shuffling and splitting aim to make this true, and time series or duplicated data break it.
Found a mistake? Tell us