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
- Builds on
- 6 concepts →
- Quiz
- 5 questions ↓
This leads to
—The full path from zero — 6 concepts before this one
- What Is AI?
- Probability Basics
- How Machines Learn
- Bayes' Theorem
- Supervised, Unsupervised and Reinforcement Learning
- Supervised Learning
- 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.
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 (spam or ham) given the features of an email. Bayes' theorem says:
Read as "the probability of given ". The pieces are:
- , the prior: how common the class is before you look at the email.
- , the likelihood: how probable these features are if the email belongs to class .
- , the posterior: your updated belief after seeing the features.
- : 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 . With a vocabulary of 50,000 words there are 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:
The symbol ("pi") means "multiply together", just as means "add up". So the classifier is:
means "the class that makes this largest", and ("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
Score for ham:
These scores are not probabilities yet, because we skipped . Normalise by dividing each by their sum:
So the email is 57% likely to be spam. Had it contained only "free", the scores would be against , giving 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 times likelier in spam, so it multiplies the odds by 12, giving 480 : 60, or 8 : 1. "Meeting" is 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 , 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:
Here is the vocabulary size and 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 is , 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:
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. is the share of all words in class that are . 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.
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 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
- 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 now?
- In the from-scratch code, set
alpha = 0.01and re-run. Why do the probabilities become more extreme? Then try a message with a word from only one class.- 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, .
Learn more
Hand-picked courses, books, videos and tutorials for going deeper. See all resources →
StatQuest
Short, cheerful, very clear videos on statistics and nearly every ML algorithm.
A Plan for Spam
The essay that popularised Bayesian spam filtering, with the actual scoring rules the author used.
scikit-learn: Naive Bayes
Gaussian, multinomial, Bernoulli and complement naive Bayes, with the formulas each one uses.
Speech and Language Processing
The standard NLP textbook, kept up to date with chapters on Transformers and LLMs. Free drafts online.
An Introduction to Statistical Learning (with Python)
The friendliest rigorous introduction to classical ML, with Python labs. Free PDF.
Probabilistic Machine Learning
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