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
- Builds on
- 0 concepts →
- Quiz
- 5 questions ↓
Read first
Nothing — start here.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:
- 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.
- 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, , is the same count done inside the smaller world where 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 . For two dice it is all 36 pairs, from (1, 1) to (6, 6). For "is this email spam?" it is .
An event is any collection of outcomes you care about. "The die shows an even number" is the event . We write its probability as . With a fair die all six outcomes are equally likely, so
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: . The chance of not rolling a six is .
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, , and write for "the probability that 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:
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:
Adding up the joint probabilities across a row gives the marginal: . 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 . 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:
In general, conditional probability is the joint probability divided by the probability of the condition:
Check: . ✓
The order matters enormously. : 60% of spam contains "free". That is a different question with a different answer. Mixing up and 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":
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 . ✓
This rule chains. For three events, . 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: . Then the multiplication rule simplifies to
Two coin flips are independent: the chance of two heads is . "Spam" and "free" are not independent: , 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:
, , and . 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: , while .
The addition rule: "or"
For "A or B (or both)", add the two probabilities and subtract the overlap, which you would otherwise count twice:
. Check by counting: emails. ✓ If and 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.
For a fair die:
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 : 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. but . 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
- Probability Distributions: describing all the probabilities of a random variable at once, including the Gaussian and the softmax.
- Bayes' Theorem: turning into .
- Statistics: Mean, Variance and Sampling: estimating probabilities and averages from data, and how much to trust the estimates.
- Maximum Likelihood Estimation and Entropy, Cross-Entropy and KL Divergence: where training losses come from.
- Naive Bayes and Logistic Regression: classifiers that output probabilities.
- Language Modeling and Next-Token Prediction: the chain of conditional probabilities behind every chatbot.
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
- Using the spam table, compute and . Which is larger, and why?
- 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.
- 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". , so the answer is about 0.518.
Learn more
Hand-picked courses, books, videos and tutorials for going deeper. See all resources →
Seeing Theory
A visual introduction to probability and statistics with interactive animations.
Statistics and Probability
A full school-to-university course on data summaries, probability, distributions, sampling and inference, with practice problems.
Conditional Probability, Explained Visually
Balls falling through shelves make conditional probability something you can watch.
Stat 110: Probability
A legendary probability course with free lectures, a free textbook and problem sets.
Review of Probability Theory
A short reference covering events, random variables, common distributions, expectation and multivariate Gaussians, written for ML students.
Mathematics for Machine Learning
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