◆ AI All-in-One

Level 3 In-Depth AI · Math Foundations

Probability Basics

Probability is the arithmetic of uncertainty — numbers from 0 to 1 that say how likely things are, and rules for combining them. AI models speak this language, from a spam filter's "92% spam" to a chatbot choosing its next word.

Level
●●●●● Beginner
Reading
12 min
To learn it well
50 minutes to read, an hour to practise
↗ Plan a path here

Read first

Nothing — start here.

This leads to

Language Modeling and Next-Token PredictionBayes' TheoremProbability DistributionsStatistics: Mean, Variance and SamplingLogistic RegressionMarkov Decision Processes

Why it matters

Almost nothing an AI system does is certain, and modern systems say so in numbers:

  • A spam filter doesn't just say "spam". It says "spam with probability 0.92", and you choose the cut-off.
  • An image classifier outputs a probability for each of 1,000 classes, such as 0.81 "tabby cat", 0.12 "tiger cat", 0.03 "lynx"….
  • A language model such as GPT works by predicting a probability for every possible next token, then picking one. Writing a reply means doing this hundreds of times.
  • Training a classifier usually means maximising the probability the model gives to the right answers (see Maximum Likelihood Estimation), and the standard loss, cross-entropy, is built from probabilities.
  • Classic methods such as Naive Bayes and Bayesian reasoning are probability from top to bottom.

So probability is not an optional extra. It is the language in which AI models express what they know and how sure they are. This chapter covers the core rules with dice, coins and email, using nothing more than counting and fractions.

The intuition

A probability is a number between 0 and 1 that measures how likely something is. 0 means impossible, 1 means certain, 0.5 means "as likely as not". You will also see it as a percentage: 0.25 is 25%.

There are two everyday ways to read it, and both are useful:

  1. Long-run frequency. "The probability of rolling a six is 1/6" means that if you roll a fair die thousands of times, about one roll in six will be a six. Roll it 100,000 times and the fraction of sixes settles very close to 0.1667.
  2. Degree of belief. "There's a 70% chance of rain tomorrow" can't be repeated thousands of times. It is a measure of confidence given what we know. Bayes' Theorem is the rule for updating such beliefs when new evidence arrives.

The arithmetic is the same either way. When outcomes are equally likely, probability is simply counting: the number of outcomes you care about, divided by the total number of outcomes. Most of this chapter is counting in a grid.

Key idea A probability is a number from 0 to 1. With equally likely outcomes, it is favourable outcomes ÷ all outcomes. Conditional probability, P(A∣B)P(A \mid B), is the same count done inside the smaller world where BB is known to be true.

How it works

Outcomes, events and the sample space

The sample space is the set of everything that can happen. For one die it is {1,2,3,4,5,6}\{1, 2, 3, 4, 5, 6\}. For two dice it is all 36 pairs, from (1, 1) to (6, 6). For "is this email spam?" it is {spam,not spam}\{\text{spam}, \text{not spam}\}.

An event is any collection of outcomes you care about. "The die shows an even number" is the event {2,4,6}\{2, 4, 6\}. We write its probability as P(even)P(\text{even}). With a fair die all six outcomes are equally likely, so

P(even)=36=0.5P(\text{even}) = \frac{3}{6} = 0.5

Two basic rules always hold:

  • Probabilities of all the separate outcomes add up to 1. Something must happen.
  • Complement: the probability that an event does not happen is one minus the probability that it does: P(not A)=1−P(A)P(\text{not } A) = 1 - P(A). The chance of not rolling a six is 1−1/6=5/61 - 1/6 = 5/6.

A random variable

A random variable is a number whose value depends on chance: the face of a die, the sum of two dice, the number of spam emails tomorrow, the pixel value of a randomly chosen photo. We usually write it with a capital letter, XX, and write P(X=3)P(X = 3) for "the probability that XX comes out as 3". Probability distributions describe all the probabilities of a random variable at once.

Joint and marginal probability: the spam table

Here is a small, realistic dataset: 1,000 emails, labelled as spam or not, and whether they contain the word "free".

contains "free" no "free" total
spam 120 80 200
not spam 40 760 800
total 160 840 1,000

Divide every count by 1,000 to turn it into a probability.

The joint probability of two events is the probability that both happen at once. It's one cell of the table:

P(spam and free)=1201000=0.12P(\text{spam and free}) = \frac{120}{1000} = 0.12

A marginal probability is the probability of one event regardless of the other. It's a row or column total, written in the "margin" of the table, hence the name:

P(spam)=2001000=0.20,P(free)=1601000=0.16P(\text{spam}) = \frac{200}{1000} = 0.20, \qquad P(\text{free}) = \frac{160}{1000} = 0.16

Adding up the joint probabilities across a row gives the marginal: P(spam)=P(spam and free)+P(spam and no free)=0.12+0.08=0.20P(\text{spam}) = P(\text{spam and free}) + P(\text{spam and no free}) = 0.12 + 0.08 = 0.20. This "sum out the other variable" step is called marginalising, and it appears all over probabilistic machine learning.

Conditional probability

Now the key question for a spam filter: if an email contains "free", how likely is it to be spam? This is a conditional probability, written P(spam∣free)P(\text{spam} \mid \text{free}). Read the vertical bar as "given".

The idea is simple: knowing the condition shrinks the world. Ignore every email without "free". You are left with the 160 that contain it. Of those, 120 are spam:

P(spam∣free)=120160=0.75P(\text{spam} \mid \text{free}) = \frac{120}{160} = 0.75
200 emails (each square = 1 email) red = spam, grey = not spam, orange outline = contains “free” P(spam) = 40 / 200 = 0.20 P(free) = 32 / 200 = 0.16 P(spam and free) = 24 / 200 = 0.12 Now look only at emails with “free” the condition shrinks the world to 32 emails P(spam | free) = 24 / 32 = 0.75 “the probability of spam, given free” Compare P(spam) = 0.20 overall. Seeing “free” raises it to 0.75, so the two are not independent.
Fig. 1 Left: 200 emails as squares (the same proportions as the table, divided by 5). 40 are spam and 32 contain "free". Right: looking only at the 32 emails that contain "free", 24 are spam, so P(spam | free) = 0.75, far above the overall 0.20.

In general, conditional probability is the joint probability divided by the probability of the condition:

P(A∣B)=P(A and B)P(B)P(A \mid B) = \frac{P(A \text{ and } B)}{P(B)}

Check: 0.12/0.16=0.750.12 / 0.16 = 0.75. ✓

The order matters enormously. P(free∣spam)=120/200=0.60P(\text{free} \mid \text{spam}) = 120 / 200 = 0.60: 60% of spam contains "free". That is a different question with a different answer. Mixing up P(A∣B)P(A \mid B) and P(B∣A)P(B \mid A) is one of the most common reasoning errors in medicine, law and machine learning. Bayes' theorem is the rule for converting one into the other.

The multiplication rule

Rearranging the definition gives a rule for "and":

P(A and B)=P(B)×P(A∣B)P(A \text{ and } B) = P(B) \times P(A \mid B)

In words: the chance of both is the chance of the first, times the chance of the second given the first. The chance an email both contains "free" and is spam is 0.16×0.75=0.120.16 \times 0.75 = 0.12. ✓

This rule chains. For three events, P(A,B,C)=P(A) P(B∣A) P(C∣A,B)P(A, B, C) = P(A)\,P(B \mid A)\,P(C \mid A, B). A language model uses exactly this to give a probability to a whole sentence: the probability of the first word, times the probability of the second given the first, times the third given the first two, and so on. See Language Modeling and Next-Token Prediction.

Independence

Two events are independent if knowing one tells you nothing about the other: P(A∣B)=P(A)P(A \mid B) = P(A). Then the multiplication rule simplifies to

P(A and B)=P(A)×P(B)(only if independent)P(A \text{ and } B) = P(A) \times P(B) \quad \text{(only if independent)}

Two coin flips are independent: the chance of two heads is 0.5×0.5=0.250.5 \times 0.5 = 0.25. "Spam" and "free" are not independent: P(spam)×P(free)=0.2×0.16=0.032P(\text{spam}) \times P(\text{free}) = 0.2 \times 0.16 = 0.032, but the real joint probability is 0.12, almost four times larger. That dependence is exactly what makes "free" useful to a spam filter.

Independence can be surprising. Roll two dice. Is "the sum is 7" independent of "the first die is 6"? Count in the grid of 36 outcomes:

2 3 4 5 6 7 3 4 5 6 7 8 4 5 6 7 8 9 5 6 7 8 9 10 6 7 8 9 10 11 7 8 9 10 11 12 1 1 2 2 3 3 4 4 5 5 6 6 second die first die 36 equally likely outcomes; each cell shows the sum Two fair dice purple: sum is 7 6 cells → P = 6/36 = 1/6 blue: first die is 6 6 cells → P = 6/36 = 1/6 orange: both at once 1 cell → P = 1/36 1/36 = 1/6 × 1/6, so the events are independent: knowing the first die is 6 leaves P(sum 7) at 1/6. (For “sum is 12” it would not: 1/36 becomes 1/6 once you know.)
Fig. 2 All 36 outcomes of two dice. Six cells sum to 7 (purple), six cells have a first die of 6 (blue), and exactly one cell is both (orange). Since 1/36 = 1/6 × 1/6, the two events are independent.

P(sum 7)=6/36=1/6P(\text{sum } 7) = 6/36 = 1/6, P(first is 6)=1/6P(\text{first is } 6) = 1/6, and P(both)=1/36=1/6×1/6P(\text{both}) = 1/36 = 1/6 \times 1/6. Independent! Whatever the first die shows, exactly one value of the second die makes 7. But "sum is 12" and "first is 6" are not independent: P(sum 12)=1/36P(\text{sum } 12) = 1/36, while P(sum 12∣first is 6)=1/6P(\text{sum } 12 \mid \text{first is } 6) = 1/6.

The addition rule: "or"

For "A or B (or both)", add the two probabilities and subtract the overlap, which you would otherwise count twice:

P(A or B)=P(A)+P(B)−P(A and B)P(A \text{ or } B) = P(A) + P(B) - P(A \text{ and } B)

P(spam or free)=0.20+0.16−0.12=0.24P(\text{spam or free}) = 0.20 + 0.16 - 0.12 = 0.24. Check by counting: 120+80+40=240120 + 80 + 40 = 240 emails. ✓ If AA and BB cannot happen together (rolling a 1 and rolling a 2 on one die), the overlap is 0 and you just add.

Expected value

The expected value of a random variable is its long-run average: each possible value multiplied by its probability, all added up.

E[X]=∑xx⋅P(X=x)\mathbb{E}[X] = \sum_x x \cdot P(X = x)

For a fair die:

E[X]=1⋅16+2⋅16+3⋅16+4⋅16+5⋅16+6⋅16=216=3.5\mathbb{E}[X] = 1 \cdot \tfrac{1}{6} + 2 \cdot \tfrac{1}{6} + 3 \cdot \tfrac{1}{6} + 4 \cdot \tfrac{1}{6} + 5 \cdot \tfrac{1}{6} + 6 \cdot \tfrac{1}{6} = \frac{21}{6} = 3.5

You can never roll 3.5, but the average of many rolls approaches it. Expected values are how you decide under uncertainty. A bet that pays £10 with probability 0.1 and costs £2 otherwise has expected value 10×0.1−2×0.9=−0.810 \times 0.1 - 2 \times 0.9 = -0.8: a losing bet in the long run.

In machine learning, the training loss is an expected value: the average error over the data the model will see. Reinforcement learning agents maximise expected total reward. And the mean of a dataset is the sample version of the expected value.

In code

Simulation is a great way to build intuition, and to check a calculation you're unsure of.

import numpy as np

rng = np.random.default_rng(0)

# Roll a fair die many times: the fraction of sixes settles near 1/6 = 0.1667
rolls = rng.integers(1, 7, size=100_000)
for n in [10, 100, 10_000, 100_000]:
    print(n, (rolls[:n] == 6).mean())
# 10 0.1
# 100 0.16
# 10000 0.1691
# 100000 0.16536

print(rolls.mean())                       # 3.49798  close to the expected value 3.5

# Two dice: is "sum is 7" independent of "first die is 6"?
d1, d2 = rng.integers(1, 7, size=(2, 100_000))
A = d1 + d2 == 7
B = d1 == 6
print(A.mean(), B.mean(), (A & B).mean(), A.mean() * B.mean())
# 0.16774 0.16754 0.02766 0.0281031596   P(A and B) is close to P(A) * P(B)
print(A[B].mean())                        # 0.16509490270980065   P(sum 7 | first is 6)

A[B] keeps only the simulated games where B happened: the "shrink the world" step of conditional probability, in code.

The spam table with Pandas and Working with Data:

import pandas as pd

counts = pd.DataFrame({"free": [120, 40], "no free": [80, 760]},
                      index=["spam", "not spam"])
joint = counts / counts.values.sum()          # joint probabilities
print(joint)
#           free  no free
# spam      0.12     0.08
# not spam  0.04     0.76
print(joint.sum(axis=1))                      # marginals: spam 0.2, not spam 0.8
print(joint.sum(axis=0))                      # marginals: free 0.16, no free 0.84
print(joint.loc["spam", "free"] / joint["free"].sum())   # 0.75  = P(spam | free)

Common pitfalls

  • Swapping the condition. P(spam∣free)=0.75P(\text{spam} \mid \text{free}) = 0.75 but P(free∣spam)=0.60P(\text{free} \mid \text{spam}) = 0.60. They answer different questions. Always say both events out loud: "the probability of this, given that".
  • Assuming independence. Multiplying probabilities is only valid for independent events. Words in an email, pixels in an image and days in a time series are almost never independent. Naive Bayes assumes independence anyway, and knows it's cheating.
  • Ignoring the base rate. A test that catches 99% of cases can still be wrong most of the time it says "yes" if the thing it tests for is rare. See Bayes' Theorem.
  • The gambler's fallacy. After five tails in a row, the next fair coin flip is still 50/50. Independent events have no memory.
  • Small samples. 10 rolls gave 10% sixes above. Frequencies only settle down with many trials. See Statistics: Mean, Variance and Sampling.
  • Probabilities that don't add up. If your model's outputs for mutually exclusive classes don't sum to 1, they aren't a probability distribution. Softmax fixes this for classifiers.

Watch out A model's "probability" is only as good as its calibration. A classifier that says 0.9 should be right about 90% of the time on such cases. Many modern neural networks are overconfident, saying 0.99 when they are right far less often. Check calibration before treating outputs as real probabilities (see Evaluation Metrics).

Where it leads

A bit of history

Probability theory began with gambling. In 1654 Blaise Pascal and Pierre de Fermat exchanged letters about how to divide the stakes of an unfinished game of chance, and in doing so laid the foundations of the subject. Christiaan Huygens wrote the first book on it in 1657, introducing expected value. Jacob Bernoulli's Ars Conjectandi (1713) proved the first law of large numbers: frequencies settle towards probabilities. Thomas Bayes and Pierre-Simon Laplace developed the rules for reasoning from evidence in the 18th century. In 1933 Andrey Kolmogorov put probability on the rigorous footing used today, with three simple axioms. Machine learning became thoroughly probabilistic from the 1990s, and every modern language model is, formally, a probability distribution over text.

Try it

  1. Using the spam table, compute P(not spam∣no free)P(\text{not spam} \mid \text{no free}) and P(no free∣not spam)P(\text{no free} \mid \text{not spam}). Which is larger, and why?
  2. What is the probability of getting at least one six in four rolls of a fair die? Compute it with the complement rule, then check by simulation.
  3. Find the expected value of the sum of two dice, first by using the 36-cell grid, then by a shortcut.

Hint for 2: "at least one six" is the complement of "no six at all". P(no six in 4 rolls)=(5/6)4≈0.482P(\text{no six in 4 rolls}) = (5/6)^4 \approx 0.482, so the answer is about 0.518.

Check your understanding

5 quick questions. Pick an answer to see whether you were right and why. Your best score is saved on this device.

  1. Of 1,000 emails, 160 contain "free", and 120 of those are spam. Of the 200 spam emails, 120 contain "free". What is P(spam | free)?

  2. P(spam) = 0.2 and P(free) = 0.16, but P(spam and free) = 0.12. What does this tell you?

  3. A fair coin has landed tails five times in a row. What is the probability the next flip is heads?

  4. A bet pays £10 with probability 0.1 and costs you £2 otherwise. What is its expected value?

  5. What is the probability of at least one six in four rolls of a fair die?

Finished this chapter?

Learn more

Hand-picked courses, books, videos and tutorials for going deeper. See all resources →

Interactive

Seeing Theory

Brown University · Beginner · Free

A visual introduction to probability and statistics with interactive animations.

Course

Statistics and Probability

Khan Academy · Beginner · Free

A full school-to-university course on data summaries, probability, distributions, sampling and inference, with practice problems.

Course

Stat 110: Probability

Joe Blitzstein (Harvard) · Intermediate · Free

A legendary probability course with free lectures, a free textbook and problem sets.

Article

Review of Probability Theory

Arian Maleki & Tom Do (Stanford CS229) · Intermediate · Free

A short reference covering events, random variables, common distributions, expectation and multivariate Gaussians, written for ML students.

Book

Mathematics for Machine Learning

Deisenroth, Faisal & Ong · 2020 · Intermediate · Free

The linear algebra, calculus, probability and optimisation that ML uses, in one free book.

Facts checked as of 30 November 2026. Fast-moving details (products, prices, laws) change often. · Source: content/entries/math/probability-basics.md