Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Naive Bayes

ProblemClassify by Bayes’ theorem, modelling each class’s features as independent given the class
Devised byThomas Bayes (1763) and Pierre-Simon Laplace (1774), inverse probability; Melvin Maron (1961), text classification; Pedro Domingos and Michael Pazzani (1997), why the independence assumption does little harm; Andrew Ng and Michael Jordan (2002), generative against discriminative learning
AccuracyOptimal when the features really are conditionally independent; otherwise often close (figures below)
CostTraining , a single pass; prediction per point
Read firstFoundations: models, data, preprocessing and metrics
APIGaussianNaiveBayes (predict_proba, joint_log_likelihood), MultinomialNaiveBayes

Overview

Bayes’ theorem turns a model of how each class generates data into a classifier: . Estimating the joint density in many dimensions is hopeless, so naive Bayes assumes the features are independent within each class, , and estimates one-dimensional distributions per class instead. The assumption is almost never true, yet the classifier works well, especially for text, where the features are word counts in thousands of dimensions. It trains in a single pass over the data and is a generative model: it describes the data, not just the boundary.

Where it is used

Naive Bayes works surprisingly well when data are scarce and features many.

  • Spam filtering and text classification. The classic application: word counts classify email, news and support tickets.
  • Medical screening and diagnosis. Combining independent test results into a posterior probability.
  • Fast baselines. It trains in one pass and is a quick benchmark for more elaborate classifiers.

History

Thomas Bayes’s essay (published posthumously in 1763) and Pierre-Simon Laplace (1774) founded inverse probability. Melvin Maron (1961) used the independence model to classify documents automatically, and it became the standard spam filter after Paul Graham’s “A plan for spam” (2002). Pedro Domingos and Michael Pazzani (1997) explained its success: the classifier only needs the largest posterior to be right, not the probabilities, and that survives strong dependence. Andrew Ng and Michael Jordan (2002) compared it with logistic regression, its discriminative counterpart, and showed that naive Bayes approaches its (higher) asymptotic error much faster, in a number of samples logarithmic rather than linear in the dimension.

The idea

Gaussian naive Bayes

Bayes’ rule. A classifier needs , the probability of class given the features. Bayes’ rule expresses it through quantities that are easier to estimate:

is the prior, how common the class is; is the likelihood, how typical these features are of the class. The denominator is the same for every class, so it does not affect which class is most probable.

The naive assumption. Estimating as a joint distribution over all the features would need enormous amounts of data. Naive Bayes assumes that, within a class, the features are independent, so that the joint probability is a product of one-dimensional ones: . Each factor involves a single feature and is easy to estimate. The assumption is rarely true (hence “naive”), but the classifier often works well anyway, because it only needs to rank the classes correctly, not to get the probabilities right.

Gaussian features. For continuous features, each is modelled as a normal distribution, with the mean and variance of feature among the training points of class . The prior is the fraction of training points in the class. Training is just the computation of these averages.

Prediction. Multiplying many small probabilities underflows, so the computation is done in logarithms, where the product becomes a sum. Taking the logarithm of Bayes’ rule with the normal densities substituted,

and the predicted class is the one with the largest value. Each feature contributes a penalty that grows with the squared distance of from the class mean, measured in units of the class’s standard deviation.

The expression is quadratic in , and since each class has its own variances the quadratic terms do not cancel when two classes are compared: the boundaries between classes are curved (quadratic). A small fraction of the largest feature variance (var_smoothing, ) is added to every variance so that a constant feature cannot cause a division by zero.

When independence fails

With two classes sharing a correlated covariance, the optimal boundary is a line along the correlation. Naive Bayes, ignoring the correlation, tilts its boundary; logistic regression, which models the boundary directly, finds the right one:

Figure 11.5. Naive Bayes on correlated features.

classifiertest accuracy
optimal (true distributions)0.939
Gaussian naive Bayes0.925
logistic regression0.940

The cost of the wrong assumption here is 1.4 percentage points of accuracy.

Multinomial naive Bayes for counts

For text, the features are counts: is the number of times word of the vocabulary occurs in a document. The natural model is that a document of class is produced by drawing words independently, word with probability . The probability of the document is then a multinomial, and its logarithm is

Each occurrence of a word adds to the score of class : words that are common in a class count as evidence for it. The score is a linear function of the counts, so the classifier is linear.

The obvious estimate of is the fraction of all the words in the training documents of class that are word , . It has a fatal flaw: a word that never occurred in a class gets probability zero, its logarithm is , and a single such word vetoes the class however strong the other evidence. Laplace smoothing adds a small pseudo-count to every word,

where is the size of the vocabulary, so that no probability is zero.

Generative against discriminative

Naive Bayes is a generative classifier: it models how the features of each class are produced, and derives the class probabilities from that model. Logistic regression is discriminative: it models the class probabilities directly and says nothing about how the features arise. The two have complementary strengths.

Naive Bayes estimates each parameter from simple averages, so it reaches its best performance with few examples; logistic regression needs more data to pin down its weights, but is not limited by a wrong model. On documents of 12 words from two overlapping topics:

Figure 11.6. Learning curves.

Naive Bayes is ahead at every size up to a thousand documents, the regime Ng and Jordan describe; here the documents really are generated word by word independently, so its model is correct and its advantage persists.

Algorithm

Fit.

  1. Count the training points in each class; the log prior of a class is the logarithm of its share.
  2. Gaussian: for each class and feature, compute the mean and the variance of that feature over the points of the class, and add the smoothing term to every variance.
  3. Multinomial: for each class, add up the counts of each word over the documents of the class, and compute the smoothed log probabilities .

Fitting is a single pass over the data, .

Predict, for one point :

  1. for each class, compute the score: the log prior plus the sum over the features of the per-feature log-likelihood (the Gaussian log-density, or );
  2. to classify, return the class with the largest score;
  3. to obtain probabilities, subtract the largest score from all of them, exponentiate, and divide by the sum. Subtracting the maximum first keeps the exponentials from underflowing to zero for all classes at once.

Implementation

    /// Joint log-likelihood `log P(class) + Σ log P(x_j | class)` as a `(rows, classes)` matrix.
    pub fn joint_log_likelihood(&self, x: VR2D) -> Result<R2D, ErrorsJSL> {
        if self.mean.is_empty() {
            return Err(ErrorsJSL::Misconfiguration("The model has not been fitted."));
        }
        check_features(x)?;
        if x.ncols() != self.mean[0].len() {
            return Err(ErrorsJSL::IncompatibleArraySizes((x.ncols(), self.mean[0].len())));
        }
        Ok(R2D::from_shape_fn((x.nrows(), self.mean.len()), |(i, c)| {
            self.log_prior[c]
                - 0.5
                    * (0..x.ncols())
                        .map(|j| (std::f64::consts::TAU * self.var[c][j]).ln() + (x[[i, j]] - self.mean[c][j]).powi(2) / self.var[c][j])
                        .sum::<f64>()
        }))
    }
  • Every label in must occur in the training data.
  • With alpha = 0 an unseen word rules a class out, but only when it occurs in the document; absent words contribute nothing. (Before this chapter was written, they produced and dropped the class from every vote.)

In practice

//! Spam filtering with multinomial naive Bayes on word counts.

use lib_jsl_core::R2D;
use lib_jsl_machine_learning::common::Classifier;
use lib_jsl_machine_learning::supervised::classification::MultinomialNaiveBayes;

fn main() {
    let vocabulary = ["free", "winner", "money", "meeting", "report", "lunch", "click", "project"];
    // Word counts of ten training e-mails; label 1 is spam.
    let counts = [
        [2.0, 1.0, 1.0, 0.0, 0.0, 0.0, 2.0, 0.0],
        [1.0, 2.0, 2.0, 0.0, 0.0, 0.0, 1.0, 0.0],
        [3.0, 0.0, 1.0, 0.0, 0.0, 1.0, 2.0, 0.0],
        [0.0, 1.0, 3.0, 0.0, 0.0, 0.0, 1.0, 0.0],
        [1.0, 1.0, 0.0, 0.0, 0.0, 0.0, 3.0, 0.0],
        [0.0, 0.0, 0.0, 2.0, 1.0, 0.0, 0.0, 2.0],
        [0.0, 0.0, 1.0, 1.0, 2.0, 0.0, 0.0, 1.0],
        [1.0, 0.0, 0.0, 1.0, 0.0, 2.0, 0.0, 1.0],
        [0.0, 0.0, 0.0, 3.0, 1.0, 1.0, 0.0, 2.0],
        [0.0, 0.0, 0.0, 0.0, 2.0, 1.0, 0.0, 3.0],
    ];
    let labels = [1, 1, 1, 1, 1, 0, 0, 0, 0, 0];
    let x = R2D::from_shape_fn((10, 8), |(i, j)| counts[i][j]);
    let mut model = MultinomialNaiveBayes::new(1.0);
    model.fit(x.view(), &labels).unwrap();
    let messages = [("free lunch meeting", [1.0, 0.0, 0.0, 1.0, 0.0, 1.0, 0.0, 0.0]), ("click to claim money, winner", [0.0, 1.0, 1.0, 0.0, 0.0, 0.0, 1.0, 0.0]), ("project report", [0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 1.0])];
    let rows = R2D::from_shape_fn((3, 8), |(i, j)| messages[i].1[j]);
    for ((text, _), label) in messages.iter().zip(model.predict(rows.view()).unwrap()) {
        println!("{text:<30} -> {}", if label == 1 { "spam" } else { "not spam" });
    }
    println!("vocabulary: {}", vocabulary.join(", "));
}
free lunch meeting             -> not spam
click to claim money, winner   -> spam
project report                 -> not spam
vocabulary: free, winner, money, meeting, report, lunch, click, project

Strengths

  • Trains in one pass, predicts in ; handles thousands of features and little data.
  • Probabilistic and generative; works for text.

Weaknesses

  • The independence assumption distorts probabilities (they are typically too confident) and can misplace the boundary.
  • Gaussian features only, or counts; no Bernoulli or categorical variants.

Exercises

  1. Show that Gaussian naive Bayes with variances shared across classes has linear decision boundaries.
  2. Show that multinomial naive Bayes is a linear classifier in the word counts, and write down its weights.
  3. Duplicate a feature times and show how naive Bayes’s posterior changes. Why does the predicted class often not?
  4. Derive the Laplace-smoothed estimate as the posterior mean under a Dirichlet prior.
Hints and answers
  1. With shared variance , the log posterior ratio has its terms cancel, leaving a function linear in .
  2. The log posterior is , which is linear in the counts with weights ; the boundary between two classes has weights .
  3. A feature repeated times contributes times its log-likelihood ratio, so the posterior becomes overconfident (it moves towards 0 or 1). The predicted class changes only if the repeated feature’s evidence flips the sign of the total, which happens only when the other evidence is close to tied.
  4. With a Dirichlet prior on the word probabilities and counts of words, the posterior mean is ; Laplace smoothing is .

Further reading

  • P. Domingos and M. Pazzani, “On the optimality of the simple Bayesian classifier under zero-one loss”, Machine Learning 29 (1997) 103–130.
  • A. Y. Ng and M. I. Jordan, “On discriminative vs. generative classifiers: a comparison of logistic regression and naive Bayes”, Advances in Neural Information Processing Systems 14 (2002).
  • C. D. Manning, P. Raghavan and H. Schütze, Introduction to Information Retrieval, Cambridge University Press, 2008, chapter 13.