Machine Learning Foundations · Chapter 5 · ~15 min · Intermediate
Naive Bayes & Probabilistic Text Classification
Unpack the mathematics of Bayes' Theorem for natural language processing. Learn how the conditional independence assumption enables lightning-fast email spam filtering, and solve the zero-frequency trap with Laplace smoothing.
- Formulate Bayes' Theorem P(A|B) = P(B|A)P(A) / P(B) for document classification
- Understand why the conditional independence assumption is 'Naive' yet effective
- Eliminate the zero-frequency annihilation bug using Laplace additive smoothing
- Prevent numerical float underflow by computing probabilities in log-space
Naive Bayes & Probabilistic Text Classification: learn it visually
Unpack the mathematics of Bayes' Theorem for natural language processing. Learn how the conditional independence assumption enables lightning-fast email spam filtering, and solve the zero-frequency trap with Laplace smoothing.
1Bayes' Theorem: Inverting Conditional Probabilities
In machine learning, we often observe clues (such as words in an email) and want to calculate the probability of a hidden hypothesis (such as whether the email is Spam or Ham).
Posterior = (Likelihood · Prior) / Evidence
Because the denominator P(Document) is identical for all classes, we only need to maximize the numerator: P(Class) · P(Document | Class)!
Wrong idea: Multiplying raw maximum-likelihood frequency counts
If the word 'cryptocurrency' never appeared in your 10,000 legitimate emails, P('cryptocurrency'|Ham) = 0. Multiplying this zeros out the entire probability!
Real system: Laplace smoothing (+1 pseudo-count additive adjustment)
Adding 1 to every word count and |V| to the denominator ensures every possible word has a tiny non-zero probability, preserving overall evidence.
When using Naive Bayes to classify a document as Spam vs Ham, why can we safely ignore the denominator P(Document)?
2The 'Naive' Independence Assumption
A single email might contain 500 words. Computing the exact joint probability of 500 co-occurring words P(w_1, w_2, ..., w_500 | Spam) would require observing every conceivable combination of words in history!
To make computation feasible, Naive Bayes makes a radical assumption: every word is conditionally independent of every other word given the class:
While grammatically false (words like "credit" and "card" frequently co-occur), this simplification turns an intractable calculation into a series of fast, independent lookups!
Why is the Naive Bayes algorithm called 'Naive'?
3Laplace Smoothing & The Log-Space Defense
Naive Bayes faces two fatal engineering traps when deployed in production:
If an unseen word occurs in a new email, its training count is 0. Multiplying ... × 0.0 × ... destroys all other evidence! Solution: Laplace (+1) Smoothing adds 1 to all word counts.
Multiplying hundreds of small fractions (0.0002 × 0.0005 × ...) underflows float64 hardware registers to 0.0. Solution: Sum in Log-Space: log(A · B) = log A + log B.
4Hands-On: Test the Live Email Spam Filter
Select words below to craft test emails. Notice how turning off Laplace Smoothing causes words with zero counts to instantly annihilate the probability product:
Live Naive Bayes Spam Classifier (Bag-of-Words & Laplace)
5Bug Hunt: Fix Broken Naive Bayes Classifier
A spam classifier in a production email gateway is throwing silent errors: whenever an incoming message contains a novel keyword, the model outputs equal zeros (0.0 vs 0.0) and misroutes important executive communication.
Add Laplace smoothing and convert the multiplication loop to log-space summation:
🎯 Find and fix the bugs in the code above, then press Run & verify to test your solution.
Need a hint?
- Add Laplace smoothing:
p_word_spam = (word_counts_spam.get(word, 0) + 1) / (total_spam + vocab_size). - Accumulate in log space: initialize
log_spam = np.log(prior_spam)and addlog_spam += np.log(p_word_spam). - Compare accumulated log sums:
return 'Spam' if log_spam > log_ham else 'Ham'.
6Chapter Knowledge Challenge
Check your mastery of probabilistic text classification, priors, and Laplace smoothing:
What is the primary mathematical reason for operating in log-space (log P) instead of multiplying raw probabilities in Naive Bayes?
In Laplace smoothing P(w|C) = (count + 1) / (N + |V|), why do we add the vocabulary size |V| to the denominator?
7Recap
- Bayes' Theorem inverts conditional probabilities:
P(C|X) ∝ P(C) · ∏ P(x_i | C). - The Conditional Independence Assumption simplifies multi-word joint probability distributions into independent multiplications.
- Laplace (+1) Smoothing prevents zero-frequency multiplication from zeroing out the entire posterior score on unseen words.
- Log-Space Summation turns fragile probability multiplications into robust floating-point additions.
Ready for Chapter 6? Mark this chapter as complete to proceed: