Lesson 14 · Thinking in probabilities
Naive Bayes
The problem
After each delivery, customers can leave a short note. The shop has 200 of them, and someone has marked the 40 that are complaints:
| Note | Complaint? |
|---|---|
| "friendly was" | no |
| "late cold wrong soggy was" | yes |
| "thanks was hot tasty" | no |
| "soggy cold missing" | yes |
The notes are made up for this lesson, and already cut into lowercase words. The manager wants new complaints flagged automatically, so someone can call back the same evening.
The features this time are words, not numbers. This lesson builds a classifier for text from Bayes' rule and counting, with one bold shortcut. It's fast, needs little data, and is still a standard first try for text.
One word: Bayes' rule
Start with one clue. Some notes contain the word "cold". From the 200 notes:
- 20% are complaints: 40 of 200.
- Half of the complaints say "cold": 20 of 40.
- 5% of the other notes say "cold": 8 of 160.
A new note says "cold". How likely is it to be a complaint? The square below is all notes. The left column is the complaints, the right column the rest. The dark parts are the notes that say "cold".
Dark area (notes that say “cold”): 0.100 + 0.040 = 0.140
P(complaint | cold) = 0.100 ÷ 0.140 = 0.714
The answer is the share of the dark area that sits in the complaints column.
Predict first
20% of notes are complaints. Half of complaints mention 'cold'; 5% of other notes do. A note says 'cold'. What's the chance it's a complaint?
In the language of the last lesson, 0.2 is the prior, the belief before reading the note. The 0.71 is the posterior, the belief after.
Many words: a bag
A note has several words, and each one is a clue. First, decide what to do about word order. "late again the pizza was late" and "the pizza was late again, late" say much the same thing. So throw the order away and keep only how often each word appears.
Describing a text by its word counts, ignoring order, is called a bag of words. Picture tipping the note's words into a bag and shaking it.
“late again the pizza was late”
The boxes are the bag: each word with its count. Shuffling changes the note but not the bag.
The 200 notes use 20 different words, their vocabulary. So each note becomes a list of 20 counts, mostly zeros. That list is the note's feature vector.
A bag loses information. "not late" and "late, not" look the same. For flagging complaints that rarely matters, and the counts are easy to work with.
The naive assumption
Bayes' rule for a whole note needs : the chance that a complaint contains exactly this bag of words. Counting that directly is hopeless. Most bags appear once or never, even in 200 notes.
So make a bold simplification. Pretend that, once you know the class, each word is chosen without regard to the others. Then the chance of the bag is a product, one factor per word:
This is conditional independence: two things are independent once you know a third. It's weaker than plain independence. "Cold" and "late" are not independent overall: both are more common in complaints, so seeing one makes the other more likely. The assumption is only that, among complaints alone, seeing "cold" tells you nothing more about "late".
That's still usually false. A complaint that says "late" is probably more likely to say "slow" too. The classifier that makes this assumption anyway is naive Bayes, and "naive" is the honest admission.
Where the word probabilities come from
Each class gets its own bag of all its words. The complaints contain 135 words in total, and 20 of them are "cold". So in this model,
The other notes contain 479 words, and 8 are "cold", so .
This is a share of words, not of notes. It differs from the "half of complaints mention cold" above, which counted notes. The word version is what the model uses, because it treats each word in a note as a separate draw from the class's bag.
Counting shares like this is maximum likelihood again: the same "3 late of 10 gives 0.3" rule, applied to every word in every class. The class probabilities are counted the same way: .
Comparing the two classes
To decide, compare the two posteriors. In Bayes' rule they share the same bottom, , so it cancels in the ratio:
A ratio like this is called the odds. Read it back: start from the prior odds, then multiply by one factor per word. Each factor says how many times more common the word is in complaints.
Worked example
The note “cold late”
Prior odds: 40 complaints to 160 others, so .
Adding up evidence
Multiplying many factors is awkward to picture. Take logs and they become sums, as in the last lesson. In the example above, , and . They add up to , the log of 31.5.
So naive Bayes keeps a running score. It starts at the prior's log-odds and adds one number per word. A positive number is evidence for a complaint, a negative one evidence against. The final score's sign decides the class, and the sigmoid turns it into a probability: .
Build a note and watch the bars. The figure uses all 200 notes and smoothed counts (explained in the next section), so its numbers differ a little from the worked example.
The note (tap a word to remove it):
- prior−1.39
- “cold”+2.02
- “late”+2.35
- total+2.98
P(complaint) = 0.952 → complaint
Add a word:
Things to notice:
- Words like "burnt", "soggy" and "missing" push hard towards complaint. "great", "fast" and "tasty" push hard the other way.
- "pizza", "order" and "the" barely move the score. Both classes use them about equally.
- Adding "late" twice adds its bar twice. Naive Bayes counts repeated words as repeated evidence.
- The prior starts the score at . A note with no strong words is called "not a complaint", because complaints are rarer.
When a count is zero
The word "thanks" appears 53 times in the other notes and never in a complaint. So by counting, .
Now a customer writes "cold late thanks". Two words point to a complaint. But the product for "complaint" contains a factor of 0, so the whole product is 0. The model says the chance of a complaint is exactly 0, whatever else the note says. In logs, the bar for "thanks" is .
| word | count in complaints | count in others |
|---|---|---|
| cold | 20P = 0.148 | 8P = 0.017 |
| late | 12P = 0.089 | 3P = 0.006 |
| thanks | 0P = 0 | 53P = 0.111 |
- prior−1.39
- “cold”+2.18
- “late”+2.65
- “thanks”−∞
- total−∞
P(complaint) = 0.000 → not a complaint
Hatched bars are infinite. Slide α up from 0 and watch them become ordinary bars.
Things to notice:
- At α = 0, "cold late thanks" gets P(complaint) = 0. One word that never appeared in a complaint wipes out all the other evidence.
- "burnt cold thanks" is worse. "burnt" has never appeared outside a complaint, so its bar is , and has no answer.
- Any α above 0 makes every bar finite. At α = 1, "cold late thanks" gets 0.54: a close call, as it should be.
A zero count means "not seen in 135 words", not "impossible". The fix is the pretend counts from the last lesson. Before counting, add α pretend occurrences of every word to each class. With a vocabulary of words,
The on the bottom keeps the probabilities adding up to 1. With this is Laplace smoothing, or add-one smoothing.
Worked example
Smoothing “thanks” with α = 1
The vocabulary has words, so each class gains 20 pretend words.
Smoothing is a MAP estimate, the same move as the pretend deliveries. The prior says "every word can appear in every class". A bigger α is a stronger prior: it pulls the two classes' word probabilities closer together. So α is a hyperparameter. The usual default is 1, and cross-validation can tune it.
DigressionLaplace and the sunriseAdd one to the count of each outcome: a rule from the 1700s and 1800s. · 1 min
Thomas Bayes' essay on reasoning backwards from evidence was published in 1763, after his death, by his friend Richard Price. Pierre-Simon Laplace developed the same ideas further.
One of Laplace's results is now called the rule of succession. If something has happened times in tries, estimate the chance it happens next time as . That's one pretend success and one pretend failure: exactly add-one smoothing with two outcomes. Laplace's famous (and debated) example was the chance that the sun rises tomorrow, given that it has risen every day on record.
In scikit-learn
scikit-learn splits the job in two. CountVectorizer turns each note into its bag of words. MultinomialNB does the counting, the smoothing and the Bayes' rule. make_pipeline chains them, so the whole thing is one estimator that takes raw text (pipelines get a full explanation later in this course).
texts, y = complaint_notes() # 200 notes; 40 are complaints
texts_train, texts_test, y_train, y_test = train_test_split(
texts, y, test_size=0.25, stratify=y, random_state=0 # 150 to train on, 50 to test
)
model = make_pipeline(CountVectorizer(), MultinomialNB(alpha=1.0)) # words → counts → naive Bayes
model.fit(texts_train, y_train)
print(model.score(texts_test, y_test)) # 1.0: all 50 test notes right
print(model.predict_proba(NEW_NOTES).round(3)) # columns: P(not a complaint), P(complaint)
print(model.predict(NEW_NOTES)) # [1 1 0]1.0
[[0.3 0.7 ]
[0.153 0.847]
[0.999 0.001]]
[1 1 0]What to notice:
- The model trains on 150 notes and is tested on the 50 it never saw (
train_test_split).stratify=ykeeps 20% complaints in both parts. It gets all 50 right. Don't expect that on real notes. These notes were generated exactly the way naive Bayes assumes (each word drawn from its class's bag). And 50 test notes hold only 10 complaints, so one score this high says little. Real complaint text is messier and scores lower. MultinomialNB(alpha=1.0)is Laplace smoothing. "Multinomial" is the name for the counts-of-words model above.- "cold late thanks" gets 0.70 here, not the figure's 0.54, because this model saw only 150 notes.
Inside the fitted pipeline are the counts from this lesson:
vectorizer, nb = model.named_steps["countvectorizer"], model.named_steps["multinomialnb"]
print(vectorizer.get_feature_names_out()) # the vocabulary, sorted
print(vectorizer.transform(["the pizza was late and late again"]).toarray()) # one row of counts
cold = vectorizer.vocabulary_["cold"] # the column for "cold"
print(nb.class_count_) # notes per class: [120. 30.]
print(nb.feature_count_[:, cold]) # times "cold" appears in each class's notes
print(np.exp(nb.feature_log_prob_[:, cold]).round(4)) # smoothed P("cold" | class)
print(np.exp(nb.class_log_prior_).round(2)) # P(class): [0.8 0.2]['again' 'burnt' 'cold' 'crispy' 'fast' 'friendly' 'great' 'hot' 'late'
'missing' 'order' 'pizza' 'slow' 'soggy' 'tasty' 'thanks' 'the' 'very'
'was' 'wrong']
[[1 0 0 0 0 0 0 0 2 0 0 1 0 0 0 0 1 0 1 0]]
[120. 30.]
[ 7. 15.]
[0.0208 0.1311]
[0.8 0.2]get_feature_names_out()is the vocabulary, in alphabetical order. Each note becomes one row of 20 counts. "and" isn't in the vocabulary, so it is dropped.feature_count_holds the word counts per class, andfeature_log_prob_the smoothed log-probabilities. Entry 0 is "not a complaint", entry 1 "complaint".class_log_prior_holds the log of the prior, 0.8 and 0.2.
And the zero-count problem, on all 200 notes:
for alpha in [0.0, 1.0]: # no smoothing, then add-one (Laplace) smoothing; trained on all 200 notes
with np.errstate(divide="ignore", invalid="ignore"): # log(0) = −inf is the point here
nb_all = make_pipeline(CountVectorizer(), MultinomialNB(alpha=alpha)).fit(texts, y)
print(alpha, nb_all.predict_proba(NEW_NOTES[:2]).round(3).tolist())
# alpha=0: "cold late thanks" gets P(complaint) = 0, and "burnt cold thanks" gets nan (∞ − ∞)
# alpha=1: 0.539 and 0.8660.0 [[1.0, 0.0], [nan, nan]]
1.0 [[0.461, 0.539], [0.134, 0.866]]With alpha=0.0, "cold late thanks" is certain not to be a complaint. "burnt cold thanks" comes out as nan (not a number), from . scikit-learn also warns about dividing by zero inside a log. The code hides that warning, since here it's the point.
Generative and discriminative models
Naive Bayes and logistic regression both output P(complaint | words). They get there in different ways.
- Naive Bayes learns how each class produces notes: P(complaint), and P(word | class) for every word. Then it turns that around with Bayes' rule. A model of how the data are produced, class by class, is a generative model. You could even use it to write new fake notes, by drawing words from a class's bag.
- Logistic regression learns P(complaint | words) directly. It never says how likely a note is to begin with. A model of the class given the features, and nothing else, is a discriminative model.
The two are closer than they look. Naive Bayes' score is the prior's log-odds plus a number per word, times how often the word appears. That's a weighted sum of the word counts plus a constant: a linear model, like logistic regression's.
The difference is how the weights are chosen. Naive Bayes reads them off from counts, one word at a time. Logistic regression fits them together by gradient descent, so it can take account of words that tend to appear together.
DigressionWhich one wins as the data grow?Naive Bayes learns fast from few examples; logistic regression often catches up. · 2 min
A well-known study by Andrew Ng and Michael Jordan (2001) compared the two on many datasets. Naive Bayes usually reached its best accuracy with fewer examples. Logistic regression usually needed more data, but often ended up better, because it isn't tied to the independence assumption.
On the complaint notes, averaged over 50 random splits (each tested on 50 notes):
| Training notes | Naive Bayes | Logistic regression |
|---|---|---|
| 10 | 89.5% | 81.5% |
| 20 | 95.3% | 87.8% |
| 50 | 98.7% | 94.2% |
| 100 | 99.1% | 95.9% |
| 150 | 99.1% | 96.7% |
Naive Bayes stays ahead here, even at 150 notes. That's no surprise: these made-up notes were generated almost exactly the way naive Bayes assumes, each word drawn from its class's bag. On real text, where words depend on each other, logistic regression often overtakes it once there are thousands of examples. The general rule of thumb: try naive Bayes when labels are scarce, and check against logistic regression when you have more.
DeeperWhy naive Bayes classifies well even when its probabilities are wrongCounting the same evidence twice makes it overconfident, but rarely changes which side wins. · 2 min
Suppose complaints that say "late" nearly always say "slow" too. Then the two words carry one piece of evidence between them. Naive Bayes adds both bars anyway: "late" (+2.35) and "slow" (+3.37 in the full model). It counts the evidence twice.
That pushes the score further from 0 than it should be. So naive Bayes' probabilities tend to be too extreme: it says 0.99 where the truth might be 0.9. In the language of calibration, it's overconfident.
But the decision only depends on the score's sign. Double-counting usually makes a right answer more extreme, not wrong. So naive Bayes can rank and classify notes well while its probabilities shouldn't be taken at face value. If you need trustworthy probabilities, for example to decide how many calls to make, calibrate them on held-back data first.
DigressionNumbers instead of words: Gaussian naive BayesOne bell curve per feature and class, for tables of numbers. · 2 min
Naive Bayes works for numeric features too. Instead of word counts, give each feature a normal distribution in each class, fitted by maximum likelihood: the class's mean and spread for that feature. Then multiply the densities, as before, pretending the features are independent within a class.
Here it predicts late deliveries from distance, traffic and rain:
deliveries = pd.DataFrame(load("deliveries")["rows"])
X = deliveries[["distance_km", "traffic", "rain"]].to_numpy() # (300, 3)
late = deliveries["late"].to_numpy() # 1 = over 30 minutes
X_train, X_test, late_train, late_test = train_test_split(X, late, test_size=0.25, stratify=late, random_state=0)
gnb = GaussianNB().fit(X_train, late_train) # one normal per feature and class
print(gnb.theta_.round(2)) # each class's mean distance, traffic and rain
print(gnb.score(X_test, late_test)) # 0.79
print(LogisticRegression().fit(X_train, late_train).score(X_test, late_test)) # 0.81[[2.33 0.93 0.24]
[3.94 2.29 0.41]]
0.7866666666666666
0.8133333333333334Late deliveries average 3.9 km against 2.3 km, and heavier traffic. Gaussian naive Bayes gets 79% of the test deliveries right, logistic regression 81%. Rain is a yes/no column, so a bell curve is a rough model of it. Naive Bayes is quick to fit, but on numeric tables other models usually do better.
Putting it together
Here is the whole method on one new note, "burnt cold thanks", with all 200 notes and α = 1:
- Bag of words: burnt 1, cold 1, thanks 1; the other 17 words 0.
- Prior: 40 complaints of 200, log-odds .
- Word probabilities: count each word in each class's notes, add 1, and divide by the class's word total plus 20.
- Evidence: "burnt" , "cold" , "thanks" .
- Score: .
- Decision: . Flag it as a complaint, and call the customer.
Without smoothing, step 4 would hit and and give no answer at all.
Common misconceptions
"Naive Bayes needs the words to be independent." It assumes they are independent within each class, and that's usually false. It often classifies well anyway, because double-counted evidence tends to make right answers more extreme rather than wrong.
"If a word never appeared in a complaint, a complaint can't contain it." The count is 0 because 135 words is a small sample. Without smoothing, that one word forces P(complaint) to exactly 0. Smoothing gives every word a small chance in every class.
"P(word | complaint) is the share of complaints that contain the word." In the multinomial model it's a share of complaint words. For "cold" that's 20 of 135, not 20 of 40.
"Naive Bayes' probabilities are reliable." Its decisions often are; its probabilities tend to be too close to 0 and 1. Check calibration before using them as real chances.
"Generative and discriminative models give different kinds of answer." Both output P(class | features). They differ in what they learn on the way: how each class produces data, or only the boundary between classes.
Recap
- Bayes' rule turns P(word | class) and P(class) into P(class | word). One "cold" makes a complaint about 0.71 likely.
- A bag of words describes a text by its word counts, ignoring order.
- Naive Bayes assumes the words are conditionally independent given the class, so the chance of a bag is a product of per-word chances.
- In log-odds, naive Bayes is a running score: the prior plus one bar per word. The sign decides the class.
- Counting word shares is maximum likelihood. A zero count makes a probability exactly 0 and wipes out the note; Laplace smoothing adds a pretend count to every word, a MAP estimate.
- Naive Bayes is a generative model; logistic regression is a discriminative one. Naive Bayes learns from little data; logistic regression often wins with more.
- scikit-learn names in this lesson:
CountVectorizer(.get_feature_names_out,.vocabulary_),MultinomialNB(alpha,.feature_count_,.feature_log_prob_,.class_log_prior_),GaussianNB,make_pipelineandtrain_test_split.