Naive Bayes for text classification
Naive Bayes is a fast probabilistic classifier for text that uses Bayes' theorem plus a strong conditional-independence assumption to score classes from word counts or word presence.
Drafted with Aria, reviewed by the AiCanCode.org team · Updated . How we write and check our notes. Spotted an error? Use Give Feedback at the bottom of the page.
Why it matters
Naive Bayes for text classification is used by engineers to build fast, simple spam filters, document-topic classifiers, sentiment detectors and startup prototypes where training speed, small data and interpretability matter. It gives good baseline performance and is easy to implement and explain.
Key ideas
Prior (defined): P(c) is the probability of class c before seeing the document (estimated by relative frequency in training data). Assumption: training set is representative so empirical frequency approximates prior.
Likelihood (defined): P(x | c) is the probability of observing features x when the true class is c. Naive Bayes defines a simple likelihood model for textual data (see below).
Posterior (defined): P(c | x) is the probability of class c given features x, obtained from Bayes' theorem.
Naive (conditional independence) assumption (defined): given the class, the features (words or word counts) are assumed independent. That is, if x = (x1, x2, ..., xN) then P(x | c) = Π_i P(xi | c). This is rarely strictly true for language, but often produces good classifiers.
Bag-of-words model (defined): text is represented by word counts (or binary indicators of presence) ignoring word order. For multinomial Naive Bayes the representation is counts; for Bernoulli Naive Bayes it is binary presence/absence.
Multinomial Naive Bayes model (defined): for class c, the probability of a document (seen as sequence or bag of word tokens) with token counts n_w is P(document | c) ∝ Π_w P(w | c)^{n_w}. Here P(w | c) is the probability of generating token w in class c. Assumptions: (1) word draws are independent given class; (2) vocabulary V is fixed; (3) token counts are modelled by multinomial distribution.
Lidstone (add-α) smoothing (Laplace when α = 1) (defined): to avoid zero likelihoods when a word did not appear in training for a class, replace raw frequency with (count + α) and normalize by (total tokens in class + α·V). Typical α = 1 (add-one smoothing) or small values like 0.1. Assumes smoothing mass α·V distributed equally across the fixed vocabulary.
Decision rule (defined): choose class c that maximizes posterior P(c | document). Since denominator P(document) is same for all classes, equivalent to maximize P(c)·P(document | c). Using independence gives argmax_c P(c)·Π_w P(w | c)^{n_w}.
Log-space computation: to avoid underflow and speed multiplication, compute log-scores: log P(c) + Σ_w n_w · log P(w | c) and select class with maximum log-score.
Variants: Bernoulli Naive Bayes uses binary features (word present or not) and models both P(feature present | c) and P(feature absent | c). Gaussian Naive Bayes is for continuous numeric features (not typical for raw text). Complement Naive Bayes (CNB) is a variant that often performs better on imbalanced text by estimating each class using statistics from all other classes.
Where an exam wants a diagram, draw two columns labelled classes (c1, c2) and a box for vocabulary V with arrows to class likelihoods; draw a document as bag-of-words and show multiplication of likelihoods into posterior. Label prior, likelihood, posterior on Bayes formula.
Formulas
P(c | x) = P(x | c) · P(c) / P(x) — Bayes' theorem. Symbols: c = class label (unitless), x = observed features (unitless). Applies always for probabilities.
P(document | c) ∝ Π_{w∈V} P(w | c)^{n_w} — Multinomial likelihood up to a document-dependent constant N_doc! / Π_w n_w! that cancels across classes. n_w = token count of word w in the document (unitless). Assumes bag-of-words and conditional independence.
choose c* = argmax_c P(c) · Π_{w} P(w | c)^{n_w} — classification decision rule. All probabilities unitless.
log-score(c) = log P(c) + Σ_{w} n_w · log P(w | c) — numerically stable score. Units: natural log of probability (unitless).
P(w | c) = (count(w, c) + α) / (N_c + α·V) — Laplace (add-α) smoothed word probability. count(w, c) = number of tokens w in class c in training (unitless). N_c = total number of word tokens in class c in training (unitless). V = vocabulary size (unitless). α ≥ 0 is smoothing parameter (unitless). Applies to multinomial Naive Bayes.
P(c) = N_c_docs / N_docs_total — empirical class prior estimated from training set. N_c_docs = #training docs in class c.
Python / scikit-learn syntax to remember:
from sklearn.feature_extraction.text import CountVectorizer; X = CountVectorizer().fit_transform(docs)from sklearn.naive_bayes import MultinomialNB; clf = MultinomialNB(alpha=1.0); clf.fit(X, y)clf.predict(X_test),clf.predict_proba(X_test)
Worked examples
Example 1 — hand calculation (multinomial + add-one smoothing). Show step-by-step as in an exam.
Training data (4 documents):
- "win offer" — spam
- "win" — spam
- "hello" — ham
- "hello offer" — ham
Vocabulary V = {win, offer, hello}, so V = 3. Class counts:
- spam docs = 2, ham docs = 2 ⇒ P(spam) = 2/4 = 0.5, P(ham) = 0.5.
- spam token counts: win=2, offer=1, hello=0 ⇒ N_spam = 3.
- ham token counts: hello=2, offer=1, win=0 ⇒ N_ham = 3.
Use add-one smoothing (α = 1). Compute P(w | c):
P(win | spam) = (2+1)/(3 + 1·3) = 3/6 = 1/2.
P(offer | spam) = (1+1)/6 = 2/6 = 1/3.
P(hello | spam) = (0+1)/6 = 1/6.
P(win | ham) = (0+1)/6 = 1/6.
P(offer | ham) = (1+1)/6 = 2/6 = 1/3.
P(hello | ham) = (2+1)/6 = 3/6 = 1/2.
Classify test document "win offer" (bag counts win:1, offer:1):
- Score(spam) = P(spam) · P(win|spam) · P(offer|spam) = 1/2 · 1/2 · 1/3 = 1/12 ≈ 0.08333.
- Score(ham) = 1/2 · 1/6 · 1/3 = 1/36 ≈ 0.02778.
Since 1/12 > 1/36, classify as spam. Posterior (normalized): spam = (1/12)/(1/12+1/36) = 3/4 = 0.75; ham = 0.25.
Example 2 — runnable Python program using scikit-learn
Code:
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.naive_bayes import MultinomialNB
train_docs = ["win offer", "win", "hello", "hello offer"]
y = ["spam", "spam", "ham", "ham"]
vectorizer = CountVectorizer()
X = vectorizer.fit_transform(train_docs)
clf = MultinomialNB(alpha=1.0)
clf.fit(X, y)
test_docs = ["win offer", "hello", "offer"]
X_test = vectorizer.transform(test_docs)
pred = clf.predict(X_test)
proba = clf.predict_proba(X_test)
print("classes_:", clf.classes_)
print("predictions:", list(pred))
print("predict_proba:\n", proba)
Sample input: the script above; no interactive input.
Exact output (expected):
classes_: ['ham' 'spam'] predictions: ['spam', 'ham', 'ham'] predict_proba: [[0.25 0.75] [0.75 0.25] [0.5 0.5 ]]
Explanation: class order is alphabetical by label in scikit-learn's classes_. The probabilities match the hand calculation for the same tokenizer and smoothing; the third document "offer" is tied between classes and the classifier predicts the class that appears first in classes_ when probabilities are equal.
(If you run this locally, confirm your scikit-learn version; small formatting differences in numpy printing may appear.)
Common mistakes
- Confusing multinomial (counts) and Bernoulli (binary presence) models — they give different likelihoods and need different feature representations.
- Using TF-IDF counts without care: MultinomialNB expects counts but can work with TF-IDF; interpret probabilities carefully.
- Not fixing vocabulary between training and test; unknown words at test time are ignored (counts zero) unless you include an explicit OOV/UNK token during vectorization — smoothing does not create probabilities for tokens outside the fixed vocabulary.
- Computing denominator in smoothed P(w|c) incorrectly — it is N_c + α·V, not N_c + α.
- Assuming Naive Bayes requires independent words in reality — it doesn't, but it assumes conditional independence for the model.
For your exam
Possible question types:
- Definitions: define Bayes' theorem, prior, likelihood, posterior, Naive Bayes classifier, bag-of-words.
- Short notes: explain multinomial Naive Bayes vs Bernoulli Naive Bayes; role of smoothing; log-space computation.
- Derivations: derive the Naive Bayes decision rule from Bayes' theorem and the conditional-independence assumption; derive smoothed estimator for P(w|c).
- Numericals: given small training set, compute priors, smoothed likelihoods, posterior scores and final class (show steps and arithmetic).
- Programs: implement training and prediction using CountVectorizer and MultinomialNB in Python; show predicted labels and probabilities.
- Diagrams: draw bag-of-words document -> likelihoods per word -> multiply -> combine with prior -> posterior.
What a full-marks answer includes:
- Clear definitions of prior, likelihood and posterior.
- Statement of conditional-independence (naive) assumption and where it is used.
- Correct derivation from Bayes' theorem to argmax rule.
- Correct smoothing formula and explanation why smoothing is needed.
- For numericals: show counts, N_c, V, apply smoothing with arithmetic, compute scores (or log-scores) and final normalized posterior.
- For code: working code using CountVectorizer + MultinomialNB and interpretation of outputs.
Quick check
- Why do we take log of probabilities in Naive Bayes?
- Give the smoothed formula for P(w | c) with add-one smoothing.
- What is the main independence assumption of Naive Bayes for text?
Answers: 1) To convert products into sums to avoid numeric underflow and for computational stability. 2) P(w|c) = (count(w,c) + 1) / (N_c + V). 3) Given the class, word occurrences (or word draws) are conditionally independent of each other (the conditional-independence assumption).
Finished this topic? Mark it so your progress, study plan and readiness keep up.
Stuck on something here?