Conditional Probability Explained With a Spam Classifier
Conditional probability is the chance of one event once you know another has happened: Pr[X | Y] is Pr[X and Y] divided by Pr[Y]. Lehman, Leighton, and Meyer, in Chapter 18 of Mathematics for Computer Science, write that "The expression Pr[X | Y] denotes the probability of event X, given that event Y happens." Definition 18.2.1 makes it exact: "Let X and Y be events where Y has nonzero probability. Then Pr[X | Y] ::= Pr[X ∩ Y] / Pr[Y]." They add that "The conditional probability Pr[X | Y] is undefined when the probability of event Y is zero."
They also warn about the choice of condition. In their Monty Hall discussion the first calculation went wrong because "we chose the wrong condition." Their diagnosis: "By choosing a condition that did not reflect everything known, we inadvertently included an extraneous outcome in our calculation." The formula is easy; deciding what to put after the bar is where mistakes come from.
Try it by hand. Suppose 100 invented emails: 40 spam and 60 ham. The word "free" appears in 30 of the spam emails and 30 of the ham emails. Then Pr[spam] = 40/100 = 2/5. To find Pr[free | spam], take Pr[free and spam] = 30/100 and divide by Pr[spam] = 40/100, which gives 3/4. To find Pr[spam | free], take the same 30/100 and divide by Pr[free] = 60/100, which gives 1/2. The numerator is the same and the denominator is different, so the two answers are different. A common slip is to treat them as equal. Now use more of what you know. Suppose 24 of the 30 spam emails with "free" also contain a link, against 6 of the 30 ham emails with "free." Then Pr[spam and free and link] = 24/100 and Pr[free and link] = 30/100, so Pr[spam | free and link] = 24/30 = 4/5. Knowing about the link moves the answer from 1/2 to 4/5. The conditioning event is the whole of what you know, which is the point of the book's warning. I checked these fractions by counting the emails in code, and the data are invented.
The trap: conditioning on the wrong event, or reversing the condition. Pr[X | Y] and Pr[Y | X] share a numerator but not a denominator, so they agree only in special cases, and a classifier that reports one while you read the other will mislead you. Dropping a fact you actually have, as in the book's Monty Hall slip, can change the answer too; it need not, since if links appeared equally often among the spam and ham emails with the word, conditioning on the link would leave Pr[spam | free] at 1/2. A caution of my own, not from the sections I read: a conditional probability computed from a small sample of emails is itself an estimate, and conditioning on a rare event leaves few emails to count, so the estimate can be noisy.
Prof Rod's rule: write the condition after the bar, check that it includes everything you know, and never read Pr[X | Y] as Pr[Y | X].