Artificial Intelligence • Mathematical Foundations • 15 min read

Probability and Bayes' Theorem

Artificial intelligence frequently operates with incomplete information. An email classifier cannot know with certainty whether every message is spam; a speech recognizer must choose among plausible transcriptions; and a forecasting model must account for uncertain future outcomes. Probability provides a mathematical language for representing such uncertainty.

Bayes’ theorem is a rule for updating probabilities when new evidence becomes available. Together, probability and Bayesian reasoning help explain how AI systems combine prior information, observed data, and assumptions to make predictions. These ideas also provide foundations for Naive Bayes classification, model evaluation, and probabilistic machine learning.

Start with a simple question: what changes when you learn something new?

Imagine that only a few messages arriving in your inbox are spam. A filter flags a message because it contains a suspicious phrase. Should you immediately assume it is spam? Not necessarily. A suspicious phrase might also appear in a legitimate message. The answer depends on two pieces of information: how common spam is before seeing the phrase, and how often the phrase appears in spam versus legitimate email.

That is the central idea behind conditional probability and Bayesian updating. Probability describes uncertainty before an observation; Bayes’ theorem tells us how to revise it after observing evidence.

For a concrete illustration, suppose 10 out of every 100 emails are spam. A detector flags 8 of those 10 spam emails, but it also flags 9 of the 90 legitimate emails. Among the 17 flagged messages, only 8 are actually spam. So a flag raises the probability of spam from 10% to about 47%, not to 80%. The detector’s 80% detection rate and the probability that a flagged email is spam are different quantities.

As you read, focus on the question being conditioned on. Does a number refer to the probability of a flag given spam, or the probability of spam given a flag? Bayes’ theorem relates these two quantities, but does not make them equal.

What is probability?

Probability is a mathematical measure of the likelihood of an event within a specified model of uncertainty. It takes a value between 00 and 11, inclusive:

0≤P(A)≤10\leq P(A)\leq 1

Here, P(A)P(A) denotes the probability of event AA.

  • P(A)=0P(A)=0 means the event has probability zero in the model.
  • P(A)=1P(A)=1 means the event occurs with probability one in the model.
  • P(A)=0.7P(A)=0.7 means the model assigns the event a probability of 70%70\%.

Important: A probability of zero does not always mean an event is logically impossible. In continuous models, an exact outcome can have probability zero even though it is possible. Similarly, a model’s assigned probability is not a guarantee about a particular prediction.

Experiments, outcomes, and events

The basic terms are:

TermMeaningExample
Random experimentA process whose outcome is uncertain before it is observedRolling a die
OutcomeOne possible result of the experimentThe die shows 44
Sample spaceThe set of all possible outcomes, denoted Ω\Omega{1,2,3,4,5,6}\{1,2,3,4,5,6\}
EventA subset of the sample spaceGetting an even number, {2,4,6}\{2,4,6\}

For a fair six-sided die, all six outcomes are equally likely. If AA is the event that the result is even, then:

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

This counting method works when the possible outcomes are finite and equally likely. In general, outcomes can have different probabilities, so probability cannot always be calculated simply by counting favorable outcomes.

Three probability rules

Probability obeys a few fundamental rules:

  1. Non-negativity: P(A)≥0P(A)\geq 0 for every event AA.
  2. Normalization: P(Ω)=1P(\Omega)=1, because the sample space represents all possible outcomes.
  3. Additivity: If events AA and BB cannot occur together, P(A∪B)=P(A)+P(B)P(A\cup B)=P(A)+P(B).

The complement of AA, written AcA^c, is the event that AA does not occur:

P(Ac)=1−P(A)P(A^c)=1-P(A)

For any two events, whether or not they overlap:

P(A∪B)=P(A)+P(B)−P(A∩B)P(A\cup B)=P(A)+P(B)-P(A\cap B)

The symbols ∪\cup and ∩\cap mean union (at least one event occurs) and intersection (both events occur), respectively. We subtract the intersection because it would otherwise be counted twice.

Conditional probability: when information changes the question

A conditional probability measures the probability of one event given that another event has occurred.

For events AA and BB, provided P(B)>0P(B)>0:

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

The vertical bar ∣\mid means given. Thus, P(A∣B)P(A\mid B) is read as the probability of A given B.

Example: selecting a student

Suppose a class contains 4040 students:

Studies PythonDoes not study PythonTotal
Studies AI12820
Does not study AI61420
Total182240

Let AA mean the selected student studies AI and BB mean the selected student studies Python. Assume one student is selected uniformly at random.

The unconditional probability that the student studies AI is:

P(A)=2040=0.5P(A)=\frac{20}{40}=0.5

But given that the student studies Python, the relevant group contains only the 1818 Python students. Of these, 1212 also study AI:

P(A∣B)=1218=23≈0.667P(A\mid B)=\frac{12}{18}=\frac{2}{3}\approx 0.667

Notice that P(A)=0.5P(A)=0.5, while P(A∣B)≈0.667P(A\mid B)\approx 0.667. Learning that a student studies Python changes the probability assigned to studying AI.

The reverse conditional probability is different:

P(B∣A)=1220=0.6P(B\mid A)=\frac{12}{20}=0.6

In general, P(A∣B)P(A\mid B) is not equal to P(B∣A)P(B\mid A). Confusing these two probabilities is a common mistake when interpreting AI predictions.

Joint probability and the multiplication rule

The joint probability P(A∩B)P(A\cap B) is the probability that both events occur.

Rearranging the definition of conditional probability gives:

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

Equivalently, when P(A)>0P(A)>0:

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

This is often called the multiplication rule. It allows a joint probability to be calculated from a conditional probability and a marginal probability.

In the student example:

P(A∩B)=1240=0.3P(A\cap B)=\frac{12}{40}=0.3

Using the multiplication rule gives the same result:

P(A∣B)P(B)=1218⋅1840=0.3P(A\mid B)P(B)=\frac{12}{18}\cdot\frac{18}{40}=0.3

Independence and conditional independence

Two events AA and BB are independent if knowing whether one occurs does not change the probability of the other. Formally:

P(A∩B)=P(A)P(B)\boxed{P(A\cap B)=P(A)P(B)}

When the relevant conditioning event has positive probability, this is equivalent to P(A∣B)=P(A)P(A\mid B)=P(A).

For example, suppose a fair coin is flipped twice. Let AA be the first flip is heads and BB be the second flip is heads. The outcomes of the two flips are independent:

P(A∩B)=12⋅12=14P(A\cap B)=\frac{1}{2}\cdot\frac{1}{2}=\frac{1}{4}

Independent events are not the same as mutually exclusive events. Mutually exclusive events cannot happen together. If two mutually exclusive events both have positive probability, they cannot be independent.

Conditional independence

Events AA and BB are conditionally independent given CC when learning AA provides no additional information about BB once CC is known. For P(C)>0P(C)>0, the defining relationship is:

P(A∩B∣C)=P(A∣C)P(B∣C)P(A\cap B\mid C)=P(A\mid C)P(B\mid C)

This assumption appears in Naive Bayes classifiers: individual features are treated as conditionally independent once the class label is known. It is a simplifying modeling assumption, not a claim that words or other features are independent in everyday life.

Bayes’ theorem

Bayes’ theorem relates the conditional probability P(A∣B)P(A\mid B) to the reverse conditional probability P(B∣A)P(B\mid A).

Starting with the multiplication rule:

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

Substitute this expression into the definition of P(A∣B)P(A\mid B):

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

The result is Bayes’ theorem:

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

This form is valid when P(B)>0P(B)>0.

The four parts of a Bayesian update

In a classification setting, let HH represent a hypothesis and EE represent observed evidence:

P(H∣E)=P(E∣H)P(H)P(E)P(H\mid E)=\frac{P(E\mid H)P(H)}{P(E)}
QuantityNameInterpretation
P(H)P(H)Prior probabilityProbability assigned to the hypothesis before the new evidence
P(E∣H)P(E\mid H)LikelihoodHow probable the observed evidence is if the hypothesis is true
P(E)P(E)Evidence or marginal likelihoodOverall probability of observing the evidence
P(H∣E)P(H\mid E)Posterior probabilityUpdated probability of the hypothesis after observing the evidence

The distinction between likelihood and posterior probability matters. A signal can be common when a hypothesis is true without making that hypothesis highly probable whenever the signal is observed.

When there are two exhaustive hypotheses, HH and HcH^c, the law of total probability gives:

P(E)=P(E∣H)P(H)+P(E∣Hc)P(Hc)P(E)=P(E\mid H)P(H)+P(E\mid H^c)P(H^c)

This supplies the denominator required to compute the posterior probability.

Worked example: an email spam warning

Imagine an email filtering system with these hypothetical characteristics:

  • Only 1%1\% of incoming emails are spam.
  • It flags 95%95\% of spam emails as suspicious.
  • It incorrectly flags 10%10\% of non-spam emails.

A new email has been flagged. What is the probability that it is actually spam?

Define:

  • SS: the email is spam.
  • FF: the email is flagged.

The given probabilities are:

P(S)=0.01P(Sc)=0.99P(F∣S)=0.95P(F∣Sc)=0.10\begin{aligned} P(S)&=0.01\\ P(S^c)&=0.99\\ P(F\mid S)&=0.95\\ P(F\mid S^c)&=0.10 \end{aligned}

Apply Bayes’ theorem and the law of total probability:

P(S∣F)=P(F∣S)P(S)P(F∣S)P(S)+P(F∣Sc)P(Sc)P(S\mid F)=\frac{P(F\mid S)P(S)}{P(F\mid S)P(S)+P(F\mid S^c)P(S^c)}

Substitute the numbers:

P(S∣F)=0.95⋅0.010.95⋅0.01+0.10⋅0.99=0.00950.1085≈0.0876\begin{aligned} P(S\mid F) &=\frac{0.95\cdot0.01}{0.95\cdot0.01+0.10\cdot0.99}\\ &=\frac{0.0095}{0.1085}\\ &\approx 0.0876 \end{aligned}

The probability that a flagged email is spam is approximately 8.76%8.76\% under these assumptions, not 95%95\%.

Why? The filter detects most spam, but legitimate messages are so much more common that the false alarms outnumber the correctly flagged spam messages.

Visualizing the base rate

The same calculation is easier to see using a hypothetical batch of 10,00010{,}000 emails:

Probability tree for ten thousand emails. One hundred are spam and nine thousand nine hundred are not. Of the spam emails, ninety-five are flagged. Of the legitimate emails, nine hundred ninety are flagged. Therefore ninety-five of one thousand eighty-five flagged emails are spam.
Base rates matter: even a detection system with high sensitivity can have many false alarms when the target event is rare. All counts in this diagram are hypothetical.
Actual classFlaggedNot flaggedTotal
Spam955100
Not spam9908,9109,900
Total1,0858,91510,000

Among the 1,0851{,}085 flagged messages, 9595 are truly spam:

P(S∣F)=951085≈0.0876P(S\mid F)=\frac{95}{1085}\approx 0.0876

This illustrates the base-rate fallacy: overlooking how common or rare a condition is in the population when interpreting evidence about an individual case.

Calculating the posterior in Python

prior_spam = 0.01
sensitivity = 0.95            # P(flagged | spam)
false_positive_rate = 0.10   # P(flagged | not spam)

p_flagged = (
    sensitivity * prior_spam
    + false_positive_rate * (1 - prior_spam)
)

posterior_spam = sensitivity * prior_spam / p_flagged

print(f"P(spam | flagged) = {posterior_spam:.2%}")

Output:

P(spam | flagged) = 8.76%

This example uses given probabilities. In real applications, priors and error rates must be estimated from suitable data, and the resulting predictions must be evaluated on representative examples.

Probability distributions and random variables

A random variable assigns a numerical value to each outcome of a random experiment. A probability distribution describes how probability is assigned across that variable’s possible values.

Two broad kinds of random variables are important in AI:

KindPossible valuesMathematical descriptionExample
DiscreteCountable valuesProbability mass function (PMF)Number of clicks on an ad
ContinuousValues over intervalsProbability density function (PDF)A measured temperature

Discrete distributions

A probability mass function p(x)=P(X=x)p(x)=P(X=x) directly assigns probability to individual possible values. Its probabilities must be nonnegative and sum to 11:

∑xp(x)=1\sum_x p(x)=1

A Bernoulli distribution models a variable X∈{0,1}X\in\{0,1\} with success probability pp:

P(X=x)=px(1−p)1−x,x∈{0,1}P(X=x)=p^x(1-p)^{1-x},\qquad x\in\{0,1\}

For example, X=1X=1 could mean an email is spam and X=0X=0 could mean it is not. A Bernoulli model specifies the probability of each class for a single binary outcome.

Continuous distributions

A probability density function f(x)f(x) describes a continuous random variable. Probabilities are obtained by integrating the density over an interval:

P(a≤X≤b)=∫abf(x) dxP(a\leq X\leq b)=\int_a^b f(x)\,dx

The total area under a valid density equals 11. The height f(x)f(x) is not itself the probability of exactly xx; for a continuous variable, the probability at any single exact value is zero.

The normal distribution is a common continuous model with a symmetric, bell-shaped density. It is characterized by a mean μ\mu and variance σ2\sigma^2:

f(x)=1σ2πexp⁡ ⁣(−(x−μ)22σ2),σ>0f(x)=\frac{1}{\sigma\sqrt{2\pi}}\exp\!\left(-\frac{(x-\mu)^2}{2\sigma^2}\right),\quad \sigma>0

Normal distributions arise in statistical modeling and in some AI algorithms, but not every real dataset or model error follows a normal distribution. Distributional assumptions should be checked rather than applied automatically.

Expected value and variance

The expected value describes the probability-weighted mean of a random variable. For a discrete variable:

E[X]=∑xxP(X=x)E[X]=\sum_x xP(X=x)

The variance measures how spread out values are around their expected value:

Var⁡(X)=E[(X−E[X])2]\operatorname{Var}(X)=E[(X-E[X])^2]

For a Bernoulli variable with success probability pp:

E[X]=p,Var⁡(X)=p(1−p)E[X]=p,\qquad \operatorname{Var}(X)=p(1-p)

These quantities connect probability to Descriptive and Inferential Statistics, which explains how distributions can be estimated and evaluated using sampled data.

How Bayes’ theorem appears in AI

Bayesian reasoning can be used whenever predictions combine uncertain evidence with information about which outcomes are plausible before that evidence is seen.

Naive Bayes classification

A Naive Bayes classifier applies Bayes’ theorem to predict a class CC from features x1,x2,…,xnx_1,x_2,\ldots,x_n. Under the assumption that the features are conditionally independent given the class:

P(C∣x1,…,xn)∝P(C)∏i=1nP(xi∣C)P(C\mid x_1,\ldots,x_n)\propto P(C)\prod_{i=1}^{n}P(x_i\mid C)

The symbol ∝\propto means proportional to. To obtain normalized probabilities across classes, the class scores must be divided by their sum (assuming the relevant evidence has positive probability).

For an email classifier, features might represent whether certain words occur. The model combines a prior for each class with feature likelihoods to select a class. This assumption makes the calculation efficient but can be inaccurate when features are strongly dependent, and the resulting class probabilities are not automatically well-calibrated.

A separate PlainCS article, Naive Bayes and Probabilistic Classification, develops the algorithm and its variants in more detail.

Other applications

AI applicationRole of probability or Bayesian reasoning
Spam and document classificationComparing how likely classes are given observed features
Speech recognitionRanking possible transcriptions from uncertain audio evidence
Sensor fusionCombining noisy sensor observations with existing estimates
Fault detectionUpdating the probability of a malfunction after receiving warning signals
Bayesian machine learningExpressing uncertainty about parameters and predictions
Decision-making under uncertaintyEvaluating expected consequences of alternative actions

Not every AI model is a Bayesian model. Many systems use probabilistic outputs without explicitly representing parameter uncertainty or performing Bayesian updates.

Important distinctions and common mistakes

Probability is not certainty

A prediction of 0.80.8 does not mean an event must occur. It expresses a degree of uncertainty under the model. Whether such predictions are calibrated must be checked empirically: for example, among cases assigned probabilities near 0.80.8, the event should occur roughly 80%80\% of the time if the model is well-calibrated and the test data represent the intended setting.

Conditional probabilities cannot be reversed

P(flagged∣spam)P(\text{flagged}\mid\text{spam}) is the rate at which spam is flagged. P(spam∣flagged)P(\text{spam}\mid\text{flagged}) is the probability that a flagged message is spam. Bayes’ theorem connects them, but they are not interchangeable.

Independence is an assumption to justify

Multiplying probabilities of features without accounting for dependence can produce misleading results. The simplified Naive Bayes formula requires conditional independence given the class, not merely convenience.

A density is not a point probability

For continuous variables, probabilities refer to ranges. A density may be greater than 11 at some points while its total integrated area remains 11.

Estimated probabilities may change

Real-world class frequencies and feature patterns change over time. A prior learned from one population may not describe another. Data drift and incorrect modeling assumptions can weaken predictions, so models should be validated and monitored after deployment.

Practice problems

  1. A fair die is rolled. What is the probability of obtaining a number greater than 44? What is the probability of not obtaining a number greater than 44?
  2. In the student table above, calculate P(Python∣AI)P(\text{Python}\mid\text{AI}) and explain why it differs from P(AI∣Python)P(\text{AI}\mid\text{Python}).
  3. Suppose a classifier flags 80%80\% of rare positive cases, falsely flags 5%5\% of negative cases, and the positive class has a prevalence of 2%2\%. Calculate P(positive∣flagged)P(\text{positive}\mid\text{flagged}).
  4. Why does the formula for Naive Bayes use conditional independence rather than independence of all features in the overall population?
Show worked answers
  1. Outcomes greater than 44 are 55 and 66, so P(greater than 4)=2/6=1/3P(\text{greater than }4)=2/6=1/3. Its complement is 2/32/3.
  2. P(Python∣AI)=12/20=0.6P(\text{Python}\mid\text{AI})=12/20=0.6, while P(AI∣Python)=12/18≈0.667P(\text{AI}\mid\text{Python})=12/18\approx0.667. The conditions select different reference groups.
  3. P(+∣F)=(0.80⋅0.02)/(0.80⋅0.02+0.05⋅0.98)=0.016/0.065≈0.2462P(+\mid F)=(0.80\cdot0.02)/(0.80\cdot0.02+0.05\cdot0.98)=0.016/0.065\approx0.2462, or about 24.62%24.62\%.
  4. Features can be associated overall because they share a class label. The simplifying assumption is that, after conditioning on the class, one feature supplies no additional information about another.

References and further reading

Related articles in

Image preview

Fit