Naive Bayes

Combine a prior belief with the evidence from each feature, assuming the features are independent, to get a fast and surprisingly strong classifier.

Lesson 32 of 6613 minIntermediate

You will learn to

  • Explain how naive Bayes multiplies a prior by the likelihood of each feature to score a class
  • State the independence assumption and what happens when it is wrong
  • Say when naive Bayes is a good quick baseline and why its probabilities need care

Before this lesson

Intuition

A doctor sees a patient with a fever and a cough. She starts from how common each illness is (the prior), then asks how often each illness causes a fever and how often each causes a cough (the evidence). An illness that is common and explains both symptoms wins.

Naive Bayes does exactly this with numbers. For every class it starts from the share of that class in the training data and multiplies in, one by one, how typical each feature value is for that class. The class with the largest result is the prediction.

The "naive" part is a simplifying assumption: given the class, the features are treated as independent of each other. That is almost never true (a fever and a cough often come together), but the assumption makes the model extremely cheap. It only needs to count or average each feature separately within each class. The model trains in a single pass, works with very few rows and handles many features. Its predicted ranking of classes is often good even when its probabilities are not.

Picture it

prior x likelihoodsSpam0.15prior 0.40 x P(free) 0.75 x P(invoice) 0.500.82Not spam0.033prior 0.60 x P(free) 0.17 x P(invoice) 0.330.18after normalising
Naive Bayes multiplies the prior and one likelihood per clue for each class. Here the spam score is about four and a half times the not-spam score.

Each class gets a score that is a product of small numbers. Only the relative size of the scores matters, so at the end they are divided by their sum to give probabilities.

The math

Bayes' rule gives the probability of a class cc for a row with features x1,…,xpx_1, \dots, x_p:

P(c∣x)=P(c) P(x1,…,xp∣c)P(x)P(c \mid x) = \frac{P(c)\, P(x_1, \dots, x_p \mid c)}{P(x)}

The naive assumption splits the joint likelihood into a product of one factor per feature:

P(c∣x)  ∝  P(c)∏j=1pP(xj∣c)P(c \mid x) \;\propto\; P(c)\prod_{j=1}^{p} P(x_j \mid c)

The symbol ∝\propto means "proportional to": the denominator P(x)P(x) is the same for all classes, so it is dropped while ranking and recovered by normalising at the end. In practice the product is computed as a sum of logarithms to avoid numbers that are too small.

How P(xj∣c)P(x_j \mid c) is estimated depends on the feature type. For words or categories it is a (smoothed) count: the share of rows of class cc that contain the value. For a numeric feature, Gaussian naive Bayes assumes a normal distribution inside each class and learns its mean μc\mu_c and standard deviation σc\sigma_c:

P(xj∣c)=12π σcexp⁡ ⁣(−(xj−μc)22σc2)P(x_j \mid c) = \frac{1}{\sqrt{2\pi}\,\sigma_c}\exp\!\left(-\frac{(x_j-\mu_c)^2}{2\sigma_c^2}\right)

Smoothing keeps a never-seen value from giving a likelihood of exactly zero. For counts, a common fix is to add 1 to each count.

Worked example

Ten emails: 4 are spam and 6 are not. The word "free" appears in 3 of the 4 spam emails and in 1 of the 6 others. The word "invoice" appears in 2 of the 4 spam emails and in 2 of the 6 others. A new email contains both words.

  • Spam: prior 4/10 = 0.40; likelihoods 3/4 = 0.75 and 2/4 = 0.50. The score is 0.40 x 0.75 x 0.50 = 0.150.
  • Not spam: prior 6/10 = 0.60; likelihoods 1/6 = 0.167 and 2/6 = 0.333. The score is 0.60 x 0.167 x 0.333 = 0.0333.

Normalising: 0.150 / (0.150 + 0.0333) = 0.82. The model gives the new email an 82% probability of being spam.

For a numeric feature, suppose class A has mean 4 and standard deviation 1, class B has mean 8 and standard deviation 2, and both have a prior of 0.5. For x = 5 the densities are 0.242 for A (one standard deviation away) and 0.065 for B (1.5 standard deviations away). The posterior for A is 0.242 / (0.242 + 0.065) = 0.79.

Finally, a computed number: on a sample dataset with 768 rows, Gaussian naive Bayes scored an accuracy of 0.755 in 5-fold stratified cross-validation in scikit-learn (seed 42), close to logistic regression at 0.775 and for almost no training time. When a baseline gets this close, ask whether the extra complexity of a bigger model is worth it.

How mlflow does it

The classification algorithm is Naive Bayes (nb), the Gaussian version, so it expects numeric features (encode categories first). Its single tunable parameter is var_smoothing, a small number added to the variances for numerical stability; the default is almost always fine. There is no Naive Bayes for regression. Because the independence assumption often makes probabilities too extreme, look at the calibration plot before using them as risks.

Common mistakes

  • Trusting the probabilities. Correlated features are counted twice, so probabilities are often too close to 0 or 1. Use the ranking, or calibrate the output.
  • Feeding it many near-duplicate columns. They multiply the same evidence. Remove redundant features first.
  • Assuming a numeric column is bell-shaped. The Gaussian version fits a normal curve per class. Strongly skewed columns may need a transformation such as a log.
  • Expecting it to beat tuned models on large data. With plenty of data, models that learn interactions usually win. Use naive Bayes as a quick baseline, or when data is scarce.
  • Forgetting smoothing with counts. A single unseen value should not veto a class. Make sure smoothing is on.

Try it in mlflow

Use Naive Bayes as a fast baseline

  1. Open Pipelines and pick a classification pipeline.
  2. Open the Models part and add Naive Bayes and Logistic Regression.
  3. Click Train 2 algorithms and open the run.
  4. Compare the cross-validated scores and the training times. Check the calibration plot of Naive Bayes before trusting its probabilities.
Open in mlflow

Read in the docs

Check your understanding

  1. 1. What does the word naive refer to in naive Bayes?
  2. 2. A spam filter has seen the word 'prize' only in spam emails, never in other emails. Without smoothing, what happens to a new email with 'prize'?
  3. 3. Two features are almost copies of each other. What is the effect on naive Bayes?