TExcelTAD
Home › Probability Theory › Naive Bayes Classifiers

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 CC and features x1,…,xdx_1, \ldots, x_d, Bayes' theorem gives

Pr⁡[C∣x1,…,xd]∝Pr⁡[C] Pr⁡[x1,…,xd∣C]\Pr[C \mid x_1, \ldots, x_d] \propto \Pr[C] \, \Pr[x_1, \ldots, x_d \mid C]

Estimating the joint likelihood is hopeless for many features. The naive assumption is conditional independence given the class:

Pr⁡[x1,…,xd∣C]=∏i=1dPr⁡[xi∣C]\Pr[x_1, \ldots, x_d \mid C] = \prod_{i=1}^{d} \Pr[x_i \mid C]

Each factor is estimated by counting. To avoid underflow, work with logarithms: score =log⁡Pr⁡[C]+∑ilog⁡Pr⁡[xi∣C]= \log\Pr[C] + \sum_i \log\Pr[x_i \mid C]. 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 Pr⁡[word∣spam]=0\Pr[\text{word} \mid \text{spam}] = 0 and veto the class forever. Add-one smoothing estimates Pr⁡[w∣C]=count(w,C)+1total(C)+V\Pr[w \mid C] = \frac{\text{count}(w, C) + 1}{\text{total}(C) + V}, where VV is the vocabulary size. It is Laplace's rule of succession again.

A tiny spam filter

python · try it yourself
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 Pr⁡[xi∣C]\Pr[x_i \mid C] as a normal density with the class's mean and variance for that feature.

python · try it yourself
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

Pr⁡[spam]=0.4\Pr[\text{spam}] = 0.4. The word "offer" appears in 30% of spam and 2% of ham. Given only that a message contains "offer", what is Pr⁡[spam]\Pr[\text{spam}]?

Answer

0.12/0.132≈0.9090.12/0.132 \approx 0.909.

Solution

0.3⋅0.40.3⋅0.4+0.02⋅0.6=0.120.132\frac{0.3 \cdot 0.4}{0.3 \cdot 0.4 + 0.02 \cdot 0.6} = \frac{0.12}{0.132}.

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 Pr⁡[spam]\Pr[\text{spam}]?

Answer

About 0.3330.333.

Solution

Odds: prior 0.4/0.60.4/0.6, times 0.3/0.02=150.3/0.02 = 15, times 0.01/0.2=0.050.01/0.2 = 0.05: 23⋅0.75=0.5\frac{2}{3} \cdot 0.75 = 0.5. Probability 0.5/1.5=1/30.5/1.5 = 1/3.

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 Pr⁡[spam]=0\Pr[\text{spam}] = 0, and "win" (never in ham) would force Pr⁡[ham]=0\Pr[\text{ham}] = 0: both scores would be −∞-\infty.

Solution
python · try it yourself
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…

  1. classes are equally likely
  2. features are independent given the class
  3. features are normally distributed
  4. there are only two classes

Why are log-probabilities summed instead of multiplying probabilities?

  1. Logs are faster to compute
  2. To avoid numerical underflow with many small factors
  3. Because probabilities can be negative
  4. To make the classifier linear