◆ AI All-in-One

Level 3 In-Depth AI · Classical Machine Learning

Naive Bayes

Bayes' theorem plus one bold simplification, that every feature is independent of the others given the class. The result is a tiny, fast classifier that filtered the world's spam and is still a strong baseline for text.

Level
●●●●● Easy
Reading
13 min
To learn it well
45 minutes to read, an hour to practise
↗ Plan a path here

Read first

Bayes' TheoremSupervised Learning

This leads to

—
The full path from zero — 6 concepts before this one
  1. What Is AI?
  2. Probability Basics
  3. How Machines Learn
  4. Bayes' Theorem
  5. Supervised, Unsupervised and Reinforcement Learning
  6. Supervised Learning
  7. Naive Bayes

Read them roughly in this order. See it on the concept map →

Why it matters

In the early 2000s spam was drowning email. Hand-written rules ("block anything containing VIAGRA") were easy to dodge. What worked was a classifier that learned, from a pile of emails people had marked as spam or not, how much each word pointed one way or the other. That classifier was naive Bayes, and versions of it shipped in Mozilla Thunderbird, SpamAssassin and countless mail servers.

Naive Bayes is still worth knowing because it is:

  • Fast. Training is just counting. It handles millions of documents and a vocabulary of a million words on a laptop in seconds.
  • Good with little data. With a few hundred labelled examples it often beats fancier models, which need more data to settle down.
  • A clean example of probabilistic thinking. It applies Bayes' Theorem directly: start with a prior belief, multiply in each piece of evidence, end with a posterior. The same reasoning reappears in language models, variational autoencoders and Bayesian methods throughout AI.

It is also a lesson in why a model built on a wrong assumption can still make right decisions.

The intuition

Imagine you are a mail clerk sorting letters into "spam" and "real". You have no rule book, but you have sorted thousands of letters and noticed things. "FREE" turns up in most spam and rarely in real mail. "Meeting" is the reverse. "The" turns up in both equally, so it tells you nothing.

When a new letter arrives you start with a hunch based on how common spam is overall, say 40%. Then you read it word by word. Each word nudges your belief up or down, by an amount that depends on how much more common that word is in spam than in real mail.

Before reading prior: 40 of 100 emails are spam spam 40% ham 60% × 0.60 for spam, × 0.05 for ham (12 : 1 for spam) After seeing “free” in 60% of spam, 5% of ham spam 89% ham 11% × 0.05 for spam, × 0.30 for ham (6 : 1 for ham) After also seeing “meeting” in 5% of spam, 30% of ham spam 57% ham 43% each word multiplies the odds by how much likelier it is in spam than in ham
Fig. 1 How naive Bayes updates its belief. It starts from the prior, 40% spam. The word "free" is 12 times likelier in spam, pushing the belief to 89%. The word "meeting" is 6 times likelier in ham, pulling it back to 57%.

The "naive" part is that you treat every word as a separate, independent clue. You don't consider that "free" and "prize" tend to appear together, which means seeing both is less surprising than the two clues suggest. That is plainly false for real language. But for deciding spam versus not-spam it rarely matters much, and it makes the arithmetic trivial.

Key idea Naive Bayes multiplies a prior (how common each class is) by one likelihood per feature (how typical that feature is for each class), assuming the features are independent within each class. The class with the biggest product wins.

How it works

Bayes' theorem for classification

We want the probability of a class cc (spam or ham) given the features x=(x1,…,xn)\mathbf{x} = (x_1, \dots, x_n) of an email. Bayes' theorem says:

P(c∣x)=P(c) P(x∣c)P(x)P(c \mid \mathbf{x}) = \frac{P(c)\, P(\mathbf{x} \mid c)}{P(\mathbf{x})}

Read P(c∣x)P(c \mid \mathbf{x}) as "the probability of cc given x\mathbf{x}". The pieces are:

  • P(c)P(c), the prior: how common the class is before you look at the email.
  • P(x∣c)P(\mathbf{x} \mid c), the likelihood: how probable these features are if the email belongs to class cc.
  • P(c∣x)P(c \mid \mathbf{x}), the posterior: your updated belief after seeing the features.
  • P(x)P(\mathbf{x}): how probable the features are overall. It is the same for every class, so when we only want to know which class is most probable we can ignore it and normalise at the end.

The hard part is P(x∣c)P(\mathbf{x} \mid c). With a vocabulary of 50,000 words there are 250,0002^{50{,}000} possible combinations of words present or absent. You could never estimate the probability of each combination.

The naive assumption

Naive Bayes assumes conditional independence: once you know the class, each feature tells you nothing about the others. Then the joint likelihood splits into a product of one-feature likelihoods, each easy to estimate by counting:

P(x∣c)≈∏j=1nP(xj∣c)P(\mathbf{x} \mid c) \approx \prod_{j=1}^{n} P(x_j \mid c)

The symbol ∏\prod ("pi") means "multiply together", just as ∑\sum means "add up". So the classifier is:

y^=arg⁡max⁡c  P(c)∏j=1nP(xj∣c)\hat{y} = \arg\max_{c} \; P(c) \prod_{j=1}^{n} P(x_j \mid c)

arg⁡max⁡c\arg\max_c means "the class cc that makes this largest", and y^\hat{y} ("y-hat") is the prediction.

A worked example by hand

Suppose you have 100 labelled emails: 40 spam and 60 ham. You count how many contain two words:

Word Spam emails containing it Ham emails containing it
"free" 24 of 40 = 0.60 3 of 60 = 0.05
"meeting" 2 of 40 = 0.05 18 of 60 = 0.30

A new email contains "free" and "meeting". (To keep the arithmetic short, we ignore words that are absent. The full Bernoulli version would multiply in a factor for each missing word too.)

Score for spam: prior × likelihoods =0.40×0.60×0.05=0.0120= 0.40 \times 0.60 \times 0.05 = 0.0120

Score for ham: 0.60×0.05×0.30=0.00900.60 \times 0.05 \times 0.30 = 0.0090

These scores are not probabilities yet, because we skipped P(x)P(\mathbf{x}). Normalise by dividing each by their sum:

P(spam∣free, meeting)=0.01200.0120+0.0090=0.571P(\text{spam} \mid \text{free, meeting}) = \frac{0.0120}{0.0120 + 0.0090} = 0.571

So the email is 57% likely to be spam. Had it contained only "free", the scores would be 0.40×0.60=0.240.40 \times 0.60 = 0.24 against 0.60×0.05=0.030.60 \times 0.05 = 0.03, giving 0.24/0.27=89%0.24 / 0.27 = 89\% spam. That is exactly the path in the figure above.

Another way to see it is in odds. The prior odds are 40 : 60. The word "free" is 0.60/0.05=120.60 / 0.05 = 12 times likelier in spam, so it multiplies the odds by 12, giving 480 : 60, or 8 : 1. "Meeting" is 0.05/0.30=1/60.05 / 0.30 = 1/6 as likely in spam, so it divides the odds by 6, giving 8 : 6, which is 57%. Each feature contributes one multiplicative factor, its likelihood ratio.

Two practical fixes

The zero problem. Suppose "prize" appeared in some spam but in none of your 60 ham emails. Then P(prize∣ham)=0P(\text{prize} \mid \text{ham}) = 0, and any email containing "prize" gets a ham score of exactly zero, however strongly every other word says ham. One unseen word vetoes everything.

The fix is Laplace smoothing (also called add-one smoothing): pretend you saw every word one extra time in every class. For word counts it looks like this:

P(w∣c)=count(w,c)+αtotal words in c+α VP(w \mid c) = \frac{\text{count}(w, c) + \alpha}{\text{total words in } c + \alpha \, V}

Here VV is the vocabulary size and α\alpha is the smoothing strength, usually 1. No probability is ever zero, and words seen often barely change.

The underflow problem. A long email multiplies hundreds of small probabilities together. A product like 0.013000.01^{300} is 10−60010^{-600}, smaller than the tiniest number a computer's floating point can hold, so it rounds to zero. The fix is to work with log probabilities. The log of a product is the sum of the logs, and sums of moderately negative numbers are perfectly safe:

log⁡P(c)+∑jlog⁡P(xj∣c)\log P(c) + \sum_{j} \log P(x_j \mid c)

Pick the class with the largest sum. This also shows that naive Bayes is a linear model in disguise: a weighted sum of features (each word's log-likelihood ratio) plus a bias (the log prior ratio), just like Logistic Regression. The two differ in how they choose the weights. Naive Bayes counts; logistic regression optimises.

Flavours for different features

The independence trick works with any per-feature distribution. The three common ones:

  • Multinomial naive Bayes treats a document as a bag of words: word order is thrown away and only the counts are kept. P(w∣c)P(w \mid c) is the share of all words in class cc that are ww. It is the standard choice for text.
  • Bernoulli naive Bayes records only whether each word is present or absent (the setting of our hand example), and also counts the evidence of missing words. It suits short texts.
  • Gaussian naive Bayes handles continuous measurements by fitting a bell curve (a normal distribution) to each feature within each class. The likelihood of a value is the height of that class's curve at that value.
1 2 3 4 5 6 7 petal length (cm) setosa mean 1.46, sd 0.17 versicolor mean 4.26, sd 0.47 virginica mean 5.55, sd 0.55 one bell curve per class, fitted to that class's flowers coloured strip = predicted class
Fig. 2 Gaussian naive Bayes on one feature of the iris flowers. A bell curve is fitted to each species' petal lengths. A new flower is assigned to whichever species' curve is highest at its petal length (times the prior), which splits the axis at about 2.2 cm and 4.9 cm.

For a flower with a 4.8 cm petal, the versicolor curve is a little higher than the virginica curve, so Gaussian naive Bayes says versicolor with probability 0.61. With all four iris measurements, each contributes its own curve, and the likelihoods multiply.

In code

Multinomial naive Bayes from scratch on ten tiny messages. Training is nothing but counting.

import numpy as np

spam = ["win free money now", "free prize claim now", "free free money", "claim your prize now"]
ham  = ["meeting tomorrow at noon", "lunch tomorrow", "send me the report",
        "are you free for lunch", "see you at the meeting", "report due tomorrow"]

docs = [d.split() for d in spam + ham]
y = np.array([1] * len(spam) + [0] * len(ham))          # 1 = spam, 0 = ham
vocab = sorted({w for d in docs for w in d})
idx = {w: i for i, w in enumerate(vocab)}

# Word counts per class (multinomial naive Bayes)
counts = np.zeros((2, len(vocab)))
for d, label in zip(docs, y):
    for w in d:
        counts[label, idx[w]] += 1

alpha = 1.0                                              # Laplace smoothing
log_prior = np.log(np.bincount(y) / len(y))              # log P(class)
log_lik = np.log((counts + alpha) / (counts.sum(1, keepdims=True) + alpha * len(vocab)))

def predict_proba(text):
    words = [w for w in text.split() if w in idx]        # ignore unseen words
    scores = log_prior + log_lik[:, [idx[w] for w in words]].sum(1)
    p = np.exp(scores - scores.max())                    # back from logs, safely
    return p / p.sum()                                   # [P(ham), P(spam)]

for msg in ["free money", "free lunch tomorrow", "claim the report"]:
    print(f"{msg!r:24} P(spam) = {predict_proba(msg)[1]:.3f}")

# 'free money'             P(spam) = 0.882
# 'free lunch tomorrow'    P(spam) = 0.202
# 'claim the report'       P(spam) = 0.289

Notice "free lunch tomorrow": "free" leans spam, but "lunch" and "tomorrow" lean ham, and together they win. The same thing in scikit-learn, where CountVectorizer builds the bag-of-words counts:

from sklearn.feature_extraction.text import CountVectorizer
from sklearn.naive_bayes import MultinomialNB
from sklearn.pipeline import make_pipeline

spam = ["win free money now", "free prize claim now", "free free money", "claim your prize now"]
ham  = ["meeting tomorrow at noon", "lunch tomorrow", "send me the report",
        "are you free for lunch", "see you at the meeting", "report due tomorrow"]

model = make_pipeline(CountVectorizer(), MultinomialNB(alpha=1.0))
model.fit(spam + ham, [1] * 4 + [0] * 6)
print(model.predict_proba(["free money", "free lunch tomorrow", "claim the report"])[:, 1].round(3))
# [0.882 0.202 0.289]

Same numbers. For continuous features use GaussianNB. Here it is against Logistic Regression on a medical dataset:

from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import cross_val_score
from sklearn.naive_bayes import GaussianNB
from sklearn.linear_model import LogisticRegression
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler

X, y = load_breast_cancer(return_X_y=True)        # 569 tumours, 30 measurements
for name, m in [("Gaussian naive Bayes", GaussianNB()),
                ("logistic regression", make_pipeline(StandardScaler(), LogisticRegression()))]:
    print(f"{name:21} accuracy {cross_val_score(m, X, y, cv=5).mean():.3f}")

# Gaussian naive Bayes  accuracy 0.939
# logistic regression   accuracy 0.981

Naive Bayes does well, but loses here. Many of these 30 measurements are strongly correlated (radius, perimeter and area of the same tumour), so the independence assumption counts the same evidence several times. Logistic regression learns to discount the duplicates.

Common pitfalls

  • Trusting the probabilities. Because correlated features are double-counted, naive Bayes tends to be overconfident: it says 99.9% when it should say 80%. Its ranking of classes is often good while its probabilities are badly calibrated. If you need real probabilities, calibrate them (see Evaluation Metrics) or use a different model.
  • Forgetting smoothing. Without it, one word never seen in a class can force a probability of zero. scikit-learn smooths by default (alpha=1.0); hand-rolled code often doesn't.
  • Multiplying raw probabilities. Long documents underflow to zero. Always add logs.
  • Using the wrong flavour. Multinomial NB expects non-negative counts; feeding it standardised features (with negatives) is an error. Gaussian NB on word counts works poorly.
  • Heavily duplicated features. If the same information appears in many features, naive Bayes multiplies it in many times. Remove near-duplicate features first.

Watch out A naive Bayes probability of 0.999 does not mean "99.9% sure". The model double-counts correlated evidence, so its confidence is usually exaggerated. Use it to rank and decide, and check calibration before treating its outputs as real probabilities.

Why a "wrong" model works so well

Words are obviously not independent. "San" is nearly always followed by "Francisco" or "Diego". So why does naive Bayes classify well?

Because classification only needs the right winner, not the right probabilities. Double-counting correlated evidence inflates the scores of all classes, and often pushes the winning class further ahead rather than changing which class wins. Domingos and Pazzani analysed this in 1997 and showed that naive Bayes can be the optimal classifier even when the independence assumption is badly violated, as long as the errors don't flip the ranking.

Its simplicity also gives it a statistical advantage. It estimates each feature's distribution separately, which needs far less data than estimating how features interact. On small datasets that low variance often beats a more flexible model's lower bias (see Overfitting and the Bias–Variance Tradeoff). With lots of data, discriminative models such as Logistic Regression usually overtake it.

Where it leads

  • Logistic regression is naive Bayes' discriminative cousin. Same linear form, but weights fitted to predict the label directly. See Logistic Regression.
  • Language models generalise the counting idea. A bigram model estimates P(next word∣previous word)P(\text{next word} \mid \text{previous word}) by counting, with the same smoothing tricks. See Language Modeling and Next-Token Prediction.
  • Text classification today mostly uses fine-tuned transformers such as BERT and Encoder Models, or embeddings fed to a simple classifier. Naive Bayes remains the five-minute baseline you should beat first.
  • Bayesian networks drop the "everything independent" assumption and model a chosen set of dependencies as a graph.

A bit of history

The theorem is from Thomas Bayes, published after his death in 1763, and was developed by Pierre-Simon Laplace, who also introduced the add-one rule now called Laplace smoothing. Classifiers that assume independent features were studied in pattern recognition and information retrieval from the 1960s; Maron's 1961 work on automatically indexing documents is an early example.

The method's fame came with spam. Sahami, Dumais, Heckerman and Horvitz described a Bayesian spam filter in 1998, and Paul Graham's 2002 essay A Plan for Spam popularised the approach. Graham reported catching about 99.5% of his own spam with very few false positives. Within a couple of years Bayesian filtering was standard in mail software. Spammers responded by stuffing messages with innocent words, the first widespread example of adversarial attacks on a machine-learning model.

Try it

  1. Redo the hand example for an email containing "free", "meeting" and a third word, "report", which appears in 1 of 40 spam and 15 of 60 ham emails. What is P(spam)P(\text{spam}) now?
  2. In the from-scratch code, set alpha = 0.01 and re-run. Why do the probabilities become more extreme? Then try a message with a word from only one class.
  3. Harder: add a copy of every spam message to the training set (so each appears twice) and re-run. Which numbers change, and why does the prior matter?

Hint for 1: the new word multiplies the odds by its likelihood ratio, (1/40)/(15/60)=0.1(1/40) / (15/60) = 0.1.

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. Prior spam rate is 40%. The word "free" appears in 60% of spam and 5% of ham. For an email with just "free", what does naive Bayes give?

  2. A word never appeared in any ham training email. Without smoothing, what happens to any new email containing it?

  3. Why does naive Bayes add log probabilities instead of multiplying raw probabilities?

  4. Naive Bayes says an email is 99.9% spam. Many of its features are strongly correlated. How should you read that number?

  5. You want to classify flowers from continuous measurements such as petal length. Which flavour fits?

Finished this chapter?

Learn more

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

Video

StatQuest

Josh Starmer · Beginner · Free

Short, cheerful, very clear videos on statistics and nearly every ML algorithm.

Article

A Plan for Spam

Paul Graham · 2002 · Beginner · Free

The essay that popularised Bayesian spam filtering, with the actual scoring rules the author used.

Docs

scikit-learn: Naive Bayes

scikit-learn · Intermediate · Free

Gaussian, multinomial, Bernoulli and complement naive Bayes, with the formulas each one uses.

Book

Speech and Language Processing

Dan Jurafsky & James H. Martin · Intermediate · Free

The standard NLP textbook, kept up to date with chapters on Transformers and LLMs. Free drafts online.

Book

Probabilistic Machine Learning

Kevin P. Murphy · Advanced · Free

A comprehensive two-volume reference viewing ML through probability. Free drafts online.

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