AI from scratch · Model zoo 4 of 10 · Naive Bayes

Naive Bayes

The first spam filters were naive Bayes, and it's still what you reach for when you have a few hundred labeled texts and need something working this afternoon. It's probability lesson 1's Bayes' rule, plus one bold shortcut: pretend every feature is independent of the others, once you know the class. The shortcut is almost always false, and the model works anyway, often. This page is about why, and about the cases where it doesn't.

1. The idea in one picture: each class measured one axis at a time

Gaussian naive Bayes describes each class by a bell curve along x and a separate bell curve along y: the ellipses are those clouds (one and two spreads out), and they are always lined up with the axes, never tilted, because the model never looks at how x and y move together. A new point goes to the class whose cloud makes it more likely, times how common that class is.

Pick checkerboard (XOR), where red means x and y have the same sign. Predict first: how does naive Bayes do?

Within red, x alone is half positive and half negative, and so is y: one axis at a time, red and blue look identical, two clouds centered on the origin. The class is entirely in how x and y go together, the one thing the shortcut throws away. On the ring, by contrast, it does very well: the disc's clouds are narrow on both axes and the ring's are wide, and that difference shows up one axis at a time.

Naive Bayes scores each class by multiplying how likely each feature is on its own; it's fast and needs little data, and it can't see features that only matter together.

2. How it learns: counting, then multiplying

Bayes' rule turns "how likely is this message if it's spam" into "how likely is it spam, given this message". The naive part is writing the first as a product, one factor per feature:

\[ P(\text{spam} \mid w_1, \dots, w_n) \;\propto\; P(\text{spam}) \prod_{j} P(w_j \mid \text{spam}) \]

Training is counting: the share of spam among messages, and for each word, how often it appears in spam and in normal messages ("ham"). No loss, no gradient, one pass over the data. To decide, compare the two classes' products; in practice, add logarithms, because multiplying hundreds of small numbers underflows to 0. Each word then adds its own evidence, \(\ln \frac{P(w \mid \text{spam})}{P(w \mid \text{ham})}\), to a running total.

Why a wrong assumption still gives the right answers, often
  1. To classify, only the order matters: is the spam total bigger than the ham total? The probability's exact value doesn't.
  2. Correlated words ("free", "prize", "claim" travel together) are counted as if each were separate evidence. That inflates the total, but it inflates it in the direction they all point.
  3. So the sign usually survives while the size is exaggerated: right side of 50%, wrong confidence (Domingos and Pazzani, 1997, showed this holds well beyond independent features).
  4. And it needs far less data: it estimates each word's rate on its own (thousands of easy averages) instead of how words combine. With few examples, a model with less to estimate wins (Ng and Jordan, 2001); with many, a model like logistic regression that learns the combinations catches up.
  5. The flip side: anything that depends on the confidence (a probability you report, a threshold at 99%, combining with other models) inherits the exaggeration. Section 4 measures it.

3. A spam filter, trained in your browser

5,574 real text messages from the UK and Singapore, 13% spam. The filter below learned from 70% of them a moment ago, by counting. Type or edit a message: each word's bar is its evidence (right for spam, left for ham), and the total plus the prior gives the verdict.

Loading 5,574 messages…

Tick no smoothing and type a word that appeared in spam but never in a normal message, like "awarded". What happens?

Without smoothing, P(awarded | ham) = 0, so its evidence is infinite and a single word decides. (Add "later", a word never seen in spam, and the filter is stuck with +∞ − ∞: no answer at all.) Smoothing (Laplace: add 1 to every count) says "never seen" isn't "impossible". Measured on the held-out messages: with almost no smoothing the log-loss is 0.53, with add-1 smoothing 0.11.

Each word adds its own evidence for spam or ham, and the totals are compared; smoothing stops one never-seen pairing from deciding everything.

4. Build it: multinomial naive Bayes in NumPy

The spammiest words read like a scam: claim, prize, 150p, tone, guaranteed; the hammiest are chat: said, later, she, lor, da (Singaporean English), and lt, gt from garbled "<" and ">" in the source data. That list is the whole model: one number per word.

5. Where it shines, where it breaks

Shines: on the text messages it gets 98.3% right (precision 97.6%, recall 89%), trained in a few milliseconds. Its edge is little data. Trained on random handfuls of messages and averaged over 10 draws, test accuracy was:

Training messages20501002001,0003,901
Naive Bayes88.2%91.1%94.0%95.2%97.6%98.3%
Logistic regression86.7%87.4%89.2%91.1%96.5%97.8%

A fair footnote: by AUC, which judges the ranking rather than the 50% cutoff, logistic regression is ahead at every size (0.91 against 0.81 at 50 messages). With little data, naive Bayes makes better yes/no calls; logistic regression's scores sort better but it rarely dares to say spam.

On the bank calls, Gaussian naive Bayes gets an AUC of 0.74. You add 9 more copies of the euribor column. Predict the AUC and the confidence.

Measured: AUC 0.740 → 0.748, but the share of calls it gives over 90% chance of a yes went from 5% to 33%, and its log-loss from 1.06 to 2.85. Ten copies are counted as ten independent witnesses saying the same thing. Logistic regression's log-loss on the same columns is 0.30: it would split one weight among the copies.

Naive Bayes is the fast, small-data, many-features classifier (text above all); its rankings are useful and its probabilities are not to be trusted.

Where it breaks, and what people do

6. The knobs that matter

KnobIn scikit-learnWhat it does
Which naive BayesMultinomialNB, BernoulliNB, GaussianNB, ComplementNBWord counts; words present or absent (short texts); numeric bells; a variant more robust to imbalanced classes.
Smoothingalpha (default 1)Pseudo-counts added to every word in every class. Too small: unseen pairings decide; too big: every word looks the same.
The featuresCountVectorizer(ngram_range, min_df, binary)Word pairs catch "not good"; dropping rare words cuts noise; binary counts stop one repeated word from shouting.
Priorsfit_prior, class_priorHow common each class is believed to be; set them if production's mix differs from training's.
Thresholdyour codeThe probabilities are overconfident, so pick a cutoff on validation data, or calibrate first.

Next in the zoo: a model that asks questions, one column at a time.

All chapters: AI from scratch. SMS Spam Collection: Almeida, Gómez Hidalgo and Yamakami (2011), UCI Machine Learning Repository, CC BY 4.0. Bank marketing: Moro, Cortez and Rita (2014), UCI, CC BY 4.0.

Last updated