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?
- About a coin flip
- Very well: the classes are cleanly separated
- Badly, because of label noise
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
- To classify, only the order matters: is the spam total bigger than the ham total? The probability's exact value doesn't.
- 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.
- 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).
- 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.
- 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?
- Nothing special: one word is one word
- The verdict becomes certain spam, whatever the other words say
- It crashes
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 messages | 20 | 50 | 100 | 200 | 1,000 | 3,901 |
|---|---|---|---|---|---|---|
| Naive Bayes | 88.2% | 91.1% | 94.0% | 95.2% | 97.6% | 98.3% |
| Logistic regression | 86.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.
- AUC jumps to 0.85
- Nothing changes
- AUC about the same, but it becomes far more confident
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
- Features that matter together. XOR, "risky only at night and downtown", word pairs whose meaning flips ("not good"): invisible one feature at a time. Add combined features (bigrams like "not good"), or use a model that learns interactions.
- Double counting. Correlated or duplicated features stack their evidence, so probabilities pile up near 0 and 1. Drop near-duplicates; if you need real probabilities, calibrate afterward on held-out data (
CalibratedClassifierCV). - The wrong shape. Gaussian naive Bayes assumes each feature is a bell curve within each class.
pdaysin the bank data is 999 for most calls and small for a few: two spikes, nothing like a bell, which is part of why its log-loss there is 1.06. Bin skewed features, or transform them. - Zero counts. Without smoothing, one word seen in only one class decides alone. Keep
alphaabove 0 (1 is the classic; tune it). - Lots of data. Its edge fades as data grows, since its simple picture can't improve; past a few thousand examples, logistic regression or boosted trees usually win.
6. The knobs that matter
| Knob | In scikit-learn | What it does |
|---|---|---|
| Which naive Bayes | MultinomialNB, BernoulliNB, GaussianNB, ComplementNB | Word counts; words present or absent (short texts); numeric bells; a variant more robust to imbalanced classes. |
| Smoothing | alpha (default 1) | Pseudo-counts added to every word in every class. Too small: unseen pairings decide; too big: every word looks the same. |
| The features | CountVectorizer(ngram_range, min_df, binary) | Word pairs catch "not good"; dropping rare words cuts noise; binary counts stop one repeated word from shouting. |
| Priors | fit_prior, class_prior | How common each class is believed to be; set them if production's mix differs from training's. |
| Threshold | your code | The 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