Lesson 8 of 16 · Conditioning
Naive Bayes Intuition
Naive Bayes from the ground up: Bayes' theorem for classification, the independence assumption, Laplace smoothing and logs. Build a spam filter in Python.
- 8 min read
- Intermediate
- Reviewed
- Use Bayes' theorem to choose between classes
- Explain the naive independence assumption and why it's useful
- Train a tiny Naive Bayes spam filter by counting words
- Use Laplace smoothing to handle words a class has never seen
- Add log probabilities to avoid numbers too small for a computer
Bayes' theorem as a classifier
Bayesian spam filters became popular in the early 2000s, and the idea behind them is still a standard first model for text. Everything in it comes from the last two lessons.
To decide whether an email is spam, compare two posteriors:
P(spam | words) = P(words | spam) × P(spam) / P(words)
P(ham | words) = P(words | ham) × P(ham) / P(words)(“Ham” is the usual name for normal, wanted email.) Both have the same bottom line, P(words), so to compare them we only need the top lines: prior × likelihood for each class. At the end, dividing each score by their total turns them back into probabilities that add up to 1.
The naive part
P(words | spam) is the probability of this exact combination of words in a spam email. Most combinations never appear in any training data, so we can't count it directly. Naive Bayes makes a bold simplification:
It's “naive” because it's not really true. “Free” and “prize” tend to appear together. But the assumption turns an impossible counting problem into an easy one, and the classifier often works well anyway, because it only needs to get the ranking of the classes right, not the exact probabilities.
Training is counting
To train the model, count:
- The priors: what share of training emails is spam.
- The word probabilities: how often each word appears in each class.
Here is a complete spam filter, trained on eight emails:
from collections import Counter
training = [
("spam", "win free prize now"),
("spam", "free money click now"),
("spam", "claim your free prize"),
("spam", "win money now"),
("ham", "are we still meeting for lunch"),
("ham", "can you send the report"),
("ham", "free lunch at the office today"),
("ham", "see you at the meeting"),
]
classes = ("spam", "ham")
# Training is just counting
priors = {c: sum(label == c for label, _ in training) / len(training) for c in classes}
word_counts = {c: Counter() for c in classes}
for label, text in training:
word_counts[label].update(text.split())
vocabulary = set(word_counts["spam"]) | set(word_counts["ham"])
def p_word(word, c):
"""P(word | class), with Laplace smoothing (add 1 to every count)."""
return (word_counts[c][word] + 1) / (sum(word_counts[c].values()) + len(vocabulary))
def p_spam(text):
scores = {}
for c in classes:
score = priors[c]
for word in text.split():
if word in vocabulary: # skip words never seen in training
score *= p_word(word, c) # the naive step: multiply word by word
scores[c] = score
return scores["spam"] / (scores["spam"] + scores["ham"])
for message in ["free prize now", "lunch meeting today", "free lunch"]:
print(f"{message:20} P(spam) = {p_spam(message):.3f}")- “free prize now” is almost certainly spam: all three words are common in spam.
- “lunch meeting today” looks normal.
- “free lunch” is a toss-up: “free” points to spam, “lunch” to normal email.
Logs: keeping tiny numbers alive
A real email can have hundreds of words. Multiplying hundreds of small probabilities gives a number too small for a computer to store, and it collapses to exactly 0:
import math
# A long email of 400 words, each with a probability of about 0.001 under one class
probs = [0.001] * 400
product = 1.0
for p in probs:
product *= p
print("multiplying:", product)
log_score = sum(math.log(p) for p in probs)
print("adding logs:", round(log_score, 1))The fix uses a rule of logarithms, log(a × b) = log(a) + log(b). Instead of multiplying probabilities, real implementations add their logs. The class with the biggest product also has the biggest sum of logs, so the decision doesn't change, and sums of logs never underflow.
Common mistakes
Classify the message free meeting with a tiny Naive Bayes model. The word free points to spam, but meeting points the other way. Which wins?
spam_words = {"win": 3, "free": 4, "prize": 2, "now": 3} # word counts in spam emails
ham_words = {"meeting": 3, "lunch": 2, "free": 1, "report": 2} # word counts in normal emails
vocabulary = set(spam_words) | set(ham_words) # 7 different words
def p_word(word, counts):
"""P(word | class) with Laplace smoothing: add 1 to every count."""
return (counts.get(word, 0) + 1) / (sum(counts.values()) + len(vocabulary))
message = "free meeting"
# Spam and normal emails are equally common, so the priors cancel out.
# Score the message for each class by multiplying p_word over its words.
# Then print P(spam | message) = spam_score / (spam_score + ham_score), rounded to 3 decimals.
Why does Naive Bayes use Laplace smoothing?
Summary
- Naive Bayes picks the class with the highest prior × likelihood; P(words) cancels out.
- The naive assumption treats words as independent within each class, so word probabilities just multiply.
- Training is counting: class shares for the priors, word counts for the likelihoods.
- Laplace smoothing adds 1 to every count so unseen words don't zero out a class.
- Real implementations add log probabilities to avoid underflow.
Next: discrete random variables.
Finished reading? Tick it off to track your progress.