Settings

Theme
Lite Mode (saves mobile data)

In Lite Mode, animations and videos don't play until you tap them, and their size is shown first. Interactive widgets still work.

Text size

Back up or move your progress →

Part 3: Classical Machine LearningClassic Algorithms

Naive Bayes

P3.B240 min●●○ IntermediateReviewed Dec 2, 2026

Why this matters for machine learning

Naive Bayes is the smallest complete probabilistic classifier: a prior, a likelihood for each feature, Bayes’ rule and an argmax. It trains by counting, works with little data and explains each decision word by word, so it is the clearest first example of turning evidence into a probability.

  • Logistic regression has the same linear form for its log odds, but it finds the weights by minimizing a loss instead of counting. (P3.A7: Logistic regression)
  • Whether a spam filter is good enough depends on precision and recall, because blocking a real email costs more than letting a spam through. (P3.A9: Evaluation metrics)
  • The probabilities naive Bayes reports are often too extreme. Calibration measures this and repairs it. (P3.A10: Calibration and class imbalance)
  • Adding pseudo-counts so that an unseen word never has probability zero is the same smoothing that n-gram language models use. (P6.2: N-gram language models, coming soon)

Before this: What are AI, ML and Deep Learning?, Joint, marginal and conditional probability, Bayes' theorem, Maximum Likelihood Estimation, MAP estimation and priors, Numerical stability, The supervised learning setup

After this lesson you can

  • Write the naive Bayes decision rule, say exactly what is assumed to be independent of what, and say why p(x)p(\mathbf{x}) can be dropped
  • Train a filter by counting, add smoothing, and explain what goes wrong without it
  • Score an email by hand and in code with a sum of log probabilities, and say why logs are needed
  • Tell the multinomial, Bernoulli and Gaussian variants apart, and name the main strengths and weaknesses

In P0.1 a toy filter gave every word a score (spam count minus ham count) and added the scores. “Win cash prize now” came out at +8+8 and “are you free for lunch” at −3-3. Those totals say which side an email is on, but not how sure the filter is. Is +8+8 “almost certain” or “a little more than a coin flip”?

This lesson builds a second filter on the same eight emails that answers in probabilities, such as “98% spam”. It is called naive Bayes: Bayes’ rule (P1.D6) plus one simplifying assumption. At the end you can compare the two filters email by email.

Bayes’ rule for a class

In classification the hypothesis is the class cc (spam or ham) and the evidence is the features x\mathbf{x} (the words). P1.D6 gave the rule

p(c∣x)=p(c) p(x∣c)p(x).p(c\mid\mathbf{x})=\frac{p(c)\,p(\mathbf{x}\mid c)}{p(\mathbf{x})}.

Here p(c)p(c) is the prior: how common the class is before you read the email. The likelihood p(x∣c)p(\mathbf{x}\mid c) says how likely these words are if the class is cc. The left side is the posterior: what we believe after reading. The filter picks the class with the largest posterior (an argmax, the class where the quantity is biggest).

Models that estimate p(c)p(c) and p(x∣c)p(\mathbf{x}\mid c) and then apply Bayes’ rule are called generative (P8.1 compares them with the discriminative models that estimate p(c∣x)p(c\mid\mathbf{x}) directly, such as logistic regression in P3.A7).

The prior is easy: count the share of spam among the training emails. The likelihood is the hard part. An email is a whole pattern of words, and p(x∣c)p(\mathbf{x}\mid c) is the chance of that exact pattern in a class. With only 19 different words, each either present or absent, there are 219=524,2882^{19}=524{,}288 possible patterns. A table of their probabilities needs 219−1=524,2872^{19}-1=524{,}287 free numbers for each class (the last one is fixed because they add to 1), and our eight emails cannot fill it. Real vocabularies have tens of thousands of words.

The naive step

Naive Bayes makes one assumption: given the class, the features are independent (P1.D5). Once you know an email is spam, whether it contains “prize” tells you nothing more about whether it contains “free”. Then the chance of the whole pattern is a product of one-word chances:

p(x1,…,xd∣c)=∏i=1dp(xi∣c).p(x_1,\dots,x_d\mid c)=\prod_{i=1}^{d}p(x_i\mid c).

The table of 524,287 numbers shrinks to 19 numbers per class (for yes/no features; a multinomial model’s 19 word chances add to 1, so 18 of them are free).

Two points about this assumption.

  • It is conditional. Naive Bayes does not say the words are independent in general. Across all emails, “free” and “prize” do appear together, because both point to spam. It says that inside one class they are treated as unrelated.
  • It is usually false. Inside spam, “free” and “prize” still tend to come together. That is why the method is called naive. The classifier does not need the assumption to be true to rank the classes correctly. Only the winning class matters for the decision, and in practice the ranking is often still good, although the final probabilities can be badly off (see below, and the Go-deeper box on why it can still work). That is an experience from practice, not a guarantee.

The decision rule

With the product in place, the posterior is proportional to the prior times the word chances. The denominator p(x)p(\mathbf{x}) does not depend on the class: it is the same number for spam and for ham. Dividing every class score by the same number cannot change which is largest, so it can be dropped when we only want the winning class:

c^=arg⁡max⁡c  p(c)∏ip(xi∣c).\hat c=\arg\max_{c}\;p(c)\prod_{i}p(x_i\mid c).

If you also want the probability, divide each score by the sum of the scores of all classes. That sum is p(x)p(\mathbf{x}), so nothing is lost.

Training is counting

Training means estimating the numbers in the rule from the labelled data. For naive Bayes it is just counting, in one pass over the emails.

  • Prior: the class count divided by the number of emails. P0.1 has 4 spam and 4 ham emails, so p(spam)=p(ham)=0.5p(\text{spam})=p(\text{ham})=0.5.
  • Word probability in a class: the number of times the word appears in the class’s emails, divided by the total number of word occurrences in that class.

This is the maximum likelihood estimate (P1.D10), the same counting rule as the coin’s “heads divided by flips”. Here the class “spam” has Nspam=15N_{\text{spam}}=15 word occurrences and the class “ham” has Nham=15N_{\text{ham}}=15, so “prize” (3 times in spam, never in ham) has estimated probability 315=0.2\frac{3}{15}=0.2 in spam and 015=0\frac{0}{15}=0 in ham. In P0.1’s emails no word repeats inside an email, so the count of a word equals the number of emails that contain it. The next cell does the counting.

Build a spam filter

This is the signature part: a few short cells you can run and change, each followed by the output it should print. They use only the standard library, so they run in the page.

Step 1: count words, priors and the vocabulary

Runs real Python in your browser. First run downloads about 6 MB (once; your browser keeps it).

Expected output:

emails: 4 spam, 4 ham
prior P(spam): 0.5
vocabulary size V: 19
spam words N_spam: 15
ham words  N_ham:  15
prize    spam=3 ham=0
free     spam=3 ham=1
now      spam=3 ham=1
lunch    spam=0 ham=2
meeting  spam=0 ham=2
cash     spam=1 ham=0

The vocabulary size V=19V=19 is the same 19 words that had scores in P0.1.

The zero-count problem

Take the P0.1 email “free prize now meeting”. In training, “prize” never appears in ham and “meeting” never appears in spam. With the raw counts, the ham score has a factor 00 (for “prize”) and the spam score has a factor 00 (for “meeting”). Both classes get probability 00, and the filter has no answer. The same happens in general: a single word that never occurred in a class makes that class impossible for every email containing the word, however strong the other evidence is. In log space it would be ln⁡0=−∞\ln 0=-\infty.

The fix is to pretend we saw every word a little: add a small count α\alpha to every word in every class. This is add-α\alpha smoothing, and with α=1\alpha=1 it is Laplace smoothing or add-one smoothing. For a vocabulary of VV words,

p(w∣c)=nc(w)+αNc+αV,p(w\mid c)=\frac{n_{c}(w)+\alpha}{N_c+\alpha V},

where nc(w)n_c(w) is the count of word ww in class cc and NcN_c is the class’s total word count. The denominator grows by αV\alpha V so that the probabilities still add to 1. These are the pseudo-counts of P1.D11: the coin’s “one imagined head and one imagined tail” generalizes to “α\alpha imagined occurrences of every word”.

With α=1\alpha=1 and V=19V=19, the probability of “prize” is 3+115+19=434=0.1176\frac{3+1}{15+19}=\frac{4}{34}=0.1176 in spam and 0+134=0.0294\frac{0+1}{34}=0.0294 in ham. No word has probability 00 any more.

The size of α\alpha is a setting you choose (a hyperparameter, P3.A4). Small α\alpha, such as 0.10.1, trusts the counts; large α\alpha pulls every word toward “equally likely in both classes” and weakens the evidence. The cell below shows all three cases for the same email.

Step 2: zero counts and smoothing

Runs real Python in your browser. First run downloads about 6 MB (once; your browser keeps it).

Expected output:

alpha=0: spam 0.00e+00  ham 0.00e+00
   both are 0: no answer
alpha=1: spam 4.79e-05  ham 8.98e-06
   P(spam) = 0.8421
alpha=0.1: spam 3.65e-05  ham 3.11e-06
   P(spam) = 0.9214

Words that were never seen in training at all, such as “the” in the P0.1 email “are you free for the meeting”, are simply skipped here (scikit-learn’s CountVectorizer also ignores them). That is fair in this data because both classes have 15 words, so a new word would get exactly the same probability in both and cancel.

Scoring an email by hand

Every denominator is 15+19=3415+19=34 in both classes, so it cancels when we compare. The odds of spam against ham (with equal priors) is then the product, over the words, of nspam+1nham+1\frac{n_{\text{spam}}+1}{n_{\text{ham}}+1}.

Email 4, “win cash prize now” (the one that P0.1’s one-word rule missed). The counts (spam, ham) are win (2,0)(2,0), cash (1,0)(1,0), prize (3,0)(3,0) and now (3,1)(3,1):

odds=2+10+1⋅1+10+1⋅3+10+1⋅3+11+1=3⋅2⋅4⋅2=48.\begin{aligned} \text{odds}&=\frac{2+1}{0+1}\cdot\frac{1+1}{0+1}\cdot\frac{3+1}{0+1}\cdot\frac{3+1}{1+1}\\ &=3\cdot2\cdot4\cdot2=48 . \end{aligned}

Odds of 4848 to 11 mean P(spam)=4848+1=0.9796P(\text{spam})=\frac{48}{48+1}=0.9796.

Email 7, “are you free for lunch” (the real email that P0.1’s one-word rule blocked). The counts are are (0,1)(0,1), you (0,1)(0,1), free (3,1)(3,1), for (0,1)(0,1) and lunch (0,2)(0,2):

odds=12⋅12⋅42⋅12⋅13=112,\text{odds}=\frac12\cdot\frac12\cdot\frac42\cdot\frac12\cdot\frac13=\frac{1}{12},

so P(spam)=11+12=0.0769P(\text{spam})=\frac{1}{1+12}=0.0769 and the email is ham. “Lunch” alone contributes a factor of 13\frac13. Each word is one vote whose strength is the ratio of its smoothed chances.

The next cell computes the same numbers in code, with logs (explained below), for all eight training emails and five new ones.

Step 3: train, score in log space, classify

Runs real Python in your browser. First run downloads about 6 MB (once; your browser keeps it).

Expected output:

P(prize|spam) = 0.1176
P(prize|ham)  = 0.0294

email 4 log scores: -10.234 -14.105

training: truth, pred, P(spam)
win free prize now     spam spam 0.980
free money now         spam spam 0.889
claim your free prize  spam spam 0.970
win cash prize now     spam spam 0.980
meeting at noon        ham  ham  0.077
lunch now with team    ham  ham  0.143
are you free for lunch ham  ham  0.077
project meeting notes  ham  ham  0.077

new emails: pred, P(spam)
win cash now                 spam 0.923
are you free for the meeting ham  0.077
claim your prize now         spam 0.970
free prize now meeting       spam 0.842
are free lunch now           ham  0.400

The log scores of email 4 are −10.234-10.234 for spam and −14.105-14.105 for ham. Their difference is 3.871=ln⁡483.871=\ln48, the same 4848 as the hand calculation.

Compared with the P0.1 score filter

Both filters get all 8 training emails right and the same 3 new emails right (P0.1’s “win cash now”, “are you free for the meeting” and “claim your prize now”). Getting all of 8 right on the emails it learned from says little (P3.A4). The difference shows on other emails. P0.1’s scores for “are free lunch now” are −1+2−2+2=+1-1+2-2+2=+1, so it says spam. Naive Bayes gives P(spam)=0.400P(\text{spam})=0.400 and says ham.

The reason is how the two filters treat evidence. The score filter subtracts counts, so “now” (3 in spam, 1 in ham) gets +2+2 and “are” (0 in spam, 1 in ham) gets only −1-1. Naive Bayes compares ratios: after smoothing, “now” has ratio 42=2\frac{4}{2}=2 and “are” has ratio 12\frac{1}{2}, the same strength in opposite directions. Neither answer is “the right one” for this email; with eight training emails the data cannot say. It does show that the two filters rank evidence differently. Only the naive Bayes output is a probability that belongs to a model of how emails arise.

The log odds are a sum of word contributions

Take the logarithm of the odds (P1.A2). A product becomes a sum, so the log odds of spam is the log prior odds plus one term per word:

ln⁡p(spam∣x)p(ham∣x)=ln⁡p(spam)p(ham)+∑iln⁡p(xi∣spam)p(xi∣ham).\begin{aligned} &\ln\frac{p(\text{spam}\mid\mathbf{x})}{p(\text{ham}\mid\mathbf{x})}\\ &=\ln\frac{p(\text{spam})}{p(\text{ham})}+\sum_i\ln\frac{p(x_i\mid\text{spam})}{p(x_i\mid\text{ham})}. \end{aligned}

Each term is the log likelihood ratio of one word: positive if the word points to spam, negative if it points to ham, and larger in size for stronger evidence. With α=1\alpha=1 in our data, “prize” has ln⁡41=+1.386\ln\frac{4}{1}=+1.386, “win” ln⁡31=+1.099\ln\frac{3}{1}=+1.099, “free” and “now” ln⁡42=+0.693\ln\frac{4}{2}=+0.693, and “lunch” ln⁡13=−1.099\ln\frac{1}{3}=-1.099. This is the readable part of naive Bayes: you can list exactly which words pushed an email which way. The widget draws these terms as bars.

  • prior 0.00
  • win2 spam, 0 ham +1.10 toward spam
  • cash1 spam, 0 ham +0.69 toward spam
  • prize3 spam, 0 ham +1.39 toward spam
  • now3 spam, 1 ham +0.69 toward spam
total log odds = +3.87
P(spam) = 98.0% → spam

Each bar is n × ln[ P(word | spam) / P(word | ham) ], with n the number of times the word occurs and add-α smoothing. Right (pink, plus sign) points to spam, left (blue, minus sign) to ham. Words missing from the 19-word vocabulary are skipped. The counts come from the eight emails of P0.1.

Try “win cash prize now” first: four pink bars add up to +3.87+3.87, which is 98%98\% spam. Then try:

  • “are you free for lunch”: four blue bars and one short pink bar (“free”) add up to −2.48-2.48, which is 7.7%7.7\%.
  • “free free free free”: a repeated word counts again each time, because the multinomial model counts occurrences. Four copies give 4×0.693=2.774\times0.693=2.77, 94%94\%.
  • The prior slider. At 50%50\% nothing changes. Move it to 1%1\% and “win cash now” drops from 92.3%92.3\% to 10.8%10.8\%, because the prior bar adds −4.60-4.60. The prior is the filter’s starting belief, so it should match the mix of mail the filter will see, which may differ from the training mix (P3.A10 on class imbalance).
  • The α\alpha slider. Raise it and every bar shrinks toward 00. Lower it to 0.10.1 and “win cash prize now” rises to almost 100%100\%.

Why logs are not optional

A real email has hundreds of words, each with a chance such as 0.050.05. The product of 300 such numbers is about 10−39010^{-390}, which is below the smallest positive number a 64-bit float can hold, so the computer stores 00 (this is underflow, P1.G2). Both classes would then be 00 and the comparison is lost. The logarithm of the same product is a perfectly ordinary number, 300ln⁡0.05=−898.7300\ln0.05=-898.7, and logs keep the order of the scores, because ln⁡\ln is increasing. So the rule is used as

c^=arg⁡max⁡c[ln⁡p(c)+∑iln⁡p(xi∣c)].\begin{aligned} \hat c&=\arg\max_c\\ &\quad\Bigl[\ln p(c)+\sum_i\ln p(x_i\mid c)\Bigr]. \end{aligned}

To turn two log scores into a probability, subtract the larger one before exponentiating (the log-sum-exp idea of P1.G2). The next cell shows both effects.

Step 4: underflow, and normalizing log scores

Runs real Python in your browser. First run downloads about 6 MB (once; your browser keeps it).

Expected output:

product : 0.0
log sum : -898.7
exp(ls) = 0.0  exp(lh) = 0.0
P(spam) = 0.9933

Other kinds of features

The model of p(xi∣c)p(x_i\mid c) depends on what the feature is. The three common choices:

  • Multinomial (built here): the email is a bag of words. p(w∣c)p(w\mid c) is the chance that a randomly picked word of a class-cc email is ww, and a word that appears nn times contributes nn times. This is the usual choice for word counts.
  • Bernoulli: each vocabulary word is a yes/no feature, “present in the email” or not. A word’s absence also counts as evidence: for “win cash now” the model multiplies in the chance that every one of the other 16 words is absent. Repeats do not matter. Its smoothed estimate is emails of class c containing w+1emails of class c+2\frac{\text{emails of class } c\text{ containing }w+1}{\text{emails of class } c+2}.
  • Gaussian: for a numeric feature, such as the number of links in an email, assume that within each class the value follows a bell curve (P1.D3). Training estimates one mean and one variance per class and feature (maximum likelihood again), and p(xi∣c)p(x_i\mid c) is the density at the new value.

The Gaussian version in one feature, with made-up link counts for 4 spam and 4 ham emails:

Step 5: Gaussian naive Bayes, one numeric feature

Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).

Expected output:

spam: mean 3.0 variance 0.5
ham : mean 0.5 variance 0.25
density spam 0.2076  density ham 0.0089
P(spam | 2 links) = 0.959

A density is not a probability, but the same density scale applies to both classes, so the comparison is fair. For many numeric features, you multiply one such density per feature, which is where the naive assumption enters again.

Go deeper The Bernoulli model on the same eight emails

With α=1\alpha=1 and 4 emails per class, the Bernoulli probability that “prize” is present is 3+14+2=0.667\frac{3+1}{4+2}=0.667 in spam and 0+16=0.167\frac{0+1}{6}=0.167 in ham. For an email, take the log of that probability for each word that is present and the log of one minus it for each of the 19 words that is absent. The log odds for the four new emails used in the code cell come out as +3.236+3.236, −3.648-3.648, +4.845+4.845 and +2.790+2.790 (probabilities 0.9620.962, 0.0250.025, 0.9920.992 and 0.9420.942), the same four decisions as the multinomial model, but with different confidence. Both models get all eight training emails right.

scikit-learn’s documentation says the Bernoulli model may do better on some data sets, especially those with shorter documents. Treat that as something to test, not a rule.

What naive Bayes is good and bad at

Good.

  • Fast and small. Training is one counting pass over the data. Prediction is one lookup and one addition per word. Adding a new email just updates counts, so the model can learn as mail arrives.
  • Little data. It needs far fewer examples than a model with many interacting parameters, because each word probability is estimated on its own.
  • Many features. A vocabulary of tens of thousands of words is no problem, which is why text is its classic use. Bayesian classifiers for junk e-mail were published in the late 1990s (Sahami and others, 1998).
  • Readable. Every decision splits into per-word contributions, as in the widget.
  • Many classes. The same rule works with any number of classes: compute one score per class and take the largest.

Bad.

  • Repeated evidence. If two features carry the same information, the model counts it twice. Copy every word as a second feature (a “twin” of each word) and email 4’s log odds go from 3.8713.871 to 7.7427.742, and its probability from 0.9800.980 to 0.99960.9996, although no new information arrived. Correlated words in real emails do this in a milder form.
  • Extreme probabilities. Because evidence from many words is added up as if independent, the reported probabilities tend to be pushed toward 0 and 1. The filter’s ranking can be good while the number “98%” is not a trustworthy frequency. With α=0.1\alpha=0.1, five words are enough for P(spam)=0.0001P(\text{spam})=0.0001 for “are you free for lunch”, and with α=5\alpha=5 the same email gets 0.3550.355. Calibration (P3.A10) checks and repairs this. If you only need the class, the extreme numbers do little harm; if you use the probability for a decision, check it.
  • Linear for word counts. For the multinomial and Bernoulli models the log odds are a weighted sum of the features, so the boundary between classes is a flat surface. (Gaussian naive Bayes with different variances per class gets a curved one.) That is fine for text, but it cannot represent a feature combination such as “this word matters only when that one is absent”.
  • A sensitive prior and α\alpha. Both are inherited from the training data or chosen by you, and both change the answers, as the widget shows.

How to judge it

A filter that is right on the emails it was trained on has only memorized them (P3.A3). Split the emails (P3.A4), train on one part, and score the other. For spam, accuracy is not enough: letting a spam through and blocking a real email are not equally costly, so look at precision and recall and move the decision threshold (P3.A9).

Go deeper Why a wrong independence assumption can still give the right class

The class only needs the larger score to belong to the right class, not the scores to be right. Domingos and Pazzani (1997, Machine Learning 29) showed that the simple Bayesian classifier can be optimal for the zero-one loss (counting mistakes) even when the features are strongly dependent, so a wrong independence assumption does not by itself make the classes come out wrong. It can still give very wrong probabilities, as the twin-feature example shows. The result says when it may work, not that it always does.

Go deeper Naive Bayes and logistic regression have the same form

The log odds above are b+∑ini wib+\sum_i n_i\,w_i, with nin_i the count of word ii, weights wi=ln⁡p(i∣spam)p(i∣ham)w_i=\ln\frac{p(i\mid\text{spam})}{p(i\mid\text{ham})} and bb the log prior odds. Logistic regression (P3.A7) has the same form, a weighted sum of the features passed through a sigmoid. The difference is how the weights are found: naive Bayes counts each word separately, logistic regression adjusts all weights together to reduce a loss, so it can give correlated words smaller weights. Ng and Jordan (2001) compared the two: naive Bayes tends to reach its best accuracy with fewer training examples, and logistic regression tends to be better when there is plenty of data.

Go deeper Add-α as a prior, and what scikit-learn adds

Add-α\alpha smoothing is the posterior mean of a Dirichlet prior with every parameter equal to α\alpha (P1.D11). The prior says that all words are equally likely at first and counts for α\alpha imagined occurrences of each. scikit-learn’s MultinomialNB(alpha=1.0) does exactly this, and it also accepts fractional counts, such as TF-IDF weights. GaussianNB adds a tiny var_smoothing to every variance so a feature that never varies does not give a division by zero. ComplementNB and CategoricalNB are further variants.

Intuition

Think of each word as a witness. The prior is where the jury leans before anyone speaks. “Prize” is a strong witness for spam, “lunch” a strong witness for ham, and “now” is a weak one. Each witness votes with a weight, and the weights add up to a verdict.

Where the comparison breaks: real witnesses are independent people. Words in one email are not. If two witnesses are really the same person repeating the claim, the jury counts the vote twice, which is exactly the twin-feature problem.

Math

For classes cc and features x1,…,xdx_1,\dots,x_d:

p(c∣x)∝p(c)∏i=1dp(xi∣c),p(c\mid\mathbf{x})\propto p(c)\prod_{i=1}^d p(x_i\mid c),c^=arg⁡max⁡c[ln⁡p(c)+∑i=1dln⁡p(xi∣c)].\begin{aligned} \hat c&=\arg\max_c\\ &\quad\Bigl[\ln p(c)+\sum_{i=1}^d\ln p(x_i\mid c)\Bigr]. \end{aligned}

Multinomial. With nin_i the count of word ii in the email, ln⁡p(c∣x)=ln⁡p(c)+∑iniln⁡θci+const\ln p(c\mid\mathbf{x})=\ln p(c)+\sum_i n_i\ln\theta_{ci}+\text{const}, where θci=Nci+αNc+αV\theta_{ci}=\dfrac{N_{ci}+\alpha}{N_c+\alpha V}, NciN_{ci} is the count of word ii in class cc and Nc=∑iNciN_c=\sum_iN_{ci}.

Bernoulli. With xi∈{0,1}x_i\in\{0,1\} and θci=Mci+αMc+2α\theta_{ci}=\dfrac{M_{ci}+\alpha}{M_c+2\alpha} (MciM_{ci} emails of class cc containing word ii, McM_c emails of class cc): ln⁡p(x∣c)=∑i[xiln⁡θci+(1−xi)ln⁡(1−θci)]\ln p(\mathbf{x}\mid c)=\sum_i\bigl[x_i\ln\theta_{ci}+(1-x_i)\ln(1-\theta_{ci})\bigr].

Gaussian. p(xi∣c)=12πσci2exp⁡(−(xi−μci)22σci2)p(x_i\mid c)=\dfrac{1}{\sqrt{2\pi\sigma_{ci}^2}}\exp\Bigl(-\dfrac{(x_i-\mu_{ci})^2}{2\sigma_{ci}^2}\Bigr) with μci,σci2\mu_{ci},\sigma_{ci}^2 the class mean and variance of feature ii.

Two classes. The log odds are b+∑iniwib+\sum_in_iw_i with b=ln⁡p(spam)p(ham)b=\ln\frac{p(\text{spam})}{p(\text{ham})} and wi=ln⁡θspam,iθham,iw_i=\ln\frac{\theta_{\text{spam},i}}{\theta_{\text{ham},i}}, and P(spam∣x)=11+e−(b+∑iniwi)P(\text{spam}\mid\mathbf{x})=\dfrac{1}{1+e^{-(b+\sum_in_iw_i)}}.

Parameters. A full joint table for dd binary features needs 2d−12^d-1 numbers per class; naive Bayes needs dd.

Code

The same model in scikit-learn, shown as a static block because scikit-learn is not available in the in-browser runner. The output is from a local run (scikit-learn 1.8.0). CountVectorizer turns each email into word counts, and MultinomialNB counts and smooths them. The probabilities equal the ones from Step 3.

import numpy as np
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.naive_bayes import MultinomialNB

spam = ["win free prize now", "free money now",
        "claim your free prize", "win cash prize now"]
ham = ["meeting at noon", "lunch now with team",
       "are you free for lunch", "project meeting notes"]
texts = spam + ham
y = [1, 1, 1, 1, 0, 0, 0, 0]               # 1 = spam

vec = CountVectorizer()                    # words -> counts
X = vec.fit_transform(texts)
model = MultinomialNB(alpha=1.0).fit(X, y)

print("X shape:", X.shape)
print("priors:", np.exp(model.class_log_prior_))
print("training accuracy:", model.score(X, y))

new = ["win cash now", "are you free for the meeting",
       "claim your prize now", "free prize now meeting"]
proba = model.predict_proba(vec.transform(new))[:, 1]
for e, p in zip(new, proba):
    print(f"{e:29}{p:.4f}")

names = vec.get_feature_names_out()
ratio = model.feature_log_prob_[1] - model.feature_log_prob_[0]
for w in ["prize", "win", "free", "lunch"]:
    print(w, round(float(ratio[list(names).index(w)]), 3))

Output:

X shape: (8, 19)
priors: [0.5 0.5]
training accuracy: 1.0
win cash now                 0.9231
are you free for the meeting 0.0769
claim your prize now         0.9697
free prize now meeting       0.8421
prize 1.386
win 1.099
free 0.693
lunch -1.099

Try it

Use the widget and the cells above.

  1. In Step 3, add a ninth training email, “free cash for lunch”, as ham. Which probabilities move, and does the new-email “win cash now” stay spam?
  2. In the widget, type a sentence of your own that mixes spam and ham words, then move α\alpha from 0.10.1 to 55. At which value does the decision flip, if it does?
  3. In Step 2, change alpha to 0.50.5 and 55 and compare the probabilities for “free prize now meeting”.

Exercises

  1. With α=1\alpha=1 and V=19V=19, find p(lunch∣ham)p(\text{lunch}\mid\text{ham}) and p(lunch∣spam)p(\text{lunch}\mid\text{spam}).
    Show answer“Lunch” appears twice in ham and never in spam, and each class has 15 words. In ham, 2+115+19=334=0.0882\frac{2+1}{15+19}=\frac{3}{34}=0.0882. In spam, 0+134=0.0294\frac{0+1}{34}=0.0294. Their ratio is 33, so ln⁡3=1.099\ln3=1.099 points to ham.
  2. Score “free lunch” by hand with equal priors.
    Show answerFree is (3,1)(3,1) and lunch is (0,2)(0,2). The odds of spam are 3+11+1⋅0+12+1=2⋅13=23\frac{3+1}{1+1}\cdot\frac{0+1}{2+1}=2\cdot\frac13=\frac23, so P(spam)=2/31+2/3=0.4P(\text{spam})=\frac{2/3}{1+2/3}=0.4 and the email is ham. The P0.1 score filter gives +2−2=0+2-2=0, which it calls ham as well (not above 00).
  3. Suppose the real mail is 1% spam. Using a prior of 0.010.01, what does the filter say about “win cash now”, whose odds are 1212 at equal priors?
    Show answerThe prior odds are 0.010.99=199\frac{0.01}{0.99}=\frac{1}{99}, so the posterior odds are 1299\frac{12}{99} and P(spam)=12111=0.108P(\text{spam})=\frac{12}{111}=0.108. It is called ham. The same words are weaker evidence when spam is rare.
  4. A new email repeats “free” four times and has no other known words. Compare the multinomial and Bernoulli models in words.
    Show answerThe multinomial model counts every occurrence, so “free” contributes four times ln⁡2=0.693\ln2=0.693, log odds 2.772.77 and P=0.941P=0.941. The Bernoulli model counts presence only, so the repeats add nothing; the four extra copies cannot make the filter more sure.
  5. How many free numbers does a full table of the chances of 19 yes/no words need per class, and how many does naive Bayes need?
    Show answer219−1=524,2872^{19}-1=524{,}287 for the full table, and 1919 for naive Bayes (one chance per word per class).
  6. In the Gaussian cell, what is P(spam)P(\text{spam}) for an email with 33 links?
    Show answerThe spam density at 33 is 12π⋅0.5=0.5642\frac{1}{\sqrt{2\pi\cdot0.5}}=0.5642. The ham density is e−(2.5)2/(2⋅0.25)2π⋅0.25=e−12.51.2533=3.0×10−6\frac{e^{-(2.5)^2/(2\cdot0.25)}}{\sqrt{2\pi\cdot0.25}}=\frac{e^{-12.5}}{1.2533}=3.0\times10^{-6}. So P(spam)≈0.99999P(\text{spam})\approx0.99999: very sure, because 33 links is far from the ham mean of 0.50.5 in units of the ham’s small spread. A real filter would not trust it that much, which shows how extreme the Gaussian model’s confidence can be.
  7. Suppose you add the ham email “free cash for lunch” (all four words are already in the vocabulary). Why does adding it change the probabilities of emails that do not contain any of its words?
    Show answerThe ham word total NhamN_{\text{ham}} grows from 15 to 19, so the denominator of every smoothed ham probability changes, and the priors become 49\frac49 for spam and 59\frac59 for ham. Every number in the model is a count divided by a total, and those totals moved.

Check your understanding

  1. What does naive Bayes assume is independent?

  2. Why can the evidence p(x)p(\mathbf{x}) be dropped when we only want the predicted class?

  3. A word never appears in the spam training emails. Without smoothing, what happens to an email that contains it?

  4. An email has 300 words, each with probability about 0.050.05 in a class. Why does the filter add logarithms instead of multiplying the probabilities?

  5. Every word feature is copied, so the filter sees each word twice. With equal priors, what happens to the log odds of an email?

Next: P3.A9 gives the numbers (precision, recall, ROC) for judging a filter, and P3.A10 shows how to check and repair its probabilities. P3.A7 builds the discriminative cousin with the same linear log odds. P6.2 uses the same counting and smoothing to predict the next word.

Key takeaways

  • Naive Bayes classifies with Bayes’ rule: p(c∣x)∝p(c) p(x∣c)p(c\mid\mathbf{x})\propto p(c)\,p(\mathbf{x}\mid c). The naive step is to assume the features are independent given the class, so p(x∣c)=∏ip(xi∣c)p(\mathbf{x}\mid c)=\prod_i p(x_i\mid c). A full table over 19 yes/no word features would need 219−1=524,2872^{19}-1=524{,}287 numbers per class; the product needs 19.
  • The rule is c^=arg⁡max⁡c p(c)∏ip(xi∣c)\hat c=\arg\max_c\,p(c)\prod_i p(x_i\mid c). The evidence p(x)p(\mathbf{x}) is the same for every class, so it does not change the winner. In practice add logs, ln⁡p(c)+∑iln⁡p(xi∣c)\ln p(c)+\sum_i\ln p(x_i\mid c), because a product of hundreds of small numbers underflows to 00 (for example 0.05300=00.05^{300}=0 while 300ln⁡0.05=−898.7300\ln0.05=-898.7).
  • Training is counting. On the eight emails of P0.1 the priors are 0.50.5 and 0.50.5, each class has 15 words and the vocabulary has V=19V=19 words. A word’s probability in a class is its count divided by the class’s word total, which is the maximum likelihood estimate.
  • A word never seen in a class would give that class probability 00 for every email containing it. Add-α\alpha smoothing uses n+αN+αV\frac{n+\alpha}{N+\alpha V}. With α=1\alpha=1 the P0.1 email “win cash prize now” has odds 3⋅2⋅4⋅41⋅1⋅1⋅2=48\frac{3\cdot2\cdot4\cdot4}{1\cdot1\cdot1\cdot2}=48, so P(spam)=4849=0.980P(\text{spam})=\frac{48}{49}=0.980.
  • The log odds are a sum of one contribution per word, ln⁡p(xi∣spam)p(xi∣ham)\ln\frac{p(x_i\mid\text{spam})}{p(x_i\mid\text{ham})}, plus the log prior odds. They are linear in the word counts, the same form as logistic regression, with weights found by counting.
  • Multinomial naive Bayes models word counts, Bernoulli models present or absent (absent words count too), and Gaussian models a numeric feature with one mean and variance per class. The lesson builds the multinomial filter.
  • It is fast and works with little data, but correlated features count the same evidence twice (copying every feature doubles the log odds, taking 0.980 to 0.9996) and the probabilities are often too extreme. Judge it on held-out data, not on the emails it was trained on.
Found a mistake? Tell us