Probability — theory with the email spam filter: counting, conditional probability and Bayes (and the exam email that ended up in spam)

The email announcing a room change for one of my midterms ended up in the spam folder, and that day I understood that a filter that gets it right also gets it wrong. I walked into the usual room, empty, five minutes before the start. I found the email later, between a “prize” from a shop I had never heard of and a cryptocurrency offer. The question I asked myself in the corridor is the question of this topic: if a filter is almost always right, how much can I trust what it sends to spam? To answer it we need three tools: counting cases properly, conditional probability and Bayes’ theorem.

In topic 1 we described data we already had: the bus waiting times. Now we jump to chance: what we can say about what has not happened yet. The whole topic revolves around one example: the spam filter of a university email account at ULPGC, with made-up but realistic data. A week of 400 emails, 100 of them spam; the word “free”; a filter that flags; emails coming from the virtual campus, the university mailing lists or outside. Each idea comes first in the example, then with its formula and then in R.

Before you start. For this topic you only need to know what a set is (union, intersection, “what is left outside”) and how to divide and multiply decimals. From R, what you saw in topic 1: creating a vector with c() and a table with matrix(). The topic answers four questions, in this order: what we mean when we say “probability” (experiments, events and Kolmogorov’s three rules); how to count cases without missing any (ordered selections, permutations and combinations); what happens to a probability when we learn something more (conditional probability, total probability and Bayes); and when learning something changes nothing (independence). We use the same week of 400 emails the whole time, 100 of them spam and 75 with the word “free”. If you get lost at any point, go back to that week’s table and ask yourself which cells you are looking at.

Experiments, sample space and events

A random experiment is anything whose outcome we do not know in advance even if we repeat it in the same way: tossing a coin, opening the next email in the inbox, checking whether the bus arrives full. The set of all possible outcomes is the sample space, written Ω \Omega (omega). An event is any subset of Ω \Omega : a piece of the possible outcomes.

Back to email. If we only look at two things for each email, whether it is spam (S) or legitimate (L) and whether it contains the word “free” (F) or not (Fc F^c ), the sample space has four outcomes:

Ω={(S,F), (S,Fc), (L,F), (L,Fc)} \Omega = \{ (S, F),\ (S, F^c),\ (L, F),\ (L, F^c) \}
Sample space of an emailTwo by two grid: rows spam and legitimate, columns with and without the word free. Four outcomes: 60, 40, 15 and 285 emails out of 400. The spam event is the top row and the free event the left column.One email, two questions: Ω has 4 outcomes"free"no "free"spam(S, F)60 emails(S, Fᶜ)40 emailslegitimate(L, F)15 emails(L, Fᶜ)285 emailsEvent S = "is spam" (row)Event F = "says free" (column)
An event is a piece of Ω: "is spam" is a whole row; "says free", a column. Where they cross is S ∩ F.

In the drawing, each cell is an outcome and underneath is how many of the week’s 400 emails fell into it. The event “is spam” is not a cell: it is the whole top row, S={(S,F),(S,Fc)} S = \{(S,F), (S,F^c)\} . The event “says free” is the left column. This way of thinking, “an event is a piece of Ω \Omega “, is what makes everything else work.

Why does defining Ω \Omega properly matter so much? Because a probability is always “of something within something”. If you change the sample space, the answer changes. A typical exam mistake is counting favourable cases with one Ω \Omega and possible cases with another.

Operations on events

Events are combined with the usual set operations:

  • Union A∪B A \cup B : A happens, or B, or both. “Is spam or says free”.
  • Intersection A∩B A \cap B : A and B happen at the same time. “Is spam and says free”: the top-left cell, 60 emails.
  • Complement Ac A^c (also Aˉ \bar{A} ): everything that is not A. The complement of “is spam” is “is legitimate”.
  • Impossible event ∅ \emptyset : the empty set. Two events are disjoint or mutually exclusive if A∩B=∅ A \cap B = \emptyset : they cannot happen together.
Operations on eventsFour Venn diagrams: the union of A and B fully coloured, the intersection only in the shared area, the complement of A as the whole rectangle except A, and two disjoint events with no shared area.ABA ∪ BA or B (or both)ABA ∩ BA and B at onceAAᶜeverything that is not AACA ∩ C = ∅cannot happen together
The coloured part is the event. The rectangle is Ω: the complement is "all of Ω except A".

In the drawing, the coloured part is the event and the rectangle is Ω \Omega . Look especially at the third one: the complement is not “the opposite” in a vague sense, it is all of Ω \Omega except A. If Ω \Omega changes, Ac A^c changes.

There are two rules you will use all the time, De Morgan’s laws:

(A∪B)c=Ac∩Bc(A∩B)c=Ac∪Bc (A \cup B)^c = A^c \cap B^c \qquad (A \cap B)^c = A^c \cup B^c

In words: “not (spam or free)” is the same as “neither spam nor free”. It looks like wordplay, but it is the door to computing probabilities of “none” from those of “some”. We prove them in the proofs article.

Whenever a problem says “at least one”, think of the complement straight away: “at least one” is the opposite of “none”, and “none” is usually much easier to compute.

Probability: what it is and which rules it follows

There are three ways to understand a number such as P(S)=0.25 P(S) = 0.25 :

  1. Classical (Laplace): if all outcomes are equally likely, the probability is favourable cases over possible cases.
  2. Frequentist: it is the proportion of times the event happens if we repeat the experiment a huge number of times.
  3. Axiomatic (Kolmogorov, 1933): it does not matter what it “means”; a probability is any function that satisfies three rules.

The third is the one the course uses to prove things, so let us start there.

Kolmogorov’s three axioms

A probability is a function P P that assigns a number P(A) P(A) to each event A⊂Ω A \subset \Omega and satisfies:

  1. Non-negative: P(A)≥0 P(A) \ge 0 for every event A.
  2. Normalised: P(Ω)=1 P(\Omega) = 1 .
  3. Additive: if A1,A2,… A_1, A_2, \dots are pairwise disjoint, P(⋃iAi)=∑iP(Ai) P\left( \bigcup_i A_i \right) = \sum_i P(A_i) .

The axioms, read out loud

Written like that they look abstract, but each one says something you already knew:

  • Non-negative: there are no negative probabilities. The least likely anything can be is “never”, and that is a 0.
  • Normalised: something has to happen. The email you open is spam or legitimate, whether it says “free” or not: the whole 100 % is shared out among the outcomes in Ω \Omega .
  • Additive: if two pieces of Ω \Omega do not overlap, the probability of putting them together is the sum. With the week, spam splits into two cells that do not touch, spam with “free” and spam without “free”, and that is why P(S)=0.15+0.10=0.25 P(S) = 0.15 + 0.10 = 0.25 .

The properties below come from combining these three. Take the complement: A and Ac A^c do not overlap and together they are all of Ω \Omega , so by axioms 3 and 2, P(A)+P(Ac)=1 P(A) + P(A^c) = 1 . With the week, the probability of legitimate is 1−0.25=0.75 1 – 0.25 = 0.75 , without counting the 300 legitimate emails.

The axioms also help you catch impossible problem statements. If you are told A and B are mutually exclusive with P(A)=0.6 P(A) = 0.6 and P(B)=0.7 P(B) = 0.7 , something is wrong: since they do not overlap, P(A∪B)=1.3 P(A \cup B) = 1.3 , and no probability goes above 1.

From just that, every property you will use follows:

  • P(Ac)=1−P(A) P(A^c) = 1 – P(A) .
  • P(∅)=0 P(\emptyset) = 0 .
  • If A⊂B A \subset B , then P(A)≤P(B) P(A) \le P(B) .
  • Probability of the union: P(A∪B)=P(A)+P(B)−P(A∩B) P(A \cup B) = P(A) + P(B) – P(A \cap B) .

The last one is the most used and the most forgotten. Why do we subtract the intersection? Because when we add P(A) P(A) and P(B) P(B) , the emails that are spam and say free are counted twice: once inside A and once inside B. With our week: P(S)=100/400=0.25 P(S) = 100/400 = 0.25 , P(F)=75/400=0.1875 P(F) = 75/400 = 0.1875 and P(S∩F)=60/400=0.15 P(S \cap F) = 60/400 = 0.15 , so

P(S∪F)=0.25+0.1875−0.15=0.2875 P(S \cup F) = 0.25 + 0.1875 – 0.15 = 0.2875

Check it by counting: spam or free means the 100 spam plus the 15 legitimate emails with “free”, 115 emails, and 115/400 = 0.2875. The numbers add up.

Adding P(A)+P(B) P(A) + P(B) for the union without checking whether A and B can happen together. You can only add without subtracting anything if they are disjoint. If you get a probability above 1, this is almost certainly why.

Favourable cases over possible cases

When Ω \Omega is finite and all outcomes are equally likely, the probability of an event is Laplace’s rule:

P(A)=favourable casespossible cases P(A) = \frac{\text{favourable cases}}{\text{possible cases}}

Mind the condition: “equally likely”. In the grid above, the four cells are not equally likely (60, 40, 15 and 285 emails), so you cannot say P(S,F)=1/4 P(S, F) = 1/4 . Laplace works for coins, dice, cards, emails picked at random from an inbox… but not for “outcomes” that you have grouped yourself.

Relative frequency approaches probability

The frequentist idea has a very useful practical consequence: if you cannot compute a probability, you can simulate it. R has the function sample() to draw random outcomes with whatever probabilities you want. Let us simulate 20 emails from a server where 25 % is spam:

set.seed(2026)   # fixes the seed: you get the same result every time you run it
email <- sample(c("spam", "legitimate"), size = 20, replace = TRUE, prob = c(0.25, 0.75))
email
table(email)

Output:

 [1] "legitimate" "legitimate" "legitimate" "legitimate" "legitimate"
 [6] "legitimate" "legitimate" "spam"       "legitimate" "legitimate"
[11] "legitimate" "legitimate" "legitimate" "spam"       "legitimate"
[16] "legitimate" "legitimate" "legitimate" "legitimate" "legitimate"
email
legitimate       spam 
        18          2 

Out of 20 emails only 2 are spam, a proportion of 0.1, when the probability is 0.25. Is the simulation wrong? No: with 20 emails chance weighs a lot. Let us repeat with more emails:

set.seed(2026)
for (n in c(20, 200, 2000, 20000)) {
  x <- sample(c(1, 0), size = n, replace = TRUE, prob = c(0.25, 0.75))   # 1 = spam, 0 = legitimate
  cat(n, "emails: proportion of spam =", round(mean(x), 4), "\n")       # the mean of ones and zeros is the proportion of ones
}

Output:

20 emails: proportion of spam = 0.1 
200 emails: proportion of spam = 0.215 
2000 emails: proportion of spam = 0.248 
20000 emails: proportion of spam = 0.2529 
Relative frequency approaches the probabilityBars with the proportion of spam in 20, 200, 2000 and 20000 simulated emails: 0.1, 0.215, 0.248 and 0.2529. A dashed line marks the probability 0.25.0.00.10.20.30.40.1000n = 200.2150n = 2000.2480n = 2,0000.2529n = 20,000probability 0.25proportion of spamEmails simulated with prob = c(0.25, 0.75)
With 20 emails we get 0.1 (half!); with 20,000 the proportion hardly moves away from 0.25.

The drawing shows what the theory says: with 20 emails, 0.1; with 200, 0.215; with 2000, 0.248; with 20,000, 0.2529. Closer and closer to the 0.25 line. This is the law of large numbers, which we will see in full in topic 7. For now, keep the idea: the proportion over many repetitions approaches the probability, and that is why a long simulation is a good way to check a calculation done by hand.

mean() on a vector of 1s and 0s (or TRUE and FALSE) gives the proportion of ones. It is the shortest way to estimate a probability in R: mean(x == "spam").

Counting without mistakes

With Laplace’s rule, computing probabilities turns into counting: how many favourable cases and how many possible ones. And counting properly is harder than it looks. All the combinatorics of this topic comes from a single rule.

The multiplication principle

If a task is done in p p steps, the first with n1 n_1 options, the second with n2 n_2 … and the last with np n_p , there are

n1×n2×⋯×np n_1 \times n_2 \times \cdots \times n_p

ways to do it in total. For example, the verification code the university sends you by email has 6 digits; each digit can be 0 to 9 and they can repeat, so there are 10×10×⋯×10=106 10 \times 10 \times \cdots \times 10 = 10^6 different codes, one million.

Permutations and combinations

Imagine you choose r r things from a set of n n . Two questions decide everything:

  1. Does order matter? The list (free, prize, offer) is not the same as (offer, free, prize) if you are ranking by severity; it is the same if you only care which three words are there.
  2. Can items repeat? A 6-digit code can have two 7s; a list of 3 different words cannot.
Which counting formula to useDecision tree: first whether order matters, then whether items can repeat. Leaves: ordered with repetition n to the r, ordered without repetition n factorial over n minus r factorial, unordered with repetition and combinations, each with its R function.Does order matter?yesnoCan items repeat?Can items repeat?yesOrdered, with rep.n^r10^6noOrdered, no rep.n!/(n−r)!prod(10:7)yesUnordered, with rep.C(n+r−1, r)choose(9, 4)noCombinationsC(n, r)choose(20, 3)All elements in order: permutations n! · Into several groups: multinomial n!/(n₁!·n₂!·…)
Two questions and you know the formula. Under each one, the R call that gives the number in the example.

Follow the tree in the drawing with two questions and you reach the formula. These are the four, each with an email example:

Order?Repeat?NameFormulaExampleIn R
YesYesOrdered with repetitionnr n^r 6-digit codes: 106 10^6 10^6
YesNoOrdered without repetition (permutations of r)n!(n−r)! \dfrac{n!}{(n-r)!} The top 4 of 10 emails in the inbox, in order: 10⋅9⋅8⋅7 10 \cdot 9 \cdot 8 \cdot 7 prod(10:7)
NoNoCombinations(nr)=n!r! (n−r)! \dbinom{n}{r} = \dfrac{n!}{r!\,(n-r)!} 3 blacklist words out of 20: (203) \binom{20}{3} choose(20, 3)
NoYesCombinations with repetition(n+r−1r) \dbinom{n+r-1}{r} 4 labels picked from 6 types (repeatable): (94) \binom{9}{4} choose(9, 4)

The four formulas come from multiplying

The table looks like a list to memorise, but all four rows come from the multiplication principle and one division. Let’s go through them in order, each one built from the one before.

  • Ordered, with repetition. Each of the 6 digits of the code has 10 options, whatever happens with the others. It is the multiplication principle as it stands: 10⋅10⋯10=106 10 \cdot 10 \cdots 10 = 10^6 . In general, nr n^r .
  • Ordered, without repetition. Now each choice uses up an option. For the first place in the inbox there are 10 emails; for the second, 9, because the first is already placed; then 8 and then 7. Multiplying, 10⋅9⋅8⋅7=5040 10 \cdot 9 \cdot 8 \cdot 7 = 5040 . The formula n!/(n−r)! n!/(n-r)! is just a short way of writing that product: 10!/6! 10!/6! keeps the factors from 10 down to 7, because those from 6 down to 1 cancel top and bottom.
  • Unordered, without repetition. Start from the ordered lists and remove what is extra. Each group of 4 emails appears in 4!=24 4! = 24 different lists (the 24 ways of ordering it), so there are 5040/24=210 5040 / 24 = 210 groups, which is choose(10, 4). That is why the combinations formula is the ordered one divided by r! r! .
  • Unordered, with repetition. This is the only one that does not come from a direct calculation but from a drawing. To pick 4 labels from 6 types, draw each label as a dot and separate the types with 5 bars. “Two of type 1, one of type 3 and one of type 6” is written ●●||●|||●. Each choice is a row of 9 symbols (4 dots and 5 bars), and choosing it means deciding which of the 9 positions get the 4 dots: (94)=126 \binom{9}{4} = 126 . That is where the n+r−1 n + r – 1 comes from: 6 types give 5 bars, plus the 4 dots, 9 positions.

If you hesitate between two formulas in the exam, work out a small case by hand. With 3 emails and 2 places, the ordered lists are 6 (ab, ba, ac, ca, bc, cb) and the unordered groups, 3 (ab, ac, bc). The formula that gives the number you counted is the right one.

Check you’ve got it: how many lists of 3 different words out of 20 are there if order matters (sorted by severity)? And if it does not?

With order, the multiplication principle: 20 options for the first, 19 for the second and 18 for the third, 20⋅19⋅18=6840 20 \cdot 19 \cdot 18 = 6840 lists. Without order, each group of 3 appears in 3!=6 3! = 6 lists, so there are 6840/6=1140 6840 / 6 = 1140 groups, exactly the choose(20, 3) in the table. If in the exam you get 6840 where the question only asks “which words”, you forgot to divide.

Two special cases complete the list:

  • Permutations: ordering all n n elements is the ordered case with r=n r = n : n!=n⋅(n−1)⋯2⋅1 n! = n \cdot (n-1) \cdots 2 \cdot 1 . Five emails can be ordered in 5!=120 5! = 120 ways. By convention, 0!=1 0! = 1 .
  • Multinomial coefficient: splitting n n objects into groups of sizes n1,n2,…,nk n_1, n_2, \dots, n_k (that add up to n n ) can be done in
(nn1 n2 ⋯ nk)=n!n1! n2!⋯nk! \binom{n}{n_1\ n_2\ \cdots\ n_k} = \frac{n!}{n_1!\, n_2! \cdots n_k!}

ways. If the filter splits 10 new emails into three folders, 5 into Primary, 3 into Promotions and 2 into Spam, there are 10!/(5! 3! 2!)=2520 10!/(5!\,3!\,2!) = 2520 different splits.

In R, all of this is three functions: factorial(), choose() and prod().

10^6                                        # 6-digit codes
factorial(5)                                # ways to order 5 emails
prod(10:7)                                  # the top 4 of 10, in order: 10·9·8·7
choose(20, 3)                               # 3 words out of 20, no order
choose(9, 4)                                # 4 labels from 6 types, with repetition: C(6 + 4 - 1, 4)
factorial(10) / (factorial(5) * factorial(3) * factorial(2))   # multinomial 10 into 5, 3 and 2

Output:

[1] 1e+06
[1] 120
[1] 5040
[1] 1140
[1] 126
[1] 2520

The first result comes out as 1e+06: that is scientific notation, 1×106 1 \times 10^6 , one million. R uses it when a number has many zeros; it is not an error.

Using choose() when order matters (or the other way round). Always ask: if I change the order of what I picked, is it a different case? If the answer is yes, it is an ordered selection and choose() falls short by a factor of r! r! .

Why does the combinations formula divide by r! r! ? Because each unordered group appears r! r! times among the ordered lists: the group {free, prize, offer} is inside the 6 lists (free, prize, offer), (free, offer, prize)… The full proof, with a drawing of the 24 lists, is in the proofs article.

A surprising example: repeated codes

This one comes up in exams: the “birthday problem”. How many people do you need so that it is more likely than not that two share a birthday? The answer (23) surprises everyone. Here is our version: some services send a code with only 3 digits (1000 possible codes). If you receive n n emails with a code, what is the probability that at least two carry the same one?

Computing “at least two equal” directly is a mess (two equal, three equal, two pairs…). Its complement is “all different“, which is counted with ordered selections:

P(all different)=1000⋅999⋯(1000−n+1)1000nP(some repeated)=1−1000⋅999⋯(1000−n+1)1000n P(\text{all different}) = \frac{1000 \cdot 999 \cdots (1000 – n + 1)}{1000^n} \qquad P(\text{some repeated}) = 1 – \frac{1000 \cdot 999 \cdots (1000 – n + 1)}{1000^n}

On top, ordered selections without repetition (the first email has 1000 codes, the second 999 so as not to repeat…); at the bottom, with repetition (each email, 1000 codes). In R:

collision <- function(n, N = 1000) 1 - prod((N - n + 1):N) / N^n   # N = possible codes
n <- c(10, 20, 30, 38, 50)
round(sapply(n, collision), 3)   # sapply applies the function to each n

Output:

[1] 0.044 0.174 0.356 0.509 0.712
Repeated 3-digit codesCurve of the probability that at least two emails carry the same 3-digit code, by number of emails from 1 to 80. It crosses 0.5 at n equal to 38, with 0.509.0.000.250.500.751.0001020303850607080number of emails with a codeP(some code repeated)n = 38 → 0.509
There are 1000 codes and 38 emails are enough for a repeat to be more likely than not. It is the birthday problem.

With 38 emails a repeated code is already more likely (0.509) than not. The drawing shows the S shape: it rises slowly at first and shoots up between 20 and 60 emails. Why so fast, with 1000 codes? Because what gets compared are not emails against a fixed code but pairs of emails: with 38 emails there are (382)=703 \binom{38}{2} = 703 pairs, and each has a small chance of matching. In the practice we check it by simulation and see what happens when N N is very large.

The calculation, email by email

The formula above is easier to understand if you do it email by email. They arrive one at a time, and each time you ask: what is the probability that this code does not match any of the earlier ones?

EmailFree codesProbability of not repeatingAll different so farSome repeatedWhy
1st10001000/1000 = 110The first one cannot repeat: there is nothing to match
2nd999999/10000.9990.001It only fails if it lands exactly on the first one’s code
3rd998998/10000.99700.00302 codes are already used; multiply by what was there
4th997997/10000.99400.00603 codes used
5th996996/10000.99000.01004 codes used

Each row multiplies the previous one by the new fraction, because for all of them to be different the 2nd must not repeat, and also the 3rd, and also the 4th… That product is exactly the fraction in the formula: on top 1000⋅999⋅998⋯ 1000 \cdot 999 \cdot 998 \cdots , at the bottom one 1000 per email.

Look at the last column: it goes up by 0.001, then 0.002, then 0.003, then 0.004. Each new email can clash with all the earlier ones, so the risk grows faster and faster. Carrying on to email 10, “all different” drops to 0.956 and “some repeated” rises to 0.044, the first number in the R output. And it almost matches counting pairs: with 10 emails there are (102)=45 \binom{10}{2} = 45 pairs, and 45/1000=0.045 45/1000 = 0.045 .

Writing 1−(999/1000)n 1 – (999/1000)^n , as if each email could only clash with one other. Each new email has fewer free codes than the one before, so the fractions go down: 999, 998, 997…, not always 999.

Conditional probability

Back to the corridor question. The filter sees that an email says “free”. What is the probability now that it is spam? It is no longer 0.25: we know something more. Conditional probability is the probability of A given that B has happened, written P(A∣B) P(A \mid B) (“P of A given B”).

The idea: changing the universe

Look at the week’s table:

“free”no “free”total
spam6040100
legitimate15285300
total75325400

If we know that the email says “free”, the only possible emails are the 75 in that column. Of those, 60 are spam. So

P(S∣F)=6075=0.8 P(S \mid F) = \frac{60}{75} = 0.8
Conditioning changes the universeTable of 400 emails by type and the word free. The free column, with 75 emails, is boxed and becomes the new universe: 60 spam and 15 legitimate, so the probability of spam given free is 60 over 75, 0.8."free"no "free"totalspam6040100legit.15285300total75325400New universe: 7560 spam15 legit.P(S | F) = 60/75= 0.8Conditioning on F means keeping only the F column and sharing out 100 % again.
Knowing nothing, P(S) = 100/400 = 0.25. Once we know it says "free", the denominator goes from 400 to 75.

In the drawing, conditioning means keeping only the F column and sharing out 100 % again among what is left. The denominator goes from 400 to 75. Knowing nothing, the probability of spam was 0.25; on seeing “free”, it rises to 0.8. Information changes probability, and that is what this whole topic is about.

The definition

Dividing numerator and denominator by 400 gives the general definition. If P(B)>0 P(B) > 0 :

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

With the week: P(S∣F)=0.15/0.1875=0.8 P(S \mid F) = 0.15 / 0.1875 = 0.8 , the same as counting. Rearranging gives the multiplication rule, the one used in trees:

P(A∩B)=P(A∣B)⋅P(B)=P(B∣A)⋅P(A) P(A \cap B) = P(A \mid B) \cdot P(B) = P(B \mid A) \cdot P(A)

From counting to the formula, step by step

The definition is not a new formula: it is the table’s calculation written with probabilities. This is how you get from one to the other:

StepCalculationWhy
1P(S∣F)=6075 P(S \mid F) = \frac{60}{75} Counting: of the 75 emails with “free”, 60 are spam
2=60/40075/400 = \frac{60/400}{75/400} Dividing top and bottom by the same number does not change the fraction
3=0.150.1875 = \frac{0.15}{0.1875} 60/400 is P(S∩F) P(S \cap F) and 75/400 is P(F) P(F)
4=P(S∩F)P(F)=0.8 = \frac{P(S \cap F)}{P(F)} = 0.8 This is the definition: what A has inside B, divided by the weight of B

The advantage of step 4 is that you no longer need the counts: it works just as well when the problem only gives you probabilities. And the multiplication rule is the same equality read backwards: for A and B to happen, B has to happen and, knowing B has happened, A has to happen.

Check you’ve got it: knowing that P(F∣S)=0.6 P(F \mid S) = 0.6 and P(S)=0.25 P(S) = 0.25 , what is P(S∩F) P(S \cap F) ? And P(F∣L) P(F \mid L) , the proportion of legitimate emails with “free”?

By the multiplication rule, P(S∩F)=P(F∣S)⋅P(S)=0.6⋅0.25=0.15 P(S \cap F) = P(F \mid S) \cdot P(S) = 0.6 \cdot 0.25 = 0.15 , the 60 cells out of 400 in the table. For the second one, the universe is the 300 legitimate emails, and 15 of them say “free”: P(F∣L)=15/300=0.05 P(F \mid L) = 15/300 = 0.05 . If you multiply it by P(L)=0.75 P(L) = 0.75 you get 0.0375 0.0375 , the prop.table() number for legitimate and free. Both ways agree.

Mixing up P(S∣F) P(S \mid F) and P(F∣S) P(F \mid S) . The first is “of those that say free, how many are spam?” = 60/75 = 0.8. The second is “of the spam, how many say free?” = 60/100 = 0.6. The denominator changes. This confusion has a name (the “prosecutor’s fallacy”) and is behind many badly told news stories.

In R, prop.table() does exactly these divisions. With margin = 2 it divides each column by its total, that is, it conditions on the column:

emails <- matrix(c(60, 40, 15, 285), nrow = 2, byrow = TRUE,
                 dimnames = list(type = c("spam", "legitimate"), word = c("free", "no free")))
addmargins(emails)                        # the table with the totals
round(prop.table(emails), 4)              # joint probabilities: each cell over 400
round(prop.table(emails, margin = 2), 4)  # conditional on the column: each cell over its column

Output:

            word
type         free no free Sum
  spam         60      40 100
  legitimate   15     285 300
  Sum          75     325 400
            word
type           free no free
  spam       0.1500  0.1000
  legitimate 0.0375  0.7125
            word
type         free no free
  spam        0.8  0.1231
  legitimate  0.2  0.8769

How to read it

The three outputs say different things, and the exam asks you to interpret them. Line by line:

  • addmargins(emails) adds the Sum row and column. The 75 at the bottom left is the number of emails with “free”; the 400, the week’s total. It is the starting table.
  • prop.table(emails) divides each cell by 400. The 0.1500 for spam and free is P(S∩F) P(S \cap F) : 15 % of all emails are spam and say free. The four cells add up to 1. The 0.0375 says that only 3.75 % of emails are legitimate with “free”: few, but they exist, and they are the ones the filter may wrongly throw into spam.
  • prop.table(emails, margin = 2) divides each cell by its column total. Now each column adds up to 1. The 0.8 is P(S∣F) P(S \mid F) : of the emails with “free”, 80 % are spam. The 0.1231 in the other column is P(S∣Fc) P(S \mid F^c) : of those that do not say free, only 12.31 % are spam. With margin = 1 you would divide by each row total and get P(F∣S)=0.6 P(F \mid S) = 0.6 .

Read in context: the word “free” multiplies the probability of spam by a little over 3 (from 0.25 to 0.8). It is a good clue for a filter, but not proof: 1 in 5 emails with “free” is legitimate.

Total probability and Bayes’ theorem

The law of total probability

University emails do not all arrive from the same place. Suppose 50 % come from the virtual campus, 30 % from the ULPGC mailing lists and 20 % from outside. And spam is not spread evenly: it is 2 % of what comes from the virtual campus, 10 % of the mailing lists and 60 % of the outside mail. What proportion of all emails is spam?

The three sources form a partition of Ω \Omega : they do not overlap (an email comes from one place only) and together they cover everything. When we have a partition B1,B2,…,Bn B_1, B_2, \dots, B_n with P(Bi)>0 P(B_i) > 0 , for any event A:

P(A)=∑i=1nP(A∣Bi) P(Bi) P(A) = \sum_{i=1}^{n} P(A \mid B_i)\, P(B_i)
Tree for total probabilityTree with three email sources: campus 0.5, lists 0.3 and external 0.2; from each comes the spam branch with 0.02, 0.10 and 0.60. The products 0.010, 0.030 and 0.120 add up to 0.16.an email0.50campus0.02spam0.50 · 0.02= 0.0100.30lists0.10spam0.30 · 0.10= 0.0300.20external0.60spam0.20 · 0.60= 0.120P(spam) = 0.010 + 0.030 + 0.120 = 0.16
Multiply along each branch and add the branches that end in spam. The external source gives 0.12 of the 0.16.

The drawing is the way not to get lost: a tree. First the source branches with their probability; then, from each source, the spam branch with its conditional probability. Multiply along each branch (multiplication rule) and add the branches that end in spam:

P(spam)=0.50⋅0.02+0.30⋅0.10+0.20⋅0.60=0.010+0.030+0.120=0.16 P(\text{spam}) = 0.50 \cdot 0.02 + 0.30 \cdot 0.10 + 0.20 \cdot 0.60 = 0.010 + 0.030 + 0.120 = 0.16

16 % of the emails are spam, and almost all of it comes from outside.

The tree, branch by branch

The total probability formula is what the tree does, written on one line. This is where each term comes from:

BranchP(source) P(\text{source}) P(spam∣source) P(\text{spam} \mid \text{source}) ProductWhy
Campus0.500.020.010Multiplication rule: P(campus∩spam) P(\text{campus} \cap \text{spam})
Lists0.300.100.030Same with the mailing lists
External0.200.600.120Same with the outside mail
Total10.160The three branches do not overlap and together they are all the spam: add them (axiom 3)

Why can we add? Because every spam email comes from one place, and only one. “Spam” splits into three pieces, campus spam, mailing-list spam and outside spam, that do not touch. That is what the partition asks for.

With counts it is even clearer. Think of 1000 emails: 500 from the campus, 10 of them spam; 300 from the lists, with 30 spam; and 200 from outside, with 120 spam. In total, 10+30+120=160 10 + 30 + 120 = 160 spam, 16 %. Remember that 120 out of 160: it is exactly what Bayes is going to calculate in the next section.

Check you’ve got it: with the same tree, what proportion of all emails is legitimate? Work it out with total probability and check the result with the complement.

For each source, the legitimate branch is 1 minus the spam one: 0.98 for the campus, 0.90 for the lists and 0.40 for outside. Multiplying along each branch and adding, 0.50⋅0.98+0.30⋅0.90+0.20⋅0.40=0.49+0.27+0.08=0.84 0.50 \cdot 0.98 + 0.30 \cdot 0.90 + 0.20 \cdot 0.40 = 0.49 + 0.27 + 0.08 = 0.84 . By the complement, 1−0.16=0.84 1 – 0.16 = 0.84 . They match: 84 % of the mail is legitimate.

Bayes’ theorem

Now we turn it around. A spam arrives. Where is it most likely to come from? We want P(external∣spam) P(\text{external} \mid \text{spam}) , but what we know is the other way round, P(spam∣external) P(\text{spam} \mid \text{external}) . Bayes’ theorem flips the conditional:

P(Bj∣A)=P(A∣Bj) P(Bj)∑i=1nP(A∣Bi) P(Bi) P(B_j \mid A) = \frac{P(A \mid B_j)\, P(B_j)}{\sum_{i=1}^{n} P(A \mid B_i)\, P(B_i)}

The numerator is the branch of the tree we care about; the denominator, the total probability we just computed. With the numbers:

P(external∣spam)=0.60⋅0.200.16=0.120.16=0.75 P(\text{external} \mid \text{spam}) = \frac{0.60 \cdot 0.20}{0.16} = \frac{0.12}{0.16} = 0.75

Although only 20 % of the emails come from outside, 75 % of the spam comes from outside. That is what Bayes does: update what we believed (the 20 % before) with a piece of data (it is spam).

Where Bayes’ formula comes from

The sum sign makes the formula look scary, but there is nothing new in it. It is the definition of conditional probability with its two pieces replaced by things you already know how to calculate:

StepWhat you writeWhy
1P(external∣spam)=P(external∩spam)P(spam) P(\text{external} \mid \text{spam}) = \frac{P(\text{external} \cap \text{spam})}{P(\text{spam})} Definition of conditional probability
2On top, P(spam∣external)⋅P(external)=0.60⋅0.20 P(\text{spam} \mid \text{external}) \cdot P(\text{external}) = 0.60 \cdot 0.20 Multiplication rule, with the conditional we do know
3At the bottom, the sum of the three branches =0.16 = 0.16 Total probability, the tree from before
40.120.16=0.75 \frac{0.12}{0.16} = 0.75 It is the branch we care about out of all the branches that end in spam

In words: of all the spam, what share comes in through the outside branch? With the 1000 emails, 120 of the 160 spam: 75 %. Bayes, without the formula, is just that.

The names of each piece show up in the exam and in ME2:

  • P(Bj) P(B_j) : prior probability (what you knew before the data). Here, 0.20.
  • P(A∣Bj) P(A \mid B_j) : likelihood (how probable the data is in each case). Here, 0.60.
  • P(A) P(A) : the total probability of the data, sometimes called the predictive probability. Here, 0.16.
  • P(Bj∣A) P(B_j \mid A) : posterior probability (what you know after the data). Here, 0.75.

In R, Bayes is a four-column table: prior, likelihood, their product (the tree branch) and the product divided by the sum.

prior      <- c(campus = 0.50, lists = 0.30, external = 0.20)  # prior: where the email comes from
likelihood <- c(0.02, 0.10, 0.60)                              # P(spam | source)
joint      <- prior * likelihood                               # each tree branch: P(source and spam)
total      <- sum(joint)                                       # total probability of spam
posterior  <- joint / total                                    # Bayes: P(source | spam)
round(cbind(prior, likelihood, joint, posterior), 4)
total

Output:

         prior likelihood joint posterior
campus     0.5       0.02  0.01    0.0625
lists      0.3       0.10  0.03    0.1875
external   0.2       0.60  0.12    0.7500
[1] 0.16

How to read it

  • Each row is a source. The prior and likelihood columns are the problem’s data.
  • The joint column holds the three tree branches: 0.01 (campus and spam), 0.03 (lists and spam), 0.12 (external and spam). Notice that they do not add up to 1: they add up to 0.16, which is the total line underneath. That is the total probability.
  • The posterior column is the joint divided by 0.16. This one does add up to 1 (0.0625 + 0.1875 + 0.75 = 1): they are the probabilities of each source given that the email is spam.
  • Read in context: if an email is spam, there is a 75 % chance it comes from outside, 18.75 % that it comes from the lists and only 6.25 % that it comes from the virtual campus. Compare the prior and posterior columns: the data “is spam” has raised “external” from 0.20 to 0.75 and lowered “campus” from 0.50 to 0.0625. That is updating with Bayes.

Always check that the posterior column adds up to 1 and that joint adds up to the total probability. If it does not, you have entered a value wrongly or divided by the wrong thing.

The base rate mistake

Now, the corridor question. My email filter catches 90 % of the spam (its sensitivity) and only wrongly flags 2 % of legitimate emails (its false alarm rate). On the server, 25 % of the mail is spam. If the filter flags an email, what is the probability that it really is spam?

Many people answer “90 %” or “98 %”. The correct calculation is Bayes with two branches:

P(spam∣flagged)=0.90⋅0.250.90⋅0.25+0.02⋅0.75=0.2250.240=0.9375 P(\text{spam} \mid \text{flagged}) = \frac{0.90 \cdot 0.25}{0.90 \cdot 0.25 + 0.02 \cdot 0.75} = \frac{0.225}{0.240} = 0.9375
sens <- 0.90; false_alarm <- 0.02; p_spam <- 0.25                 # sensitivity, false alarm, spam rate
p_flagged <- sens * p_spam + false_alarm * (1 - p_spam)          # total probability that the filter flags
p_flagged
sens * p_spam / p_flagged                                        # Bayes: P(spam | flagged)

Output:

[1] 0.24
[1] 0.9375
Bayes with 1000 emailsOut of 1000 emails, 250 are spam and 750 legitimate. The filter flags 225 of the 250 spam and 15 of the 750 legitimate ones. Of the 240 flagged, 225 are spam: 0.9375.1000 emails250 spam750 legitimate× 0.25× 0.75× 0.90225 flagged× 0.1025 not flagged× 0.0215 flagged× 0.98735 not flaggedFlagged: 225 + 15 = 240, and 225 of them are spamP(spam | flagged) = 225/240 = 0.9375
With counts instead of probabilities, Bayes is counting: of the flagged ones (yellow), how many are spam?

The drawing makes it easier with counts: think of 1000 emails. 250 are spam and the filter flags 225 (90 %); 750 are legitimate and the filter flags 15 (2 %). There are 225 + 15 = 240 flagged, and 225 of them are spam: 225/240 = 0.9375. Bayes, with counts, is counting inside the flagged ones.

Think about what that means: 1 in 16 emails that go to spam is legitimate (15 of 240). The room-change email was one of those 15. And it gets worse when spam is rare: if only 5 % of the mail were spam, the same calculation gives 0.7031, so almost 3 in 10 flagged emails would be legitimate. Ignoring the starting proportion is called the base rate fallacy, and it is the same mistake that makes people think a positive medical test means “you are ill” when the illness is rare. In the practice we draw how the answer changes with the spam rate.

Answering with the sensitivity (0.90) when asked for P(spam∣flagged) P(\text{spam} \mid \text{flagged}) . The sensitivity is P(flagged∣spam) P(\text{flagged} \mid \text{spam}) : the conditional the other way round.

Check you’ve got it: if only 5 % of the mail were spam, with the same filter (90 % sensitivity and 2 % false alarms), what is the probability that a flagged email is spam? Do it with 1000 emails.

Out of 1000 emails, 50 would be spam and the filter would flag 90 % of them: 45. The other 950 would be legitimate and the filter would wrongly flag 2 %: 19. There are 45+19=64 45 + 19 = 64 flagged, and 45 of them are spam: 45/64=0.7031 45/64 = 0.7031 , about 0.70 to two decimals, the number given in the text. The filter has not changed; what has changed is the base rate. With less spam, the 19 legitimate emails flagged by mistake weigh much more among the flagged ones.

Independent events

The definition

Two events are independent if knowing that one has happened does not change the probability of the other: P(A∣B)=P(A) P(A \mid B) = P(A) . Substituting into the definition of conditional probability gives the form used to check it:

A and B are independent  ⟺  P(A∩B)=P(A)⋅P(B) A \text{ and } B \text{ are independent} \iff P(A \cap B) = P(A) \cdot P(B)

Are “spam” and “free” independent in our week? P(S)⋅P(F)=0.25⋅0.1875=0.0469 P(S) \cdot P(F) = 0.25 \cdot 0.1875 = 0.0469 , but P(S∩F)=0.15 P(S \cap F) = 0.15 . They do not match: they are dependent, and that is why “free” works as a clue. On the other hand, if we look at whether the email has an attachment (100 of 400) and whether it arrives at the weekend (80 of 400), and it turns out 20 meet both:

P(attachment∩weekend)=20400=0.05=0.25⋅0.20=P(attachment)⋅P(weekend) P(\text{attachment} \cap \text{weekend}) = \frac{20}{400} = 0.05 = 0.25 \cdot 0.20 = P(\text{attachment}) \cdot P(\text{weekend})

They are independent: knowing it is the weekend does not change the proportion of emails with an attachment (20 of 80 is 25 %, the same as 100 of 400).

Two ways of checking independence

To find out whether two events are independent you can look at the product or at the conditional probability. They say the same thing, and it is worth being able to do both:

PairP(A)⋅P(B) P(A) \cdot P(B) P(A∩B) P(A \cap B) P(A∣B) P(A \mid B) versus P(A) P(A) Conclusion
Spam and free0.25⋅0.1875=0.0469 0.25 \cdot 0.1875 = 0.0469 0.1560/75 = 0.8 versus 0.25Dependent: “free” raises the spam
Attachment and weekend0.25⋅0.20=0.05 0.25 \cdot 0.20 = 0.05 0.0520/80 = 0.25 versus 0.25Independent: the weekend changes nothing

The conditional column is the one you can understand in words: “does the proportion of A change when I keep only the emails in B?”. The product column is the one used in proofs and in problems that only give probabilities. If one says “yes”, so does the other.

Assuming two events are independent because they “seem” unrelated. Independence is checked with numbers, not intuition: if the problem does not state it, you have to calculate it.

Independent is not the same as mutually exclusive

This is the most common confusion in the topic.

Mutually exclusive is not the same as independentLeft: two folders that share no emails, mutually exclusive events and therefore dependent. Right: table of 400 emails by attachment and weekend, 20, 80, 60 and 240; the product of the probabilities, 0.25 times 0.20, gives 0.05, equal to the intersection: independent.Mutually exclusivePromotionsfolderSpamfolderIf it is in one, it is surely notin the other: knowing one changes all.→ DEPENDENTIndependentweekendweekdayattachm.2080no att.60240P(A ∩ W) = 20/400 = 0.05P(A)·P(W) = 0.25 · 0.20 = 0.05→ knowing one does not change the other
Two mutually exclusive events with positive probability are never independent: if one happens, the other can no longer happen.

On the left, two folders: an email is in Promotions or in Spam, never both. They are mutually exclusive, and precisely for that reason they are very dependent: if you know it is in Promotions, you know for sure it is not in Spam; the information has changed everything. On the right, attachment and weekend: they can happen together and neither says anything about the other.

The rule: if P(A)>0 P(A) > 0 and P(B)>0 P(B) > 0 and they are mutually exclusive, P(A∩B)=0≠P(A) P(B) P(A \cap B) = 0 \neq P(A)\,P(B) , so they are never independent.

Saying “they are independent because they have nothing in common”. Having nothing in common (empty intersection) means being mutually exclusive. Independent means that the product of the probabilities equals the intersection.

More than two events and filters in a chain

With three or more events you need to be careful: being pairwise independent is not enough. For A1,…,An A_1, \dots, A_n to be mutually independent, the product has to hold for any subset of them, including all three at once. There are examples (you will see one in the course’s proposed exercises with two coin tosses) where each pair is independent but the three together are not.

When events are independent, the calculations for systems “in series” and “in parallel” are very convenient. My email goes through two filters that work separately: the ULPGC filter stops 90 % of the spam and Gmail’s, 80 %. For a spam to reach the inbox it has to escape both:

Two independent filtersA spam goes through the ULPGC filter, which stops 90 percent, and then the Gmail filter, which stops 80. It gets through with probability 0.10 times 0.20, equal to 0.02, and some filter stops it with 0.98.A spam has to dodge both filtersspamULPGC filterstops 90 %0.10Gmail filterstops 80 %0.20P(gets through) = 0.10 · 0.20 = 0.02P(some filter stops it) = 1 − 0.02 = 0.98
To get through it must escape both: with independence, the escape probabilities multiply.
P(gets through)=0.10⋅0.20=0.02P(some filter stops it)=1−0.02=0.98 P(\text{gets through}) = 0.10 \cdot 0.20 = 0.02 \qquad P(\text{some filter stops it}) = 1 – 0.02 = 0.98

Notice that “some filter stops it” is computed with the complement, as the hint at the start said. Adding 0.90 + 0.80 = 1.7 makes no sense: the events “the first stops it” and “the second stops it” are not mutually exclusive.

What is proved in this topic

The exam has “prove that” questions. These are the ones from this topic; here you have the result and the idea, and the full step by step is in the proofs article:

ResultThe ideaWhere
P(Ac)=1−P(A) P(A^c) = 1 – P(A) , P(∅)=0 P(\emptyset) = 0 , if A⊂B A \subset B then P(A)≤P(B) P(A) \le P(B) Split into disjoint pieces and apply axiom 3Proof 1
P(A∪B)=P(A)+P(B)−P(A∩B) P(A \cup B) = P(A) + P(B) – P(A \cap B) The intersection is counted twiceProof 2
Bonferroni and the union boundInduction on the number of eventsProof 3
(nr)=n!r!(n−r)! \binom{n}{r} = \frac{n!}{r!(n-r)!} and Pascal’s identityEach group appears r! r! times in orderProof 4
P(⋅∣B) P(\cdot \mid B) is a probabilityCheck the three axiomsProof 5
Total probability and BayesPartition and multiplication ruleProof 6

Common mistakes

  • Laplace without equally likely outcomes. Counting the cells of a table and dividing by 4 when the cells have different frequencies.
  • Adding overlapping probabilities. P(A∪B) P(A \cup B) without subtracting P(A∩B) P(A \cap B) .
  • Order or no order. Using choose() when order matters, or prod() when it does not.
  • Flipping the conditional. P(A∣B)≠P(B∣A) P(A \mid B) \neq P(B \mid A) : the denominator changes.
  • Forgetting the base rate. Giving a filter’s or a test’s sensitivity as if it were the posterior probability.
  • Independent versus mutually exclusive. Mutually exclusive events (with positive probabilities) are always dependent.
  • Misreading prop.table(). Without margin, joint; with margin = 1, conditional on the row; with margin = 2, on the column.

In the exam results are given to 2 decimal places (0.9375→0.94 0.9375 \to 0.94 ). Do the calculations with all the decimals and round only at the end; if you round halfway, the final result can be a hundredth off.

Try it in the R playground

Open the site’s R playground, paste this script and run it. It brings together the three big ideas of the topic: counting, conditioning and Bayes, with the week’s data.

# Probability with the spam filter: a week of 400 emails
emails <- matrix(c(60, 40, 15, 285), nrow = 2, byrow = TRUE,
                 dimnames = list(type = c("spam", "legitimate"), word = c("free", "no free")))
prop.table(emails, margin = 2)           # P(type | word)

# Bayes with the filter: sensitivity 0.90, false alarm 0.02
rate <- c(0.05, 0.25, 0.50)              # try three spam rates
0.90 * rate / (0.90 * rate + 0.02 * (1 - rate))

# Repeated 3-digit codes
collision <- function(n, N = 1000) 1 - prod((N - n + 1):N) / N^n
plot(1:80, sapply(1:80, collision), type = "l", xlab = "emails", ylab = "P(repeated)")
abline(h = 0.5, lty = 2)

What to look at:

  1. In the Environment tab you will see the emails matrix (2 × 2) and the rate vector.
  2. In the prop.table output, check that each column adds up to 1.
  3. The second line of numbers is the three posterior probabilities: see how much it drops with 5 % spam.
  4. In Plots you get the repeated-codes curve; find where it crosses the 0.5 line.
  5. Change N = 1000 to N = 10000 in the function and draw it again: you will see a warning or a broken curve. In the practice we explain why and how to fix it.

Summary

ConceptFormulaIn R
Laplacefavourable / possible (only if equally likely)mean(x == "spam") to estimate it by simulation
UnionP(A∪B)=P(A)+P(B)−P(A∩B) P(A \cup B) = P(A) + P(B) – P(A \cap B)
ComplementP(Ac)=1−P(A) P(A^c) = 1 – P(A) 1 - p
Ordered without / with repetitionn!/(n−r)! n!/(n-r)! / nr n^r prod((n - r + 1):n) / n^r
Combinations / with repetition(nr) \binom{n}{r} / (n+r−1r) \binom{n+r-1}{r} choose(n, r)
Multinomialn!/(n1!⋯nk!) n!/(n_1! \cdots n_k!) factorial()
ConditionalP(A∣B)=P(A∩B)/P(B) P(A \mid B) = P(A \cap B)/P(B) prop.table(t, margin = 2)
Total probability∑P(A∣Bi)P(Bi) \sum P(A \mid B_i) P(B_i) sum(prior * likelihood)
BayesP(Bj∣A)=P(A∣Bj)P(Bj)/P(A) P(B_j \mid A) = P(A \mid B_j)P(B_j) / P(A) prior * likelihood / sum(prior * likelihood)
IndependenceP(A∩B)=P(A) P(B) P(A \cap B) = P(A)\,P(B) compare the two numbers

Three ideas to keep:

  1. A probability is always “within something”. Conditioning changes that something: the denominator.
  2. Bayes is counting inside what you have observed. Think of 1000 cases and counts, and the base rate will not slip past you.
  3. Mutually exclusive is not independent. The first is about not overlapping; the second, about one not telling you anything about the other.

In the proofs article you see why each result in the table is true, step by step. Then, in the R practice, we simulate a week of the filter, count repeated codes and build Bayes in a table. And to check you have got it, the probability exercises go from easy to hard and come with commented solutions.

Next step: proofsProbability — step-by-step proofs with the spam filter: from the axioms to Bayes (and the union that came out as 1.15)

Did this article help you? Here is how you can support SergioLearns →