Naive Bayes Classification

The standard probabilistic text classifier. Bayes' rule applied to documents, the generative story behind the multinomial model, its estimates derived as maximum likelihood with a Lagrange multiplier, add-one smoothing derived as the posterior mean under a uniform Dirichlet prior, what the smoothing constant does, computing in log space, Naive Bayes as a linear classifier, the training and classification procedure with its rule for unseen words, the textbook's worked example carried through every step, cost, results on Reuters-21578, and worked problems from the course text.

Multinomial Naive Bayes assigns a document to the class $c$ that maximizes $\log \hat{P}(c) + \sum_k \log \hat{P}(t_k \mid c)$, assuming its tokens are independent given the class. Its relative-frequency estimates are proved here to be the maximum likelihood estimates, and add-one smoothing, $(T_{ct} + 1)/(\sum_{t'} T_{ct'} + B)$, is derived as the posterior mean under a uniform Dirichlet prior. For two classes the log odds are linear in the term counts, so Naive Bayes is a linear classifier. On the textbook's China/Japan example, smoothing reverses the decision, and the smoothing constant $\alpha$ flips it at 0.573. On the ten largest categories of Reuters-21578 (standard split), add-one smoothing gives micro-F1 0.835 and macro-F1 0.721; $\alpha = 3$, the best micro-F1 on a development split, gives 0.874 and 0.731.

The grain classifier of the text classification problem reads a Reuters story and answers yes or no. It was built from 7,769 labeled training stories in a single pass over the data, and on the test stories it finds 142 of the 149 about grain. This article shows how Bayes' rule turns the word counts of labeled stories into a decision about a new one.

Naive Bayes classifies a document with Bayes' rule, under the assumption that its terms are independent of one another once the class is known. It is derived in a few lines, it handles tens of thousands of features without difficulty, and it is often more accurate than its assumptions would suggest. On the ten largest categories of Reuters-21578, the version built in this article reaches a micro-averaged F1 of 0.835. Its independence assumption is the same one the Binary Independence Model makes.

Here is the route. First we turn Bayes' rule into a classifier that needs a story of how documents are written. Then we estimate the story's parameters, derive the estimates, and see why they must be smoothed. Next we move to log space and find a linear classifier. Then we state the procedure, and finally we test it on Reuters. This article is the home of the multinomial model's estimates and of add-one smoothing as a Bayesian estimate; later articles build on both. Throughout, we follow Manning, Raghavan, and Schütze (2008, §13.2) and carry the textbook's four-document example through every step. The probability primer covers the background.

The running example

Manning, Raghavan, and Schütze (2008, §13.2) use four training documents, three in class China ($c$) and one not ($\bar{c}$, labeled Japan below), and one test document:

Document Text Class
1 Chinese Beijing Chinese China
2 Chinese Chinese Shanghai China
3 Chinese Macao China
4 Tokyo Japan Chinese Japan
test Chinese Chinese Chinese Tokyo Japan ?

The test document is ambiguous on purpose. It mentions Chinese three times, which points to China. But it also contains Tokyo and Japan, which have only ever appeared in the Japan document. Every section below computes something on this China/Japan example. All the numbers come from a script (tools/experiments/reuters/china_japan.py), rounded to three decimals unless stated.

From Bayes' rule to a classifier

What we want is the probability of each class given the document. The probability that document $d$ belongs to class $c$ follows from Bayes' rule:

$$P(c \mid d) = \frac{P(d \mid c)\, P(c)}{P(d)}.$$

To classify, choose the class with the highest posterior probability, the maximum a posteriori (MAP) class. $P(d)$ is the same for every class, so it can be dropped:

$$c_{\text{map}} = \arg\max_{c \in \mathbb{C}} P(d \mid c)\, P(c).$$

$P(c)$, the prior, is how common the class is. $P(d \mid c)$ is the probability of seeing this document if it belongs to class $c$, and estimating it is the difficulty. A document is a sequence of tokens $\langle t_1, t_2, \dots, t_{n_d} \rangle$, and there are far too many possible sequences to estimate their probabilities directly. Even the five-token test document is one of $6^5 = 7{,}776$ sequences over a six-term vocabulary, and the training set contains none of them. A model is needed that assigns a probability to a sequence it has never seen.

The generative story

Naive Bayes supplies that model by imagining how a document of class $c$ might have been written (Manning, Raghavan, and Schütze, 2008, §13.4):

  1. Choose the class $c$, with probability $P(c)$.
  2. Choose a length $n_d$.
  3. For each position $k = 1, \dots, n_d$, draw a term $t_k$ from the class's distribution over the vocabulary, $P(t \mid c)$, independently of every other position.

No one believes documents are written this way. The story is useful because it names exactly what the model must estimate: one prior per class and one distribution over the vocabulary per class. Under it, the probability of a particular document is

$$P(d \mid c) = P(n_d) \prod_{k=1}^{n_d} P(t_k \mid c).$$

The length term $P(n_d)$ is assumed to be the same for every class. Like $P(d)$, it cannot change which class wins, so it is dropped. Two assumptions are packed into step 3:

  • Conditional independence. Given the class, each token tells nothing about any other.
  • Positional independence. The distribution is the same at every position, so word order is irrelevant and the document might as well be a bag of words.

This is the multinomial model. A term occurring three times contributes its probability three times. The name comes from the multinomial distribution. The product above is the probability of the tokens in their given order. The probability of the bag of words, the counts alone, is that product times the number of orderings with those counts, the multinomial coefficient $n_d! / \prod_t \mathrm{tf}_{t,d}!$, where $\mathrm{tf}_{t,d}$ is the number of times term $t$ occurs in $d$. The coefficient depends only on the document. It is the same for every class and, like $P(n_d)$, cannot change which class wins. Under this model the counts are a sufficient statistic for the term probabilities, which is the precise sense in which the bag of words loses nothing (Sufficient Statistics).

Each class's distribution $P(t \mid c)$ is a unigram language model, and the product is the probability that this model generates the document. Classification is therefore the query likelihood comparison of language models for retrieval with the roles exchanged. There, one query was scored under a model for each document. Here, one document is scored under a model for each class (Manning, Raghavan, and Schütze, 2008, §13.2).

The independence assumption is false, since Hong makes Kong far more likely, and word order matters. It is the same assumption the BIM makes, and it is "naive" for the same reason. Lewis (1998) traced the assumption's long history in retrieval and classification, where it has been used since the 1960s. Why the classifier works well anyway is the subject of the Bernoulli model and why Naive Bayes works.

The classifier becomes

$$c_{\text{map}} = \arg\max_{c} \; P(c) \prod_{k=1}^{n_d} P(t_k \mid c).$$

Estimating the parameters

The story leaves one prior per class and one distribution over the vocabulary per class to fill in. Where do their values come from? They are estimated from the training set by relative frequencies:

$$\hat{P}(c) = \frac{N_c}{N}, \qquad \hat{P}(t \mid c) = \frac{T_{ct}}{\sum_{t' \in V} T_{ct'}},$$

where $N_c$ is the number of training documents in class $c$, $N$ the total number of training documents, and $T_{ct}$ the number of occurrences of term $t$ in the training documents of class $c$, counting repeats.

Why relative frequencies

These are the maximum likelihood estimates: the values that make the training data most probable under the generative story. Here is the idea in one sentence. If 5 of a class's 8 training tokens are Chinese, the distribution that makes those tokens most probable gives Chinese probability 5/8: each term gets the share of the tokens it actually had. Maximum Likelihood Estimation treats the method in general.

The formal version. Here is the plan. We write the probability of the whole training set under the generative story, see that it splits into one piece for the priors and one piece for each class's term distribution, and maximize each piece under the constraint that its probabilities sum to 1.

Write $\pi_c = P(c)$ and $\theta_{ct} = P(t \mid c)$. A training document $d$ of class $c$ has probability $\pi_c \, P(n_d) \prod_k \theta_{c t_k}$, and the training documents are independent, so the logarithm of the probability of the training set is a sum over documents. Class $c$ contributes a factor $\pi_c$ once for each of its $N_c$ documents, and term $t$ contributes a factor $\theta_{ct}$ once for each of its $T_{ct}$ occurrences in those documents:

$$\ell(\pi, \theta) = \sum_{c} N_c \log \pi_c \;+\; \sum_{c} \sum_{t \in V} T_{ct} \log \theta_{ct} \;+\; \sum_{d} \log P(n_d).$$

The last sum contains no parameter. The constraints are $\sum_c \pi_c = 1$ and, for each class, $\sum_t \theta_{ct} = 1$. Each constraint involves one group of parameters, and each group appears in one piece of $\ell$, so the pieces can be maximized separately.

The term probabilities of one class. Fix a class and write $\theta_t$ for $\theta_{ct}$. The piece to maximize is $\sum_t T_{ct} \log \theta_t$ subject to $\sum_t \theta_t = 1$. A term with $T_{ct} = 0$ does not appear in the sum, so any probability given to it is taken from terms that do appear and lowers the sum: the maximum has $\theta_t = 0$ for it. For the terms that occur, introduce a Lagrange multiplier $\lambda$ for the constraint and set the derivative of the Lagrangian to zero:

$$\frac{\partial}{\partial \theta_t} \Big[ \sum_{t'} T_{ct'} \log \theta_{t'} - \lambda \big( {\textstyle\sum_{t'}} \, \theta_{t'} - 1 \big) \Big] = \frac{T_{ct}}{\theta_t} - \lambda = 0 \quad\Longrightarrow\quad \theta_t = \frac{T_{ct}}{\lambda}.$$

Every $\theta_t$ is proportional to its count, and the terms with a count of zero fit the same formula. Summing over $t$ and using the constraint, $1 = \sum_t \theta_t = \sum_t T_{ct} / \lambda$, so $\lambda = \sum_{t'} T_{ct'}$ and

$$\hat{\theta}_t = \frac{T_{ct}}{\sum_{t'} T_{ct'}},$$

the relative frequency above.

The stationary point is the maximum. Write $T = \sum_{t'} T_{ct'}$ and $p_t = T_{ct}/T$ for the relative frequencies, and let $\theta$ be any other distribution over the vocabulary. If $\theta_t = 0$ for some term with $p_t > 0$, the training tokens have probability zero under $\theta$ and there is nothing to prove, so assume $\theta_t > 0$ for every such term. Using $\log x \le x - 1$ for $x > 0$, where $\log$ is the natural logarithm, and summing only over terms with $p_t > 0$,

$$\sum_t T_{ct} \log \theta_t - \sum_t T_{ct} \log p_t = T \sum_t p_t \log \frac{\theta_t}{p_t} \le T \sum_t p_t \Big( \frac{\theta_t}{p_t} - 1 \Big) = T \Big( \sum_{t:\, p_t > 0} \theta_t - 1 \Big) \le 0.$$

So no distribution gives the training tokens a higher probability than the relative frequencies do. Equality needs $\theta_t = p_t$ for every term, since $\log x = x - 1$ only at $x = 1$. This argument is Gibbs' inequality, which Cross-Entropy and Kullback–Leibler Divergence proves for any two distributions on a finite alphabet.

The priors. The piece to maximize is $\sum_c N_c \log \pi_c$ subject to $\sum_c \pi_c = 1$. Every class has at least one training document, so every $N_c > 0$. With a multiplier $\kappa$,

$$\frac{\partial}{\partial \pi_c} \Big[ \sum_{c'} N_{c'} \log \pi_{c'} - \kappa \big( {\textstyle\sum_{c'}} \, \pi_{c'} - 1 \big) \Big] = \frac{N_c}{\pi_c} - \kappa = 0 \quad\Longrightarrow\quad \pi_c = \frac{N_c}{\kappa}.$$

Summing over the classes, $1 = \sum_c \pi_c = \sum_c N_c / \kappa = N/\kappa$, so $\kappa = N$ and $\hat{P}(c) = N_c/N$. The inequality above, with classes in place of terms and $N_c$ in place of $T_{ct}$, shows that this too is the maximum.

On the running example, the counts are:

Term $T_{ct}$, China $T_{ct}$, Japan
Chinese 5 1
Beijing 1 0
Shanghai 1 0
Macao 1 0
Tokyo 0 1
Japan 0 1
Total 8 3

The priors are $\hat{P}(c) = 3/4$ and $\hat{P}(\bar{c}) = 1/4$. The maximum likelihood estimates for China are $5/8 = 0.625$ for Chinese, $1/8 = 0.125$ for each of the three city names, and zero for Tokyo and Japan. For the Japan class they are $1/3$ each for Chinese, Tokyo, and Japan, and zero for the cities.

Example (one zero decides). With these estimates the test document Chinese Chinese Chinese Tokyo Japan is assigned to Japan. The zero estimates for Tokyo and Japan make the document's probability under China zero, whatever its three occurrences of Chinese contribute; either zero alone would be enough.

Smoothing

Zero estimates are disastrous. The test document contains Tokyo, so its probability under China is $\tfrac{3}{4} \times 0.625^3 \times 0 \times 0 = 0$. The unsmoothed classifier chooses Japan, with score $\tfrac{1}{4} \times (1/3)^5 = 0.00103$. Three occurrences of Chinese count for nothing, because one term never seen in a class's training documents vetoes the class outright. With tens of thousands of terms and limited training data, this happens constantly. Almost every real test document contains some term that one class's training documents lack.

Add-one smoothing, or Laplace smoothing, adds 1 to every count:

$$\hat{P}(t \mid c) = \frac{T_{ct} + 1}{\sum_{t' \in V} T_{ct'} + B},$$

where $B = \lvert V \rvert$ is the vocabulary size, added to the denominator so that the probabilities still sum to 1. Every term then has a small nonzero probability in every class. The added counts act like one imaginary occurrence of every term in every class. That is a uniform prior belief, which the training data then revises (Manning, Raghavan, and Schütze, 2008, §13.2). The section after the worked numbers derives that reading. A more general form adds a constant $\alpha > 0$ instead of 1, giving $(T_{ct} + \alpha)/(\sum_{t'} T_{ct'} + \alpha B)$. It is known as add-$\alpha$ or Lidstone smoothing (Manning and Schütze, 1999, ch. 6).

With $B = 6$, the smoothed estimates for the running example are:

Term China, $(T_{ct} + 1)/(8 + 6)$ Japan, $(T_{ct} + 1)/(3 + 6)$
Chinese 6/14 = 0.429 2/9 = 0.222
Beijing 2/14 = 0.143 1/9 = 0.111
Shanghai 2/14 = 0.143 1/9 = 0.111
Macao 2/14 = 0.143 1/9 = 0.111
Tokyo 1/14 = 0.071 2/9 = 0.222
Japan 1/14 = 0.071 2/9 = 0.222

Smoothing moves probability from seen to unseen terms, and it moves more in the small class. The Japan class has only three training tokens, so six imaginary ones overwhelm them: its estimate for Chinese falls from 0.333 to 0.222. The China class, with eight real tokens, is changed less.

The test document has Chinese three times, Tokyo once, and Japan once:

$$\hat{P}(c \mid d) \propto \tfrac{3}{4} \cdot \left(\tfrac{3}{7}\right)^3 \cdot \tfrac{1}{14} \cdot \tfrac{1}{14} \approx 0.0003,$$

$$\hat{P}(\bar{c} \mid d) \propto \tfrac{1}{4} \cdot \left(\tfrac{2}{9}\right)^3 \cdot \tfrac{2}{9} \cdot \tfrac{2}{9} \approx 0.0001.$$

The classifier now chooses China. The two scores are 0.000301 and 0.000135. Dividing each by their sum restores the $P(d)$ dropped earlier and gives $\hat{P}(\textit{China} \mid d) = 0.690$. Smoothing reversed the decision.

Add-one smoothing as a posterior mean

Adding one to every count can look like an arbitrary repair. It is the exact answer to a well-posed question. Here is the idea. Maximum likelihood picks the single distribution that makes the training tokens most probable. A Bayesian estimate instead starts from a prior belief about which distributions are plausible, weighs every distribution by how well it explains the tokens, and averages. If every distribution over the vocabulary is equally plausible beforehand, the average gives term $t$ the probability $(T_{ct} + 1)/(\sum_{t'} T_{ct'} + B)$.

The formal version. Fix a class, and write $\theta = (\theta_1, \dots, \theta_B)$ for its term distribution and $T_t$ for the count $T_{ct}$. The set of all such $\theta$, with $\theta_t \ge 0$ and $\sum_t \theta_t = 1$, is called the simplex. The Dirichlet distribution with parameters $a_1, \dots, a_B > 0$ is the probability density on the simplex

$$p(\theta) = \frac{1}{Z(a)} \prod_{t=1}^{B} \theta_t^{\,a_t - 1}, \qquad Z(a) = \frac{\prod_t \Gamma(a_t)}{\Gamma\big(\sum_t a_t\big)},$$

where $\Gamma$ is the gamma function, which satisfies $\Gamma(x + 1) = x\,\Gamma(x)$, and $Z(a)$ is the integral of the product over the simplex, the constant that makes the density integrate to 1 (Bishop, 2006, §2.2.1). With every $a_t = 1$ the product is 1, so the density is constant: every distribution is equally plausible. That is the uniform prior. With every $a_t = \alpha$ the prior is called symmetric.

Step 1: the posterior is again a Dirichlet distribution. Take the prior to be Dirichlet with parameters $\alpha_t$. The training tokens of the class have probability $\prod_t \theta_t^{T_t}$ given $\theta$. By Bayes' rule the density of $\theta$ given the tokens is proportional to the likelihood times the prior:

$$p(\theta \mid \text{tokens}) \;\propto\; \prod_t \theta_t^{T_t} \cdot \prod_t \theta_t^{\,\alpha_t - 1} = \prod_t \theta_t^{\,T_t + \alpha_t - 1}.$$

This is the Dirichlet density with parameters $a_t = T_t + \alpha_t$. Each count has been added to its prior parameter.

Step 2: the probability of the next token is the posterior mean. The classifier needs the probability that a token of this class is term $t$. Given $\theta$ that probability is $\theta_t$, and $\theta$ is uncertain, so by the law of total probability

$$P(\text{next token is } t \mid \text{tokens}) = \int \theta_t \; p(\theta \mid \text{tokens}) \, d\theta = E[\theta_t \mid \text{tokens}].$$

Step 3: the mean of a Dirichlet distribution. Let $A = \sum_s a_s$. Multiplying the density by $\theta_t$ raises the exponent of $\theta_t$ by one, which gives the product for parameters $a$ with $a_t$ replaced by $a_t + 1$. Its integral is the constant $Z$ for those parameters, so

$$E[\theta_t] = \frac{1}{Z(a)} \int \theta_t \prod_s \theta_s^{\,a_s - 1} \, d\theta = \frac{\Gamma(a_t + 1)}{\Gamma(a_t)} \cdot \frac{\Gamma(A)}{\Gamma(A + 1)} = \frac{a_t}{A},$$

where every other factor of $Z$ cancels and the last step uses $\Gamma(x + 1) = x\,\Gamma(x)$ twice.

The result. With $a_t = T_{ct} + \alpha$ for every term, $A = \sum_{t'} T_{ct'} + \alpha B$ and

$$P(\text{next token is } t \mid \text{tokens}) = \frac{T_{ct} + \alpha}{\sum_{t'} T_{ct'} + \alpha B}.$$

With $\alpha = 1$, the uniform prior, this is add-one smoothing, and with general $\alpha$ it is Lidstone smoothing. On the running example the China class has counts $(5, 1, 1, 1, 0, 0)$, so its posterior under the uniform prior is Dirichlet with parameters $(6, 2, 2, 2, 1, 1)$, which sum to 14. The posterior means are $6/14$, $2/14$ and $1/14$, the China column of the table above. The script evaluates the ratio of the two constants $Z$ directly and obtains the same six values.

Example (a common misstatement). "Add-one smoothing is the most probable distribution under a uniform prior" is not correct. Under the uniform prior the posterior density is proportional to $\prod_t \theta_t^{T_t}$, which is the likelihood itself, so its most probable point is the maximum likelihood estimate, zeros included: $5/8$ for Chinese and 0 for Tokyo. Add-one smoothing is the posterior mean under the uniform prior. It is the most probable point under a different prior, the symmetric Dirichlet with every $\alpha_t = 2$. Then the posterior is proportional to $\prod_t \theta_t^{T_t + 1}$, and the maximization of the previous section, with $T_t + 1$ in place of $T_t$, gives $(T_t + 1)/(\sum_{t'} T_{t'} + B)$.

The same derivation serves two other units. A prior whose parameters are proportional to the collection's term frequencies instead of equal gives the Dirichlet smoothing of language models for retrieval, and the probability primer works the two-outcome case, the Beta prior. Latent Dirichlet allocation is built on Dirichlet priors of the same kind. In the statistics library, Priors, Posteriors and Conjugate Families works out the spread of the China posterior and the probability of the next tokens, and Choosing a Prior shows how much the uniform prior adds over a large vocabulary.

What the smoothing constant does

It is tempting to read smoothing as a technicality for avoiding zeros, with 1 as the natural amount to add. On this example the constant $\alpha$ decides the answer.

Example (the limit of heavy smoothing). If $\alpha$ is made enormous, so that the added counts swamp the real ones, China wins by $\log 3 = 1.099$ in log odds. Each estimate $(T_{ct} + \alpha)/(\sum_{t'} T_{ct'} + 6\alpha)$ tends to $1/6$ as $\alpha$ grows, in both classes. The term evidence then cancels and only the prior's 3-to-1 ratio remains. The figure plots the log odds of China against Japan as $\alpha$ varies.

Notice that the decision changes sign with the smoothing constant α (log scale). Below about α = 0.57 the near-zero estimates for Tokyo and Japan in the China class dominate and Japan wins. Add-one smoothing (α = 1) gives log odds of 0.799 in favor of China. As α grows very large every term becomes equally likely in both classes and only the prior's log 3 = 1.10 remains.
Notice that the decision changes sign with the smoothing constant α (log scale). Below about α = 0.57 the near-zero estimates for Tokyo and Japan in the China class dominate and Japan wins. Add-one smoothing (α = 1) gives log odds of 0.799 in favor of China. As α grows very large every term becomes equally likely in both classes and only the prior's log 3 = 1.10 remains.

Near $\alpha = 0$ the log odds fall without limit, because $\hat{P}(\textit{Tokyo} \mid c)$ approaches zero. As $\alpha$ grows, the estimates for both classes approach the uniform $1/6$, and the log odds approach the prior's 1.099. The decision changes from Japan to China at $\alpha = 0.573$. Smoothing is therefore not a technicality. It sets how far the classifier trusts sparse counts, and it should be chosen on held-out data, like any other parameter. The Reuters results below show what that looks like on a real collection.

Computing in log space

Multiplying hundreds of probabilities, each much smaller than 1, produces numbers too small to represent in floating point. A product of factors of $10^{-4}$, a typical probability for a moderately rare term, reaches zero in double precision after 81 factors (the script multiplies until the product is zero and counts). The average Reuters story in the experiments below has 87.5 tokens after stop words are removed. Taking logarithms turns the product into a sum, and the logarithm preserves order:

$$c_{\text{map}} = \arg\max_{c} \left[ \log \hat{P}(c) + \sum_{k=1}^{n_d} \log \hat{P}(t_k \mid c) \right].$$

Each term adds evidence for or against each class, weighted by its log probability, and the prior is a starting bias toward common classes. For the running example, with natural logarithms:

Contribution China Japan
Prior log 3/4 = −0.288 log 1/4 = −1.386
Chinese (3 times) 3 × (−0.847) = −2.542 3 × (−1.504) = −4.512
Tokyo (once) −2.639 −1.504
Japan (once) −2.639 −1.504
Score −8.108 −8.907

China wins by 0.799.

Example (the words alone favor Japan). Three occurrences of Chinese against one each of Tokyo and Japan do not, by themselves, favor China. Japan gains 1.135 on each of Tokyo and Japan, 2.270 in all. China gains 0.657 on each of the three occurrences of Chinese, 1.970 in all. On the words alone, Japan leads by 0.300. China wins only because the prior favors it by a further 1.099.

Naive Bayes is a linear classifier

For two classes, the decision depends only on the difference of the two scores, the log odds. Subtracting the two sums and grouping the tokens by term, so that a term occurring $\mathrm{tf}_{t,d}$ times contributes $\mathrm{tf}_{t,d}$ times:

$$\log \frac{\hat{P}(c \mid d)}{\hat{P}(\bar{c} \mid d)} = \underbrace{\log \frac{\hat{P}(c)}{\hat{P}(\bar{c})}}_{b} + \sum_{t \in V} \mathrm{tf}_{t,d} \underbrace{\log \frac{\hat{P}(t \mid c)}{\hat{P}(t \mid \bar{c})}}_{w_t}.$$

The document is assigned to $c$ when $b + \sum_t w_t \, \mathrm{tf}_{t,d} > 0$. That is a weighted sum of the document's term counts compared with a threshold, a hyperplane in the space of term-frequency vectors. Multinomial Naive Bayes is therefore a linear classifier, in the same family as the BIM's sum of term weights and the classifiers of vector space classification. Each weight $w_t$ is the log of how many times more probable the term is in one class than the other, and it can be read directly as that term's vote.

For the running example the weights are:

Term $w_t$ Count in test document Contribution
Chinese log (6/14)/(2/9) = 0.657 3 1.970
Beijing, Shanghai, Macao log (2/14)/(1/9) = 0.251 0 0
Tokyo log (1/14)/(2/9) = −1.135 1 −1.135
Japan log (1/14)/(2/9) = −1.135 1 −1.135
Bias $b$ log 3 = 1.099 1.099
Log odds 0.799

Terms absent from the document contribute nothing, whatever their weights. That is a property of the multinomial model, and the main point of contrast with the Bernoulli model, in which absences count.

Back to the grain classifier. On a real category the weights show what the classifier has learned. For the Reuters category grain, trained on all 7,769 training stories:

Notice who the votes come from. These are the ten largest and ten smallest weights of the multinomial Naive Bayes classifier for the Reuters category grain, with each term's occurrences in grain and in other training stories. The positive weights belong to grain vocabulary such as wheat, maize (maiz), barley (barlei) and durum. The negative weights belong to earnings reports: shr (shares), qtr (quarter), rev (revenue) and dividend, which never occur in grain stories.
Notice who the votes come from. These are the ten largest and ten smallest weights of the multinomial Naive Bayes classifier for the Reuters category grain, with each term's occurrences in grain and in other training stories. The positive weights belong to grain vocabulary such as wheat, maize (maiz), barley (barlei) and durum. The negative weights belong to earnings reports: shr (shares), qtr (quarter), rev (revenue) and dividend, which never occur in grain stories.

The positive weights are what a person would expect: feedgrain, wheat, maize, barley, durum, and rice. The largest weights go to terms that occur only in grain stories, such as feedgrain, 50 times in grain and never elsewhere. Smoothing caps them. A term never seen outside the class cannot receive an infinite weight, only one that grows with its count. The most negative weights belong to the vocabulary of earnings reports, the largest category in the collection. Most of the evidence that a story is not about grain is evidence that it is about something specific, such as quarterly results.

The bias is $b = \log(433/7{,}336) = -2.830$, since only 433 of the 7,769 training stories are about grain. A story must collect about 2.8 nats of evidence before the classifier will assign it to the category.

Example (one word against the prior). A story whose only term in the vocabulary was a single wheat would be assigned to grain. The weight of wheat is 5.923, so the story's log odds are $-2.830 + 5.923 = 3.093$, above zero. One strongly grain-specific term outweighs the prior; a real story's other terms add their own votes.

The algorithm

Everything above fits in two short procedures, which the course text gives as pseudocode (Manning, Raghavan, and Schütze, 2008, Figure 13.2).

Training. Given the labeled training documents:

  1. Collect the vocabulary $V$, the set of distinct terms in the training documents, and let $B = \lvert V \rvert$.
  2. For each class $c$, count its training documents $N_c$ and set the prior to $N_c/N$.
  3. For each class $c$ and each term $t \in V$, count the occurrences $T_{ct}$ of $t$ in the class's documents, repeats included, and set $\hat{P}(t \mid c) = (T_{ct} + 1)/(\sum_{t'} T_{ct'} + B)$.

Classification. Given a new document $d$:

  1. Extract its tokens, keep those that are in $V$, and keep them as a sequence, so that a term occurring three times is kept three times.
  2. For each class, add the logarithm of the prior and the logarithm of $\hat{P}(t \mid c)$ for each kept token.
  3. Return the class with the largest sum.

Two details of the first classification step matter. The tokens are a sequence and not a set, because the multinomial model counts every occurrence. And a token that is not in $V$ is dropped, because the model has no parameter for it.

Example (a test token outside the vocabulary). The document Chinese Chinese Chinese Tokyo Japan Osaka is classified exactly as the test document was: China, with log odds 0.799. Osaka occurs in no training document, so it is not in $V$ and is dropped before scoring. That is the right treatment, since a word never seen in training is evidence for neither class.

Example (a common misstatement). "An unseen word gets the smoothed probability of a term with count zero" is wrong for a word outside the vocabulary. Smoothing gives $1/(\sum_{t'} T_{ct'} + B)$ to a term of $V$ that did not occur in class $c$. Applying it to Osaka would multiply the China score by $1/14$ and the Japan score by $1/9$, and so change the log odds by $\log(9/14) = -0.442$, from 0.799 to 0.357. The word would count against China only because China has more training tokens. Two such words would lower the log odds to $0.799 - 2 \times 0.442 = -0.085$ and change the decision to Japan on no evidence at all.

Cost

How much work does all this take? Training reads every token once to count it, then computes a probability for every term in every class: $O(\lvert \mathbb{D} \rvert L_{\text{ave}} + \lvert \mathbb{C} \rvert \lvert V \rvert)$, where $L_{\text{ave}}$ is the average document length. Classifying a document adds one log probability per token per class: $O(\lvert \mathbb{C} \rvert L_d)$. Both are as cheap as a learning method can be, since even reading the data takes as long as training. That speed is a large part of why Naive Bayes is used on very large collections, such as the 120,000 reviews of my Goodreads project.

Results on Reuters-21578

On real news the classifier does well on large categories and assigns small ones too often. The experiments in this topic use the ten largest categories of Reuters-21578 with its standard training and test split: 7,769 training stories and 3,019 test stories. A separate binary classifier was trained for each category, as is usual for multilabel collections. The text was processed in four steps:

  • lowercased and tokenized into alphabetic words;
  • filtered with a short stop list (Lucene's English list plus said);
  • stripped of one-letter tokens;
  • stemmed with the original Porter algorithm.

With all 18,135 terms of the training vocabulary and add-one smoothing, multinomial Naive Bayes reached a micro-averaged F1 of 0.835 and a macro-averaged F1 of 0.721 on the test stories.

The per-category results show where it struggles:

Category F1 Category F1
acq 0.953 interest 0.706
earn 0.948 money-fx 0.703
crude 0.818 wheat 0.583
ship 0.765 trade 0.532
grain 0.710 corn 0.495

Large categories with distinctive vocabulary, such as earn and acq (acquisitions), are classified almost perfectly. Small categories that overlap with others are much harder. Nearly all wheat and corn stories are also labeled grain, and they share most of their vocabulary with stories about grain in general. The errors are lopsided: every category's recall is above 0.84, while precision falls as low as 0.35 for corn. The classifier assigns small categories too often. Evaluating classifiers gives the full counts and shows that moving the decision threshold above zero recovers much of the lost F1. Vector space classification compares other classifiers with it on Reuters.

Choosing the smoothing constant

The China/Japan example showed that $\alpha$ can flip a decision. On Reuters, add-one is a reasonable choice but not the best one: $\alpha = 3$ does better on micro-F1. To measure this, the training stories were split at random (seed 790) into 80 percent for training and 20 percent for development, and $\alpha$ was varied:

Notice the cliff to the right of α = 3. Micro- and macro-averaged F1 of multinomial Naive Bayes on Reuters as the smoothing constant α varies from 0.001 to 30, on a development split of the training stories (circles) and on the test stories with the full training set (squares). Both measures are best between α = 1 and α = 3 and collapse for larger values. The dotted line marks add-one smoothing.
Notice the cliff to the right of α = 3. Micro- and macro-averaged F1 of multinomial Naive Bayes on Reuters as the smoothing constant α varies from 0.001 to 30, on a development split of the training stories (circles) and on the test stories with the full training set (squares). Both measures are best between α = 1 and α = 3 and collapse for larger values. The dotted line marks add-one smoothing.

On the development split, $\alpha = 3$ gave the best micro-F1 (0.862) and $\alpha = 1$ the best macro-F1 (0.748), with $\alpha = 3$ close behind (0.745). Values of 10 and above collapsed, macro-F1 falling to 0.351 at $\alpha = 10$. A plausible reason is that heavy smoothing flattens the small categories' distributions toward uniform and erases their distinctive terms. The prior against a small category then decides almost everything, as in the limit computed for the China/Japan example. This explanation was not tested separately; the experiment shows the collapse, not its cause. Values below 1 were somewhat worse and nearly flat.

The test results follow the development results closely, which is what a sound development split should show. With $\alpha = 3$, test micro-F1 rises from 0.835 to 0.874 and macro-F1 from 0.721 to 0.731. The best value depends on the collection, its vocabulary size, and the class sizes, so it should be tuned rather than assumed. The rest of this topic keeps $\alpha = 1$, so that its numbers stay comparable.

Worked problems

Problems 1, 2, 4 and 5 are Exercises 13.9 (its multinomial parts), 13.7, 13.8 and 13.10 of the course text (Manning, Raghavan, and Schütze, 2008), restated in our own words with their data. Problem 3 is posed on the running example. The script tools/experiments/reuters/china_japan.py recomputes every number.

Problem 1. The training set has four documents. Two are in class China: Taipei Taiwan and Macao Taiwan Shanghai. Two are not: Japan Sapporo and Sapporo Osaka Taiwan. Estimate a multinomial Naive Bayes classifier with add-one smoothing, and classify the test document Taiwan Taiwan Sapporo. Only the parameters the test document needs have to be estimated.

Solution. Write $c$ for China and $\bar{c}$ for its complement. Each class has two of the four documents, so $\hat{P}(c) = \hat{P}(\bar{c}) = 1/2$. The vocabulary has seven terms (Taipei, Taiwan, Macao, Shanghai, Japan, Sapporo, Osaka), so $B = 7$. The documents of $c$ hold $2 + 3 = 5$ tokens, and so do those of $\bar{c}$. The test document needs only Taiwan and Sapporo:

Term $T_{ct}$ in $c$ $\hat{P}(t \mid c)$ $T_{ct}$ in $\bar{c}$ $\hat{P}(t \mid \bar{c})$
Taiwan 2 (2 + 1)/(5 + 7) = 1/4 1 (1 + 1)/(5 + 7) = 1/6
Sapporo 0 (0 + 1)/(5 + 7) = 1/12 2 (2 + 1)/(5 + 7) = 1/4

The test document has Taiwan twice and Sapporo once:

$$\hat{P}(c \mid d) \propto \tfrac{1}{2} \cdot \left(\tfrac{1}{4}\right)^2 \cdot \tfrac{1}{12} = \tfrac{1}{384} = 0.00260, \qquad \hat{P}(\bar{c} \mid d) \propto \tfrac{1}{2} \cdot \left(\tfrac{1}{6}\right)^2 \cdot \tfrac{1}{4} = \tfrac{1}{288} = 0.00347.$$

The classifier assigns the document to $\bar{c}$, not China. Normalizing, $\hat{P}(c \mid d) = (1/384)/(1/384 + 1/288) = 3/7 = 0.429$, and the log odds are $\log(288/384) = \log(3/4) = -0.288$. Two occurrences of Taiwan, each worth a factor $3/2$ for China, are outweighed by one Sapporo, worth a factor 3 against it: $(3/2)^2 / 3 = 3/4$. The Bernoulli model and why Naive Bayes works solves the rest of the exercise, with the Bernoulli model.

Problem 2. The priors are estimated as the fraction of training documents in each class, not as the fraction of training tokens. Explain why.

Solution. The generative story chooses a class once for each document, in its first step, and then draws all the document's tokens from that class. The prior is therefore the probability that a document belongs to the class, and the derivation above showed that its maximum likelihood estimate is $N_c/N$, a ratio of document counts. The fraction of tokens estimates a different quantity, the probability that a token picked at random from the collection lies in a document of the class. That quantity depends on how long each class's documents are. In the running example the two differ: China has 3 of 4 documents but 8 of 11 tokens, so the document prior gives a bias of $\log(3/1) = 1.099$ and a token prior would give $\log(8/3) = 0.981$. The decision would not change here (the log odds would be $0.799 - 1.099 + 0.981 = 0.681$), but a class with a few very long documents would be given a prior far above its share of the documents, and the classifier decides about documents.

Problem 3. In the running example, the test document has $n$ occurrences of Chinese and one each of Tokyo and Japan. Find every $n$ for which the classifier chooses China.

Solution. By the linear form, the log odds are the bias plus each term's weight times its count:

$$1.099 + 0.657\,n - 1.135 - 1.135 = 0.657\,n - 1.171.$$

This is positive exactly when $n > 1.171/0.657 = 1.78$. So the classifier chooses China for every $n \ge 2$ and Japan for $n = 0$ and $n = 1$. The values are $-1.171$, $-0.515$, $0.142$ and $0.799$ for $n = 0, 1, 2, 3$, computed from unrounded weights. One occurrence of Chinese is not enough to outweigh Tokyo and Japan even with the prior's help, and two are.

Problem 4. The classification procedure, as stated above, adds one log probability per token per class. If the document has $L_a$ tokens and $M_a$ distinct terms, that takes time proportional to $\lvert \mathbb{C} \rvert L_a$ after the tokens are extracted. Modify it to take time proportional to $L_a + \lvert \mathbb{C} \rvert M_a$.

Solution. Make one pass over the tokens and build a table of the count $\mathrm{tf}_{t,d}$ of each distinct term, which takes time proportional to $L_a$. Then, for each class, add $\mathrm{tf}_{t,d} \log \hat{P}(t \mid c)$ once for each distinct term, which takes time proportional to $M_a$ per class. The sums are unchanged, because a term occurring $\mathrm{tf}_{t,d}$ times contributed the same logarithm $\mathrm{tf}_{t,d}$ times. This is the grouping by term that produced the linear form. The test document of the running example has $L_a = 5$ tokens and $M_a = 3$ distinct terms. The original procedure performs $2 \times 5 = 10$ additions of log probabilities, and the modified one $2 \times 3 = 6$ multiplications and additions, for the same scores $-8.108$ and $-8.907$. The saving matters for long documents that repeat their terms.

Problem 5. Words are to be classified as English or not English. A source emits four words: ozb with probability 4/9 and uzu with probability 4/9, both not English, and zoo with probability 1/18 and bun with probability 1/18, both English. The features are the letters b, n, o, u and z, treated as the terms of a multinomial model. The training set reflects the source exactly. An estimate that comes out as zero is replaced by 0.01, and no other estimate is changed. (i) Compute the priors and the letter probabilities. (ii) Classify the word zoo. (iii) Classify zoo again with a model that drops positional independence and estimates a separate letter distribution for each of the three positions.

Solution. (i) The priors are $P(\text{English}) = 1/18 + 1/18 = 1/9$ and $P(\text{not English}) = 8/9$. Within the English class, zoo and bun are equally likely, so the class's letters are z, o, o, b, u, n in equal proportion. Within the other class, ozb and uzu are equally likely, giving o, z, b, u, z, u.

Letter $\hat{P}(\text{letter} \mid \text{English})$ $\hat{P}(\text{letter} \mid \text{not English})$
b 1/6 1/6
n 1/6 0, replaced by 0.01
o 2/6 = 1/3 1/6
u 1/6 2/6 = 1/3
z 1/6 2/6 = 1/3

(ii) For zoo, with letters z, o, o:

$$\text{English: } \tfrac{1}{9} \cdot \tfrac{1}{6} \cdot \tfrac{1}{3} \cdot \tfrac{1}{3} = \tfrac{1}{486} = 0.00206, \qquad \text{not English: } \tfrac{8}{9} \cdot \tfrac{1}{3} \cdot \tfrac{1}{6} \cdot \tfrac{1}{6} = \tfrac{8}{972} = \tfrac{2}{243} = 0.00823.$$

The classifier says zoo is not English, by a factor of 4, although zoo is one of the two English words. The letters z and o are both common in the non-English words, and the prior favors that class 8 to 1.

(iii) With a distribution for each position, the English class has z or b first, o or u second, and o or n third, each with probability 1/2. So $P(\textit{zoo} \mid \text{English}) = (1/2)^3 = 1/8$, and the English score is $\tfrac{1}{9} \cdot \tfrac{1}{8} = 1/72 = 0.0139$. In the other class the first letter is o or u, the second is always z, and the third is b or u. None of z first, o second, o third occurs, so each of the three probabilities is zero and is replaced by 0.01, and the score is $\tfrac{8}{9} \times 0.01^3 = 8.9 \times 10^{-7}$. The classifier now says English, by a factor of exactly 15,625. Here position carries the information: z is common in the non-English words but never first, and o never second or third. Positional independence threw that away. For documents, with thousands of positions and little regularity in what appears where, the positional model would have far too many parameters to estimate, which is why the multinomial model pools the positions.

What we have learned

Naive Bayes is Bayes' rule plus a generative story in which each token is drawn independently given the class. Its parameters are relative frequencies, smoothed so that one unseen term cannot veto a class; the amount of smoothing can flip a decision. In log space it is a linear classifier whose weights read as votes. It chooses China by 0.799 and reaches 0.835 micro-F1 on Reuters.

The multinomial model counts every occurrence of a term and ignores the terms a document lacks. The Bernoulli model and why Naive Bayes works sets out the model in which a document records only which terms it contains, and explains why a classifier built on a false independence assumption still classifies well.

References

  • Bishop, C. M. (2006). Pattern Recognition and Machine Learning, section 2.2.1. Springer. record · 10 pages
  • Lewis, D. D. (1998). Naive (Bayes) at forty: The independence assumption in information retrieval. In Proceedings of ECML 1998, 4–15. record · 2 pages
  • Manning, C. D., Raghavan, P., and Schütze, H. (2008). Introduction to Information Retrieval, sections 13.2 and 13.4. Cambridge University Press. record · 102 pages
  • Manning, C. D., and Schütze, H. (1999). Foundations of Statistical Natural Language Processing, chapter 6. MIT Press. record · 2 pages

Reviewed: verified, 16 Nov 2026 · checked against sources, 23 Nov 2026 · citations checked, 16 Nov 2026 · editorial review, 23 Nov 2026 · 12 revisions