Naive Bayes Classifiers
Naive Bayes is the simplest probabilistic classifier: apply Bayes' theorem to the features of an item, assume the features are independent given the class, and pick the most probable class. It is fast, needs little data, and was the workhorse of the first effective spam filters. It is also a good lesson in how a wrong assumption can still give useful answers.
The model
For a class and features , Bayes' theorem gives
Estimating the joint likelihood is hopeless for many features. The naive assumption is conditional independence given the class:
Each factor is estimated by counting. To avoid underflow, work with logarithms: score . In odds form, each word contributes a likelihood ratio, exactly as in the odds form of Bayes.
Laplace smoothing
A word never seen in spam during training would get and veto the class forever. Add-one smoothing estimates , where is the vocabulary size. It is Laplace's rule of succession again.
A tiny spam filter
import math
from collections import Counter
train = [
("win money now", "spam"), ("cheap pills win big", "spam"), ("claim your free prize now", "spam"),
("free money claim now", "spam"), ("lunch meeting tomorrow", "ham"), ("project report attached", "ham"),
("can we move the meeting", "ham"), ("report due tomorrow see attached", "ham"),
("free lunch tomorrow", "ham"), ("are you coming to lunch", "ham"),
]
classes = ["spam", "ham"]
prior = Counter(c for _, c in train)
words = {c: Counter() for c in classes}
for text, c in train:
words[c].update(text.split())
vocab = {w for c in classes for w in words[c]}
def scores(text):
out = {}
for c in classes:
total = sum(words[c].values())
s = math.log(prior[c] / len(train))
for w in text.split():
s += math.log((words[c][w] + 1) / (total + len(vocab)))
out[c] = s
return out
for msg in ["win a free prize", "meeting report tomorrow", "free lunch meeting", "claim money"]:
s = scores(msg)
p_spam = 1 / (1 + math.exp(s["ham"] - s["spam"]))
print(f"{msg:26s} P(spam) = {p_spam:.3f}")win a free prize P(spam) = 0.923
meeting report tomorrow P(spam) = 0.030
free lunch meeting P(spam) = 0.123
claim money P(spam) = 0.895
The posterior probabilities come from normalising the two scores; "free lunch meeting" is classified as ham because "lunch" and "meeting" outweigh "free".
Why it works despite being naive
Words are clearly not independent ("free" and "prize" co-occur). The probability estimates are therefore over-confident, often pushed toward 0 or 1. But classification only needs the ranking of classes to be right, and that survives the wrong assumption surprisingly often. When calibrated probabilities matter, logistic regression or gradient boosting do better.
Gaussian naive Bayes
For numeric features, model each as a normal density with the class's mean and variance for that feature.
import numpy as np
rng = np.random.default_rng(5)
# two classes of points in 2D
X0 = rng.normal([0, 0], [1.0, 1.0], size=(200, 2))
X1 = rng.normal([2.5, 1.5], [1.0, 0.7], size=(200, 2))
X = np.vstack([X0, X1])
y = np.array([0] * 200 + [1] * 200)
def fit(X, y):
return {c: (X[y == c].mean(axis=0), X[y == c].std(axis=0), np.mean(y == c)) for c in (0, 1)}
def predict(model, X):
logp = []
for c in (0, 1):
mu, sd, prior = model[c]
ll = -0.5 * (((X - mu) / sd) ** 2).sum(axis=1) - np.log(sd).sum() + np.log(prior)
logp.append(ll)
return np.argmax(np.vstack(logp), axis=0)
model = fit(X, y)
Xt = np.vstack([rng.normal([0, 0], [1.0, 1.0], (1000, 2)), rng.normal([2.5, 1.5], [1.0, 0.7], (1000, 2))])
yt = np.array([0] * 1000 + [1] * 1000)
print("test accuracy:", (predict(model, Xt) == yt).mean())test accuracy: 0.934
In software
Naive Bayes powers baseline text classifiers (spam, sentiment, topic routing), is available as sklearn.naive_bayes, and remains a strong first model for small datasets. Its training is one pass of counting, so it scales to huge data and updates incrementally. See also Machine Learning for the broader picture.
Go further: Multinomial Naive Bayes for Text builds a larger text classifier and compares the variants and their smoothing.
Exercises
Exercise 1: By hand
. The word "offer" appears in 30% of spam and 2% of ham. Given only that a message contains "offer", what is ?
Answer
.
Solution
.
Exercise 2: Two words
Add a second word, "meeting", which appears in 1% of spam and 20% of ham, independent of "offer" given the class. A message contains both. What is ?
Answer
About .
Solution
Odds: prior , times , times : . Probability .
Exercise 3: Smoothing matters (code)
In the spam filter above, classify "win lunch" with smoothing and explain what would happen without it.
Answer
With smoothing both words contribute; without it, "lunch" (never seen in spam) would force , and "win" (never in ham) would force : both scores would be .
Solution
from collections import Counter
spam_words = Counter("win money now cheap pills win big claim your free prize now free money claim now".split())
ham_words = Counter("lunch meeting tomorrow project report attached can we move the meeting report due tomorrow see attached free lunch tomorrow are you coming to lunch".split())
for w in ["win", "lunch"]:
print(w, "spam count:", spam_words[w], " ham count:", ham_words[w])win spam count: 2 ham count: 0
lunch spam count: 0 ham count: 3
Each zero count would zero out one class, so the classifier could not decide at all.
Test yourself
The 'naive' assumption in naive Bayes is that…
- classes are equally likely
- features are independent given the class
- features are normally distributed
- there are only two classes
Why are log-probabilities summed instead of multiplying probabilities?
- Logs are faster to compute
- To avoid numerical underflow with many small factors
- Because probabilities can be negative
- To make the classifier linear