Unit 5, lesson 34

Naive Bayes Classification

How naive Bayes combines class priors with per-class feature probabilities, what its conditional independence assumption says, why Laplace smoothing prevents zero probabilities, and why scores use log probabilities.

  • Video 34
  • Generative Classifiers

A maintenance desk receives short messages from equipment operators and has to decide quickly which ones are urgent. Past messages show how often words such as stop and heat appear in urgent and in routine messages, but the question about a new message runs the other way, from its words to its class. Naive Bayes reverses the direction with Bayes’ rule and keeps the model small by assuming that the words are independent within each class. This lesson builds the classifier from class priors and word probabilities, smooths the estimates, computes with logarithms, and shows what the independence assumption can break.

Key terms

Generative classifier

Definition A generative classifier models how the features arise within each class. For classes c=1,…,Kc = 1, \dots, K it specifies class probabilities πc=P(Y=c)\pi_c = P(Y = c) and, for each class, a distribution P(x∣Y=c)P(\mathbf{x} \mid Y = c) of the feature vector, a probability mass function for discrete features or a density for continuous ones. Together they give the joint distribution P(x,Y=c)=qc(x)P(\mathbf{x}, Y = c) = q_c(\mathbf{x}), where qc(x)=πc P(x∣Y=c)q_c(\mathbf{x}) = \pi_c\, P(\mathbf{x} \mid Y = c), and Bayes’ rule turns it into class probabilities,

P(Y=c∣x)=qc(x)∑k=1Kqk(x),P(Y = c \mid \mathbf{x}) = \frac{q_c(\mathbf{x})}{\sum_{k=1}^{K} q_k(\mathbf{x})} ,

for every x\mathbf{x} at which the denominator is positive. The products qc(x)q_c(\mathbf{x}) are unnormalized scores. When all errors cost the same, predicting the class with the largest posterior probability minimizes the probability of an error, provided the model is correct. A discriminative classifier such as logistic regression instead models P(Y=c∣x)P(Y = c \mid \mathbf{x}) directly and says nothing about how x\mathbf{x} varies within a class.

In plain words A generative classifier first learns what messages of each class look like, then uses Bayes’ rule to ask which class most plausibly produced the message in hand. The largest score picks the same class as the largest probability, because every score is divided by the same total. A score becomes a probability only after that division.

Example Ten constructed training messages are labeled urgent or routine, and each is described by two binary features, x1=1x_1 = 1 when the word stop appears and x2=1x_2 = 1 when heat appears. A fitted model, whose numbers the following cards derive, has priors π^U=0.6\hat{\pi}_U = 0.6 and π^R=0.4\hat{\pi}_R = 0.4, and gives a message containing both words the probabilities P^(x∣U)=0.3125\hat{P}(\mathbf{x} \mid U) = 0.3125 and P^(x∣R)=1/9\hat{P}(\mathbf{x} \mid R) = 1/9. The scores are qU=0.6⋅0.3125=0.1875q_U = 0.6 \cdot 0.3125 = 0.1875 and qR=0.4/9≈0.0444q_R = 0.4/9 \approx 0.0444, which sum to 167/720167/720. So

P(U∣x)=0.1875167/720=135167≈0.8084.\begin{aligned} P(U \mid \mathbf{x}) &= \frac{0.1875}{167/720} \\[0.4em] &= \frac{135}{167} \approx 0.8084 . \end{aligned}

The score 0.18750.1875 on its own is not the probability that the message is urgent.

Class prior

Definition The class prior πc=P(Y=c)\pi_c = P(Y = c) is the probability of class cc before any features are seen, with πc≥0\pi_c \ge 0 and π1+⋯+πK=1\pi_1 + \cdots + \pi_K = 1. If ncn_c of the nn training examples belong to class cc, the maximum likelihood estimate is π^c=nc/n\hat{\pi}_c = n_c/n. That estimate suits prediction only when the training examples were sampled with the class proportions of the population where the classifier will be used. When the classes were collected in fixed numbers or rebalanced, the priors should be set to the deployment proportions instead. Changing the priors multiplies the posterior odds of class cc against class kk by the same factor as their prior odds and leaves the likelihoods P(x∣Y=c)P(\mathbf{x} \mid Y = c) untouched.

In plain words The prior says how common each class is. The features then move the probability up or down from that starting point. A rare class needs stronger evidence from the features to win.

Example The training set has six urgent and four routine messages, so π^U=0.6\hat{\pi}_U = 0.6, π^R=0.4\hat{\pi}_R = 0.4 and the prior odds of urgent are 1.51.5. For a message with both words, the likelihoods from the first card have ratio 0.3125÷(1/9)=2.81250.3125 \div (1/9) = 2.8125, so the posterior odds of urgent are

1.5×2.8125=4.21875=13532,\begin{aligned} 1.5 \times 2.8125 &= 4.21875 \\[0.4em] &= \tfrac{135}{32} , \end{aligned}

which again gives 135/167≈0.8084135/167 \approx 0.8084. If only 2020 percent of the messages in service were urgent, the prior odds would be 0.250.25 and the posterior odds 0.25×2.8125=0.7031250.25 \times 2.8125 = 0.703125, a posterior probability of about 0.4130.413. The same message would then be classified as routine under equal costs.

Naive Bayes assumption

Definition The naive Bayes assumption states that the features are conditionally independent given the class. For every class cc and every feature vector x=(x1,…,xp)\mathbf{x} = (x_1, \dots, x_p),

P(x∣Y=c)=∏j=1pP(Xj=xj∣Y=c).\begin{aligned} & P(\mathbf{x} \mid Y = c) \\[0.4em] &= \prod_{j=1}^{p} P(X_j = x_j \mid Y = c) . \end{aligned}

It is a modeling assumption, not a fact about the data, and it says nothing about independence of the features when the classes are pooled. Its value is economy. For pp binary features a general distribution within one class needs 2p−12^p - 1 probabilities, while the assumption needs only pp, one for each feature.

In plain words Once the class is known, learning that one word appears is assumed to say nothing more about whether another word appears. The words can still be associated across all messages, simply because urgent messages contain more of both. The assumption fails when one word tends to bring another along within the same class, for example if writers who mention heat also tend to write stop.

Example Among the six urgent messages, four contain stop and three contain heat. Among the four routine messages, one contains each word. These counts do not say how many messages contain both words. Take the unsmoothed proportions as estimates, 4/64/6 for stop and 3/63/6 for heat among urgent messages and 1/41/4 for each word among routine ones. The assumption then implies that 6⋅46⋅36=26 \cdot \tfrac{4}{6} \cdot \tfrac{3}{6} = 2 of the six urgent messages are expected to contain both. Under the same fitted model the probability of stop is 0.6⋅46+0.4⋅14=0.50.6 \cdot \tfrac{4}{6} + 0.4 \cdot \tfrac{1}{4} = 0.5, the probability of heat is 0.40.4, and the probability of both is

0.6⋅46⋅36+0.4⋅14⋅14=0.225,\begin{aligned} & 0.6 \cdot \tfrac{4}{6} \cdot \tfrac{3}{6} + 0.4 \cdot \tfrac{1}{4} \cdot \tfrac{1}{4} \\[0.4em] &= 0.225 , \end{aligned}

not 0.5×0.4=0.20.5 \times 0.4 = 0.2. The words are dependent overall although the model makes them independent within each class. With p=30p = 30 binary features a general model would need 230−1=1,073,741,8232^{30} - 1 = 1{,}073{,}741{,}823 probabilities per class, against 3030 under the assumption.

Laplace smoothing

Definition For a binary feature jj and a class cc with ncn_c training examples, of which rcjr_{cj} have xj=1x_j = 1, the smoothed estimate of θcj=P(Xj=1∣Y=c)\theta_{cj} = P(X_j = 1 \mid Y = c) is

θ^cj=rcj+αnc+2α\hat{\theta}_{cj} = \frac{r_{cj} + \alpha}{n_c + 2\alpha}

with a smoothing constant α>0\alpha > 0. Laplace smoothing is the choice α=1\alpha = 1, which adds one imagined example with the feature present and one with it absent to every class. It is the posterior mean of θcj\theta_{cj} under a uniform prior. With α=0\alpha = 0 the formula is the maximum likelihood estimate rcj/ncr_{cj}/n_c, which equals 00 when the feature never appears in the class and 11 when it always does. For every α>0\alpha > 0 the estimate lies strictly between 00 and 11. The constant is a modeling choice, fixed in advance or tuned on validation data, and the counts come from the training data only.

In plain words Without smoothing, a word that never appeared in the urgent training messages would get probability 00 for that class, and no future message containing it could ever be classified as urgent, however strong the other evidence. Smoothing pulls every estimate a little toward 1/21/2, by less when the class has many examples. It is a rule for estimating, not a set of extra observations to report or evaluate.

Example The smoothed estimates are

θ^U,stop=4+16+2=58,θ^U,heat=3+16+2=12,θ^R,stop=θ^R,heat=1+14+2=13.\begin{gathered} \hat{\theta}_{U,\text{stop}} = \tfrac{4 + 1}{6 + 2} = \tfrac{5}{8} , \\[0.4em] \hat{\theta}_{U,\text{heat}} = \tfrac{3 + 1}{6 + 2} = \tfrac{1}{2} , \\[0.4em] \hat{\theta}_{R,\text{stop}} = \hat{\theta}_{R,\text{heat}} = \tfrac{1 + 1}{4 + 2} = \tfrac{1}{3} . \end{gathered}

These give the likelihoods of the first card, 58⋅12=0.3125\tfrac{5}{8} \cdot \tfrac{1}{2} = 0.3125 and 13⋅13=19\tfrac{1}{3} \cdot \tfrac{1}{3} = \tfrac{1}{9}. Now suppose a third word, noise, appeared in none of the six urgent messages and in two of the four routine ones. Unsmoothed, its urgent probability is 00, and every message containing noise gets posterior probability exactly 00 for urgent. Smoothed, the estimates are 1/81/8 for urgent and 3/6=1/23/6 = 1/2 for routine, so the word counts as evidence for routine without overriding everything else.

Naive Bayes classifier

Definition The Bernoulli naive Bayes classifier works with binary features xjx_j in {0,1}\{0, 1\} for j=1,…,pj = 1, \dots, p. It combines class priors πc\pi_c with the probabilities θcj=P(Xj=1∣Y=c)\theta_{cj} = P(X_j = 1 \mid Y = c) under the naive Bayes assumption,

P(x∣Y=c)=∏j=1pθcj xj(1−θcj)1−xj,\begin{aligned} & P(\mathbf{x} \mid Y = c) \\[0.4em] &= \prod_{j=1}^{p} \theta_{cj}^{\,x_j} (1 - \theta_{cj})^{1 - x_j} , \end{aligned}

so a present feature contributes θcj\theta_{cj} and an absent one contributes 1−θcj1 - \theta_{cj}. It is fitted with π^c=nc/n\hat{\pi}_c = n_c/n, or with deployment priors, and smoothed estimates θ^cj\hat{\theta}_{cj}. It predicts the class with the largest score π^c P^(x∣Y=c)\hat{\pi}_c\, \hat{P}(\mathbf{x} \mid Y = c), which is the class with the largest estimated posterior probability, and ties are broken by a fixed rule. Unequal error costs call for a different decision rule applied to the posterior probabilities. Multinomial naive Bayes is a different model, built for word counts, in which the likelihood comes from how often each vocabulary word occurs, so the feature representation must be stated.

In plain words Each feature casts a vote that depends on the class, through its probability when present or its complement when absent, and the votes are multiplied with the prior. With two classes, the posterior odds are the prior odds times one likelihood ratio per feature, which makes every decision easy to inspect. In the Bernoulli model a missing word is evidence too.

Example A message with both words has urgent score 0.6⋅58⋅12=3160.6 \cdot \tfrac{5}{8} \cdot \tfrac{1}{2} = \tfrac{3}{16} and routine score 0.4⋅13⋅13=2450.4 \cdot \tfrac{1}{3} \cdot \tfrac{1}{3} = \tfrac{2}{45}, as in the first card. Its posterior odds factor as the prior odds 1.51.5, the ratio 58÷13=1.875\tfrac{5}{8} \div \tfrac{1}{3} = 1.875 for stop and the ratio 12÷13=1.5\tfrac{1}{2} \div \tfrac{1}{3} = 1.5 for heat, with product 135/32135/32. A message with neither word gets

qU=0.6⋅38⋅12=0.1125,qR=0.4⋅23⋅23≈0.1778,\begin{aligned} q_U &= 0.6 \cdot \tfrac{3}{8} \cdot \tfrac{1}{2} = 0.1125 , \\[0.4em] q_R &= 0.4 \cdot \tfrac{2}{3} \cdot \tfrac{2}{3} \approx 0.1778 , \end{aligned}

so its urgent probability is 81/209≈0.387681/209 \approx 0.3876 and the equal-cost decision is routine. The two absent words moved the odds away from urgent, which a model that ignored absent words could not do.

Log-probability score

Definition The log-probability score of class cc for a feature vector x\mathbf{x} is the natural logarithm of its unnormalized score. In the Bernoulli naive Bayes model, with all θcj\theta_{cj} strictly between 00 and 11, the present features add ln⁡θcj\ln \theta_{cj} and the absent ones add ln⁡(1−θcj)\ln(1 - \theta_{cj}),

ℓc(x)=ln⁡πc+∑j: xj=1ln⁡θcj+∑j: xj=0ln⁡(1−θcj).\begin{aligned} \ell_c(\mathbf{x}) &= \ln \pi_c + \sum_{j:\, x_j = 1} \ln \theta_{cj} \\[0.4em] &\quad + \sum_{j:\, x_j = 0} \ln(1 - \theta_{cj}) . \end{aligned}

The logarithm is strictly increasing, so the class with the largest ℓc(x)\ell_c(\mathbf{x}) is the class with the largest score. To recover probabilities, subtract the largest log score m=max⁡kℓk(x)m = \max_k \ell_k(\mathbf{x}) before exponentiating,

P(Y=c∣x)=eℓc(x)−m∑k=1Keℓk(x)−m.\begin{aligned} & P(Y = c \mid \mathbf{x}) \\[0.4em] &= \frac{e^{\ell_c(\mathbf{x}) - m}}{\sum_{k=1}^{K} e^{\ell_k(\mathbf{x}) - m}} . \end{aligned}

The common factor e−me^{-m} cancels, so the result is exactly the normalized posterior, and the largest term in the denominator equals 11, so the division cannot become 0/00/0.

In plain words A product of many probabilities below 11 quickly becomes smaller than the smallest positive number a computer stores, and then every class scores 00. A sum of logarithms stays an ordinary number, and only the differences between the class sums matter. Smoothing keeps every logarithm finite.

Example For the message with both words,

ℓU=ln⁡0.6+ln⁡58+ln⁡12≈−1.6740,ℓR=ln⁡0.4+2ln⁡13≈−3.1135.\begin{aligned} \ell_U &= \ln 0.6 + \ln \tfrac{5}{8} + \ln \tfrac{1}{2} \\[0.4em] &\approx -1.6740 , \\[0.4em] \ell_R &= \ln 0.4 + 2 \ln \tfrac{1}{3} \\[0.4em] &\approx -3.1135 . \end{aligned}

The difference 1.43951.4395 equals ln⁡(135/32)\ln(135/32), and the urgent probability is 1/(1+e−1.4395)≈0.80841/(1 + e^{-1.4395}) \approx 0.8084, the same as before. With 200200 features each contributing a factor 0.010.01, the direct product 10−40010^{-400} is below the smallest positive double-precision number, about 4.9×10−3244.9 \times 10^{-324}, and rounds to 00, while the log score 200ln⁡0.01≈−921.03200 \ln 0.01 \approx -921.03 is computed without trouble.

Check yourself

  1. Using the fitted model on this page, with priors 0.60.6 for urgent and 0.40.4 for routine, smoothed probabilities 58\tfrac{5}{8} for stop and 12\tfrac{1}{2} for heat among urgent messages and 13\tfrac{1}{3} for each word among routine messages, classify a message that contains stop but not heat. Give both scores, the urgent posterior probability and the equal-cost decision.
Show the answer

The absent word contributes the complement of its probability. The urgent score is 0.6⋅58⋅12=316=1357200.6 \cdot \tfrac{5}{8} \cdot \tfrac{1}{2} = \tfrac{3}{16} = \tfrac{135}{720}, unchanged from the message with both words because 1−12=121 - \tfrac{1}{2} = \tfrac{1}{2}. The routine score is 0.4⋅13⋅23=445=647200.4 \cdot \tfrac{1}{3} \cdot \tfrac{2}{3} = \tfrac{4}{45} = \tfrac{64}{720}. So

P(U∣x)=135135+64=135199≈0.6784,\begin{aligned} P(U \mid \mathbf{x}) &= \frac{135}{135 + 64} \\[0.4em] &= \frac{135}{199} \approx 0.6784 , \end{aligned}

and the equal-cost decision is urgent. As a check, the posterior odds are 1.5×1.875×0.75=135/641.5 \times 1.875 \times 0.75 = 135/64, where 0.75=12÷230.75 = \tfrac{1}{2} \div \tfrac{2}{3} is the ratio for the absent heat. The evidence for urgent is weaker than for the message with both words, whose probability was about 0.80840.8084.

  1. Suppose none of the four routine training messages had contained stop, with all other counts unchanged. Find the urgent posterior probability of a message containing both words without smoothing and with Laplace smoothing.
Show the answer

Without smoothing the routine estimate for stop is 0/4=00/4 = 0, so the routine score is 00 and the urgent posterior probability is exactly 11. No other feature could change that. With Laplace smoothing the routine estimate is (0+1)/(4+2)=16(0 + 1)/(4 + 2) = \tfrac{1}{6}, so the routine score is 0.4⋅16⋅13=145=167200.4 \cdot \tfrac{1}{6} \cdot \tfrac{1}{3} = \tfrac{1}{45} = \tfrac{16}{720}, while the urgent score stays 135720\tfrac{135}{720}. The posterior is

135135+16=135151≈0.8940.\frac{135}{135 + 16} = \frac{135}{151} \approx 0.8940 .

Four routine messages without the word are weak evidence that the word can never occur in a routine message, and smoothing keeps the estimate positive.

  1. A colleague adds a copy of the stop column under a second name, so every message now has three features. What does naive Bayes now give for a message containing both words, and does the agreement between the two identical columns support the conditional independence assumption?
Show the answer

The copy has the same smoothed probabilities as stop, so its ratio 1.8751.875 enters the posterior odds a second time,

1.5×1.8752×1.5≈7.910,1.5 \times 1.875^2 \times 1.5 \approx 7.910 ,

and the urgent probability rises to 2025/2281≈0.88782025/2281 \approx 0.8878 from 0.80840.8084, although the message carries no new information. The agreement does not support the assumption. Two identical columns are perfectly dependent within each class, unless the word is always present or always absent there, and the model counts the same evidence twice. Correlated features do the same to a lesser degree, so a naive Bayes classifier can choose labels well while its probabilities are too extreme. Its probabilities should be checked for calibration on held-out messages before anyone relies on them.

How this lesson connects