Naive Bayes
朴素贝叶斯
Build a text classifier from explicit event models and distinguish smoothing, conditional independence and probability calibration.
naive-bayesA few word counts can make a useful first classifier
Consider four invented messages. Label offer offer now and offer free as promo, and meeting now and meeting agenda as work. A new message says offer offer. Counting training occurrences suggests promo, but how can we turn those counts into a reproducible classification rule?
Naive Bayes gives each class a prior weight, then accumulates evidence from individual features under a deliberately simple model. In the implementation below, the two classes have equal prior probability. After smoothing, the probability of an offer token is under promo and under work. Two occurrences produce a likelihood ratio of and a normalized promo score of , about 0.9297. That last number is conditional on fitted model parameters, not a measured guarantee that 92.97% of such predictions will be correct.
The assumption is conditional independence
Let be a class and a feature vector. For observations with positive evidence, Bayes’ rule gives
The naive assumption replaces a complicated joint distribution with a product:
This is mutual independence conditional on the class, not independence before knowing the class. Merely requiring every pair of features to be conditionally independent is insufficient for a product involving three or more features. With continuous features, the factors can be densities rather than probability masses. Gaussian naive Bayes, for example, uses a separate one-dimensional Gaussian density for each feature and class, with positive variances. These variants differ in their observation models, not in Bayes’ rule. scikit-learn’s naive Bayes guide states the factorization and Gaussian model.
Text requires care about what the features represent. A multinomial model generates a token independently at each position given the class and fitted token probabilities . All positions share those probabilities. If a length- document has token counts , its count probability is
The count coordinates themselves are not independent: their total is fixed. Independent token positions lead to the multinomial count law. For one observed count vector, the factorial coefficient is the same across classes and cancels during classification. Word order disappears, but repeated occurrences remain. Introduction to Information Retrieval, Section 13.4 distinguishes these random objects explicitly.
Our teaching model conditions on and uses the same class prior for every length. Equivalently, a complete generation model could make length independent of class. If length has a class-dependent distribution, include when classifying a document instead of silently discarding it. The textbook notes that token generation alone does not specify a distribution over arbitrary document lengths.
Let be the number of training documents in class , their total, the number of occurrences of token in that class, and . We use empirical class priors and additive smoothing:
Smoothing prevents an unobserved word–class combination from receiving probability zero. The token formula is the posterior mean under a symmetric Dirichlet() prior. It is not generally the posterior mode under that same prior. Conventional multinomial NB then plugs this vector into its token model; it does not integrate the entire vector out for each future document. The practical zero-frequency issue and additive estimate are discussed in IR, Section 13.2.
Our vocabulary has five observed words plus one explicit unknown-token bucket, making . With , promo has , work has , and offer occurs three and zero times respectively. Thus and . Both class priors are . Multiplying two token factors and normalizing gives the opening result.
A Bernoulli text model instead represents every vocabulary term by a presence indicator . It uses
Here is the probability that a class- document contains the word at least once. Repeated occurrences do not change the indicator, but absence contributes through . If smoothed symmetrically, its denominator is , using document counts and the two presence states. That differs from the multinomial denominator. IR’s Bernoulli-model section explains the two event models.
Fit a vocabulary once, then score in log space
The complete standard-library program implements multinomial NB. It accepts already segmented token sequences, including Chinese tokens if supplied by the caller; it is not a natural-language tokenizer. Class labels and tokens must be nonempty strings. Training must contain at least one document, but individual documents can be empty. Only classes observed in training can be predicted.
The internal key None represents every unknown token and cannot collide with a valid string token. Predicting does not expand the vocabulary. Parameters are exact fractions; log scores and normalized outputs are floating-point approximations. Subtracting the maximum score before exponentiating ensures that at least one relative weight is one.
from collections import Counter
from fractions import Fraction as F
import math
def valid_tokens(tokens):
if isinstance(tokens,(str,bytes)):
raise ValueError("supply a token sequence, not an unsegmented string")
tokens=tuple(tokens)
if any(not isinstance(t,str) or not t for t in tokens):
raise ValueError('tokens must be nonempty strings')
return tokens
def fit_multinomial(documents, labels, alpha=1):
docs=[valid_tokens(d) for d in documents]
labels=tuple(labels)
if not docs or len(docs)!=len(labels) or any(not isinstance(c,str) or not c for c in labels):
raise ValueError('matching nonempty training data and string labels required')
if type(alpha) is not int and not isinstance(alpha,F):
raise ValueError('integer or Fraction smoothing required')
alpha=F(alpha)
if alpha<=0:raise ValueError('positive smoothing required')
classes=tuple(sorted(set(labels)))
known={t for d in docs for t in d}
vocabulary=(None,*sorted(known))
class_counts=Counter(labels)
token_counts={c:Counter() for c in classes}
for doc,c in zip(docs,labels):token_counts[c].update(doc)
probability={}
for c in classes:
denominator=sum(token_counts[c].values())+alpha*len(vocabulary)
probability[c]={t:(token_counts[c][t]+alpha)/denominator for t in vocabulary}
priors={c:F(class_counts[c],len(docs)) for c in classes}
return classes,known,probability,priors
def predict_multinomial(model,tokens):
classes,known,probability,priors=model
counts=Counter(t if t in known else None for t in valid_tokens(tokens))
order=sorted(counts,key=lambda t:'' if t is None else t)
logq=lambda p:math.log(p.numerator)-math.log(p.denominator)
scores={c:logq(priors[c])+math.fsum(counts[t]*logq(probability[c][t]) for t in order)
for c in classes}
maximum=max(scores.values())
relative={c:math.exp(scores[c]-maximum) for c in classes}
total=math.fsum(relative.values())
posterior={c:relative[c]/total for c in classes}
# First in sorted class order breaks an exact tie in computed scores.
winner=max(classes,key=lambda c:scores[c])
return winner,posterior
model=fit_multinomial([d.split() for d in ['offer offer now','offer free','meeting now','meeting agenda']],
['promo','promo','work','work'])
assert model[2]['promo']['offer']==F(4,11)
assert model[2]['work']['offer']==F(1,10)
assert math.isclose(predict_multinomial(model,['offer','offer'])[1]['promo'],float(F(1600,1721)))
assert predict_multinomial(model,[])[1]=={'promo':.5,'work':.5}
assert 'novel' not in model[1]
predict_multinomial(model,['novel'])
assert 'novel' not in model[1]
Let be the number of training documents, their total token count, the number of classes, and the vocabulary size including the unknown bucket. Counting and filling the probability table takes operations. This implementation also sorts vocabulary and class names, adding comparisons. Peak training storage is because documents are copied; the resulting model stores parameters.
For a query with tokens mapping to distinct buckets, counting costs , sorting the buckets costs , and scoring plus normalization costs , including the empty query. These bounds treat dictionary access and arithmetic as unit operations; fraction and string costs depend on their lengths. The logarithm is evaluated from integer numerator and denominator to avoid first rounding a tiny positive fraction to zero, but floating-point rounding remains. Extremely small normalized class probabilities may still underflow. An exact tie in computed scores chooses the first sorted class label.
Smoothing cannot make duplicated evidence independent
Take two equally likely classes and a binary signal with and . Now create two features by copying it: . The true posterior after seeing is . Incorrectly treating the copies as independent gives
The class decision stays the same, but the probability becomes too extreme. This is one explicit failure model, not a claim that every naive Bayes classifier is always overconfident. IR, Table 13.4 and discussion separates classification quality from probability estimation. Smoothing addresses zero frequencies; calibration assesses whether numerical probabilities match observed frequencies on suitable evaluation data. Neither automatically fixes a wrong dependence model.
Word order can carry meaning that a bag of words discards. Different negation patterns may share similar counts. Changing tokenization, vocabulary filtering, or the unknown-word policy changes the model too. Learn vocabulary and any feature-selection rules using training data only; choose smoothing and any calibration method using appropriate validation data, then reserve separate data for evaluation. For class imbalance, inspect class-specific errors and decision costs rather than accuracy alone.
TF–IDF vectors can be useful engineering inputs to implementations accepting nonnegative features, but they are not literal integer multinomial counts. State that change in interpretation. Likewise, classifier probabilities obtained after plugging in estimated parameters do not carry all parameter uncertainty merely because the algorithm’s name contains “Bayes.”
Count the right events
- For the four-message corpus with smoothing one, compute the
promoscore foroffer offer. Answer: the unnormalized weights are and , giving normalized probability under the fitted model. - Must an empty query and a query containing one unknown word produce the same probabilities? Answer: no. The empty query returns the class priors, here one half each. The unknown bucket has probabilities and , so one unknown token gives
promoprobability . The vocabulary remains unchanged. - Duplicate the binary signal in the example above. What are the true and naive posterior probabilities for class 1 after observing both features equal to one? Answer: and . Copying a signal did not create another independent observation.
- Does repeating
offerchange the evidence in both text models? Answer: it changes its count in the multinomial model. In the Bernoulli presence model it remains present once; probabilities for every absent vocabulary word still contribute.
A baseline with assumptions you can inspect
Naive Bayes is useful as a baseline because its sufficient counts, class priors, and per-feature contributions are visible. Compare its errors with a classifier that can learn different feature weights or interactions, while keeping the data split and representation fixed. Compare probability quality separately from label accuracy. Conjugate-prior and posterior-predictive methods explain what parameter integration would add; richer language representations address information that independent token positions cannot preserve.
Make a prediction, then check
Two text features are copies of the same signal. Which problem does additive smoothing automatically address?
Learning objectives
- Derive the class rule from Bayes’ theorem and distinguish full conditional independence from fixed-total multinomial counts.
- Distinguish multinomial token and Bernoulli presence models and compute smoothing, unknown-token handling and stable log scores.
- Use a duplicated-evidence counterexample to explain miscalibration and assess smoothing, accuracy and calibration separately.
Prerequisites & connections
- Bayesian inference
- Independence and conditional independence
- Categorical and multinomial distributions
References
- Introduction to Information Retrieval — Naive Bayes text classification
Christopher D. Manning; Prabhakar Raghavan; Hinrich Schütze · 2008 - Introduction to Information Retrieval — The Bernoulli model
Christopher D. Manning; Prabhakar Raghavan; Hinrich Schütze · 2008 - Introduction to Information Retrieval — Properties of Naive Bayes
Christopher D. Manning; Prabhakar Raghavan; Hinrich Schütze · 2008 - scikit-learn — Naive Bayes
scikit-learn developers
Version1 · Editorial status: Recorded technical checks completed
View technical check record (AI)
Codex · 2026-09-05 · Codex multi-agent technical check: primary-source verification, derivation and numerical assertions, bilingual comparison, and review by another agent or the parent; no independent human peer review.
- Read the IR textbook and sklearn documentation and re-derived conditional factorization, token/count event distinctions, smoothing as a posterior mean and the length convention.
- Enumerated fixed-length token event spaces and aggregated counts; checked log normalization against exact fractions, including 1600/1721 and unknown-token probability 10/21.
- Checked copied signals, the pairwise-independent XOR counterexample, Bernoulli absence factors, unchanged vocabulary, long queries and invalid inputs; matched four bilingual answers, equations, code and anchors.
- Another agent performed read-only review and executed nine tests, additionally integrating the polynomial exactly to obtain fully integrated prediction 25/28, distinct from plug-in posterior-mean prediction 1600/1721; the article distinguishes them correctly.
- The parent executed all 37 independent classical-method checks successfully; bilingual code, display equations, six main anchors and four answered exercises were individually compared.
Source locations checked:
- Introduction to Information Retrieval — Naive Bayes text classification · Section 13.2 full HTML read: equations 113–119, zero-frequency explanation, document prior versus token counts, Table 13.2 and training/test complexity discussion. No textbook example or code copied; four-message corpus and exact ratios independently constructed.
- Introduction to Information Retrieval — The Bernoulli model · Full HTML read, especially lines 4–10: document presence indicators versus token occurrence counts, repeated words and explicit absence factors; lines 13–14 denominator uses class-document count plus two.
- Introduction to Information Retrieval — Properties of Naive Bayes · Section 13.4, equations 121–128 and tables 13.3–13.4, full HTML read. Lines 16–38 distinguish conditional and positional assumptions and missing document-length model; lines 54–64 distinguish classification from probability estimation. Multinomial count coordinates explicitly not called independent.
- scikit-learn — Naive Bayes · Introduction lines 75–94 and Gaussian NB lines 99–104 read. Used full conditional factorization, not the loose pairwise wording. Parameter-specific Gaussian factors stated; relative frequency identified as empirical estimate, not generic MAP; no current implementation performance claim.
Related topics