Naive Bayes
After this lesson, you will be able to:
- Understand the 'naive' assumption — pretend features are independent *given the class* — and why this shortcut works surprisingly well even though it is technically wrong
- Build the Naive Bayes formula step by step from Bayes' theorem and handle the 'never-seen-this-word-before' problem with Laplace smoothing
- Know the three flavors of Naive Bayes (Gaussian, Multinomial, Bernoulli) and pick the right one for numbers vs. word counts vs. yes/no features
- Explain why multiplying many small probabilities causes underflow and how log space solves it
- Recognize when Naive Bayes outperforms more complex models — specifically in high-dimensional, low-data text classification scenarios
Before you start
Don't worry if the math looks intense — Naive Bayes is really just multiplying a bunch of simple probabilities together and picking the biggest answer. Once you see it work on a spam filter example, it will click!
#From Bayes' Theorem to a Classifier
We want to classify a document d (with features x1, x2, ..., xn) into one of several classes (like spam or ham). By Bayes' theorem:
#The Naive Assumption
Computing P(x1, x2, ..., xn | c) exactly requires knowing the joint distribution of all features given the class — exponentially many parameters. With 10,000 vocabulary words, you would need to estimate 2^10000 probabilities. Impossible.
So the full Naive Bayes classifier is:
The rule above multiplies many small probabilities. Open the derivation to see how it follows from Bayes' theorem (derived in Probability & Bayes' Theorem), why the denominator can be dropped, and why taking logs turns the product into a sum that picks the same winner.
Try it! Open the Python REPL and type these lines yourself. Build a one-line spam classifier:from sklearn.naive_bayes import MultinomialNB; from sklearn.feature_extraction.text import CountVectorizer; v = CountVectorizer(); X = v.fit_transform(["free money now","meeting tomorrow","win prize","project update"]); y = [1,0,1,0]; m = MultinomialNB().fit(X,y); print(m.predict(v.transform(["free prize"])))— it predicts spam!
#Quick Spam Classifier Demo
Tests: Verify 'free money click now' is classified as SPAM. Verify 'project meeting tomorrow' is classified as HAM.
#Spam Filter Walkthrough
Let us build a spam classifier from scratch using real word frequencies.
| Word | P(word | spam) | P(word | ham) |
|---|---|---|
| free | 0.60 | 0.05 |
| winner | 0.40 | 0.01 |
| click | 0.50 | 0.08 |
| meeting | 0.02 | 0.30 |
| now | 0.45 | 0.15 |
Priors: P(spam) = 400/1000 = 0.40, P(ham) = 600/1000 = 0.60.
An email contains 'FREE WINNER CLICK NOW'. Spam or not?
#Step 1: Compute the Spam Score
P(spam) x P(free|spam) x P(winner|spam) x P(click|spam) x P(now|spam)
= 0.40 x 0.60 x 0.40 x 0.50 x 0.45
#Step 2: Compute the Ham Score
P(ham) x P(free|ham) x P(winner|ham) x P(click|ham) x P(now|ham)
= 0.60 x 0.05 x 0.01 x 0.08 x 0.15
#Step 3: Classify
Spam score: 0.0216 Ham score: 0.0000036
Every word in this email is strong evidence for spam. The combined effect is devastating.
Naive Bayes is overconfident when features are correlated. The derivation shows the mechanism in its cleanest case, a feature that is simply copied: every copy is counted as fresh evidence.
#Laplace Smoothing: The Zero-Frequency Problem
What happens if the word "cryptocurrency" appears in a test email but was never seen in the training spam? P(cryptocurrency | spam) = 0, and since we multiply all probabilities, the entire product becomes zero — regardless of all other evidence. One unseen word kills the classifier.
With alpha = 1 (add-one smoothing), a word that never appeared in spam gets a probability of 1/(total_spam_words + vocab_size) instead of 0. This is a crucial practical detail — without smoothing, Naive Bayes breaks on any email containing new words.
Where does that exact fraction come from? It is the average of the word's probability after combining a flat prior with the counts. The two-outcome version, a Beta prior updated by counts, appears in MLE, MAP & Fisher Information. Open the derivation for the same idea over a vocabulary of many words.
#Three Flavors of Naive Bayes
#Multinomial Naive Bayes
Use for: spam filtering, sentiment analysis, document categorization, news topic classification.
#Bernoulli Naive Bayes
Use for: short text classification, feature presence/absence, binary survey data.
#Gaussian Naive Bayes
Use for: iris flower classification, medical diagnosis with continuous lab values, any continuous feature set.
The count model and the yes/no model look different, but both are linear classifiers once you look at the log-odds. Open the derivation to see where they agree and exactly how they differ: what happens to words that are absent.
Now let's actually run Multinomial Naive Bayes on text. The cell below tokenizes a small set of restaurant reviews, fits the model, and prints the per-word log-probabilities so you can see exactly which words pull toward "positive" versus "negative".
Naive Bayes assumes features are CONDITIONALLY INDEPENDENT given the class. For a spam classifier, what does that assumption claim about the words 'free' and 'click'?
#Interactive: Watch Naive Bayes Classify Data
Interactive Lab
Switch to the Naive Bayes algorithm to see its boundary on the same dataset. Compare with logistic regression — both linear, but driven by very different math under the hood.
#Why Does Naive Bayes Actually Work?
The independence assumption is clearly wrong. "New" and "York" co-occur. "Free" and "click" co-occur in spam. So why does it work?
#The Deeper Reason "Naive" Works
Despite assuming word independence (clearly wrong — "New York" is not independent), Naive Bayes works surprisingly well because it only needs the RANKING of probabilities to be correct, not the exact values. Consider: if the true P(spam|email) is 0.92 and Naive Bayes estimates 0.73, the classification is still correct — spam wins. The probabilities are wrong, but the ordering is right.
This is analogous to a judge ranking contestants. Even if the judge's scores are miscalibrated (giving everyone lower scores than they deserve), as long as the ranking is preserved, the right contestant wins. Naive Bayes is a consistently miscalibrated judge who still usually picks the right winner.
#Try It Yourself
Tests: Verify 'free winner click now' is classified as spam. Verify 'meeting report hello' is classified as ham. Check that probabilities sum to approximately 100%.
On the Optimality of the Simple Bayesian Classifier under Zero-One Loss
Pedro Domingos and Michael Pazzani (1997)
The seminal paper explaining why Naive Bayes works despite the clearly wrong independence assumption. Shows that the classifier only needs to get the ranking right, not the exact probabilities, and that the independence assumption often does not affect the ranking.
#Looking Ahead: Discriminant Analysis
P(X | y) · P(y) and apply Bayes' rule to recover P(y | X). They only differ in what they assume about P(X | y). Gaussian Naive Bayes assumes per-class Gaussians with diagonal covariance (features conditionally independent). Drop that diagonal restriction and you get Linear Discriminant Analysis (LDA) — same shared covariance across classes, but full matrices. Let each class wear its own covariance and you get Quadratic Discriminant Analysis (QDA). These are the next lesson — a discriminative-looking cousin family of Gaussian Naive Bayes, with linear vs. quadratic boundaries falling out of one assumption. See Linear & Quadratic Discriminant AnalysisLinear Discriminant AnalysisClassify with one shared covariance per class, giving a straight boundary; also a supervised projection to at most C-1 directions.Learn more for the full story, including Fisher's 1936 criterion for supervised dimensionality reduction.#When to Use Naive Bayes vs. Alternatives
| Situation | Reach for | Why |
|---|---|---|
| Text classification with word counts (spam, sentiment, topic) | Multinomial Naive Bayes | Default workhorse; trains in milliseconds on millions of docs |
| Binary feature vectors (presence/absence) | Bernoulli Naive Bayes | Treats "absence" as informative evidence |
| Continuous features, classes roughly Gaussian | Gaussian NB (or LDA — see next lesson) | NB's diagonal-Σ assumption is cheap; LDA captures within-class correlations |
| Continuous features, many correlated, > 100 features | Logistic regression + L2 | NB double-counts correlated evidence and gets overconfident |
| You need probability calibration for downstream decisions | Logistic regression (or calibrate NB with Platt scaling) | NB probabilities are notoriously over-confident |
| Tabular data with mixed types and rich interactions | Gradient Boosting (LightGBM/XGBoost) | Captures interactions NB cannot model by assumption |
#Key Takeaways
- Naive Bayes is Bayes' theorem with a strong independence shortcut — it classifies by computing P(class) times the product of P(feature|class) for each feature, picking the class with the highest score
- The 'naive' assumption is wrong but works — features are rarely independent, but the classifier only needs correct ranking (which class scores highest), not exact probabilities; this makes it a surprisingly strong baseline
- Laplace smoothing prevents zero probabilities — adding a small count (alpha) to every feature ensures that one unseen word does not zero out the entire probability; without it, Naive Bayes breaks on new vocabulary
- Three variants for different data types — Multinomial NB for word counts (text), Bernoulli NB for binary features, Gaussian NB for continuous features; Multinomial NB is the workhorse of text classification
- Log probabilities prevent underflow — always work in log space when implementing Naive Bayes to avoid multiplying many tiny numbers into zero
#Quick Check
Why is it called 'Naive' Bayes?