Sign in

Naive Bayes

Naive Bayes classifier

A classifier that applies Bayes' rule with the simplifying assumption that the features are independent of one another once the class is known.

Overview

To decide whether an email is spam, you could ask how likely each of its words is in spam and in normal mail, and combine that with how common spam is overall. Naive Bayes does exactly this. It learns, for each class, how each feature behaves on its own, and at prediction time it multiplies those per-feature likelihoods together with the class prior. Treating the features as independent is rarely true, which is why it is called naive. The simplification means training is a single pass of counting or averaging, with no iterative optimisation.

A short history

The classifier rests on Bayes' theorem, published in 1763 after the death of Thomas Bayes. Its use for classifying text dates from work on automatic document indexing in the early 1960s. It became widely known through spam filtering: a 1998 paper by Mehran Sahami and colleagues, and Paul Graham's 2002 essay A Plan for Spam, showed that counting words per class and multiplying probabilities works surprisingly well, even though words are not truly independent.

How it works

  1. Count the rows of each class and set the log prior log⁡P(c)\log P(c) from the class shares, or use equal priors when fit_prior is false.
  2. For kind gaussian, store the mean and variance of every feature within every class, adding a small amount to each variance for stability.
  3. For kind multinomial, store smoothed shares of each feature's total count within each class. For kind bernoulli, store the smoothed share of the class's rows in which each feature is present.
  4. To predict, add the log prior and the log likelihood of every feature for each class. Working in logs avoids multiplying many tiny numbers.
  5. Pick the class with the largest total, or normalise the totals into probabilities with predict_proba.

Watch out for

  • Correlated features are counted as separate evidence, so the predicted probabilities are pushed toward 0 and 1 and are poorly calibrated even when the chosen class is right.
  • With alpha at 0, a feature never seen with a class gets probability zero and vetoes that class no matter what the other features say.
  • The gaussian kind assumes each feature is bell-shaped within a class. Heavily skewed or multi-peaked features fit badly and should be transformed first.
  • Choosing the wrong kind for the data, such as multinomial on standardised features with negative values, is an error or gives meaningless likelihoods.

Use cases

When to use it

Text classification with word counts, and any problem with many features and little data where a fast, simple baseline is needed. It trains in one pass and copes well with thousands of features.

In industry

Email
Spam filtering from word frequencies, with the filter updated cheaply as users mark new messages.
Media and support
Fast first-pass text classification, such as tagging articles by topic or routing tickets.
Healthcare
Simple diagnostic aids that combine the evidence from several findings, where each probability can be inspected.

Choosing it: what must hold

  • Features that are roughly independent within each class, or a task where rough probabilities are acceptable.
  • Count or category features (for the multinomial form) or roughly bell-shaped numeric features (for the Gaussian form).
  • Smoothing for feature values never seen with a class, so that one zero does not wipe out the product.

When to choose something else

IfUse instead
You need well calibrated probabilitiesLogistic regression
Features are strongly correlated or interactA random forest or gradient boosted trees
You have a large labelled text corpus and need the best accuracyA fine-tuned Transformer model

Math foundations

  1. Bayes' 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})}

    The probability of a class given the features, written in terms of things that can be estimated: how common the class is and how likely these features are within it.

  2. The naive assumption

    P(x∣c)=∏j=1dP(xj∣c)P(\mathbf{x} \mid c) = \prod_{j=1}^{d} P(x_j \mid c)

    Features are treated as independent given the class, so the joint likelihood splits into one simple factor per feature. This is what makes the model cheap to fit.

  3. The decision rule

    c^=arg⁡max⁡c[log⁡P(c)+∑j=1dlog⁡P(xj∣c)]\hat{c} = \arg\max_{c} \left[ \log P(c) + \sum_{j=1}^{d} \log P(x_j \mid c) \right]

    The denominator P(x)P(\mathbf{x}) is the same for all classes, so it can be dropped. Sums of logs replace products. This is what joint_log_likelihood returns.

  4. Gaussian likelihood

    P(xj∣c)=12πσcj2exp⁡ ⁣(−(xj−μcj)22σcj2)P(x_j \mid c) = \frac{1}{\sqrt{2\pi \sigma_{cj}^2}} \exp\!\left(-\frac{(x_j - \mu_{cj})^2}{2\sigma_{cj}^2}\right)

    For real-valued features. μcj\mu_{cj} and σcj2\sigma^2_{cj} are the mean and variance of feature jj among the rows of class cc.

  5. Multinomial likelihood with smoothing

    θcj=Ncj+αNc+αd,log⁡P(x∣c)=∑j=1dxjlog⁡θcj+const\theta_{cj} = \frac{N_{cj} + \alpha}{N_c + \alpha d}, \qquad \log P(\mathbf{x} \mid c) = \sum_{j=1}^{d} x_j \log \theta_{cj} + \text{const}

    For counts. θcj\theta_{cj} is the share of class cc's total count that falls on feature jj. Adding α\alpha to every count keeps unseen features from getting probability zero.

  6. Bernoulli likelihood with smoothing

    θcj=ncj+αnc+2α,P(xj∣c)=θcjxj(1−θcj)1−xj\theta_{cj} = \frac{n_{cj} + \alpha}{n_c + 2\alpha}, \qquad P(x_j \mid c) = \theta_{cj}^{x_j} (1 - \theta_{cj})^{1 - x_j}

    For present or absent features. Unlike the multinomial form, a feature that is absent also counts as evidence, through the factor 1−θcj1 - \theta_{cj}.

Symbols

cc
a class
x,xj\mathbf{x}, x_j
feature vector and its j-th feature
dd
number of features
P(c)P(c)
prior: the share of training rows in class c
μcj,σcj2\mu_{cj}, \sigma_{cj}^2
mean and variance of feature j within class c
NcjN_{cj}
total count of feature j over the rows of class c
NcN_c
total count of all features over the rows of class c
ncjn_{cj}
number of rows of class c in which feature j is present
ncn_c
number of rows of class c
θcj\theta_{cj}
estimated probability of feature j in class c
α\alpha
additive (Laplace) smoothing

Worked by hand

Bernoulli model, α=1\alpha = 1. There are 3 spam and 3 normal emails. The word free appears in 2 of the spam emails and in none of the normal ones. A new email contains the word free, and we use only that one feature.

P(free∣spam)=2+13+2=0.6,P(free∣normal)=0+13+2=0.2P(\text{free} \mid \text{spam}) = \frac{2 + 1}{3 + 2} = 0.6, \qquad P(\text{free} \mid \text{normal}) = \frac{0 + 1}{3 + 2} = 0.2
P(spam) P(free∣spam)=0.5×0.6=0.30P(\text{spam})\,P(\text{free} \mid \text{spam}) = 0.5 \times 0.6 = 0.30
P(normal) P(free∣normal)=0.5×0.2=0.10P(\text{normal})\,P(\text{free} \mid \text{normal}) = 0.5 \times 0.2 = 0.10
P(spam∣free)=0.300.30+0.10=0.75P(\text{spam} \mid \text{free}) = \frac{0.30}{0.30 + 0.10} = 0.75

The email is spam with probability 0.75. Without smoothing the normal class would have likelihood zero and the answer would be a certain 1, from only six emails.

Visual example

Loading the example.

Try this

  • Each class is one bell shape per axis. Try the circles data to see where that fails.
  • Add a tight cluster: its class becomes very sure of itself nearby.

Code sample

import numpy as np
from impl import NaiveBayes
from config import NaiveBayesConfig

# word counts for the vocabulary ["free", "win", "meeting", "report"]
X = np.array([[3, 2, 0, 0], [2, 1, 0, 1], [0, 0, 2, 3], [0, 1, 3, 1]])
y = np.array(["spam", "spam", "ham", "ham"])
model = NaiveBayes(NaiveBayesConfig(kind="multinomial")).fit(X, y)
print(model.predict(np.array([[1, 1, 0, 0]])))              # ['spam']
print(model.predict_proba(np.array([[1, 1, 0, 0]])))        # columns follow model.classes_ = ['ham', 'spam']
Read the implementation (101 lines)
"""Naive Bayes classifier with Gaussian, multinomial or Bernoulli feature likelihoods.

NumPy only. For every class c the model stores log P(c) and the parameters of P(x_j | c) for each feature j.
Prediction adds the per-feature log likelihoods (the "naive" independence assumption) to the log prior.
"""
from __future__ import annotations

import numpy as np

try:
    from .config import NaiveBayesConfig
except ImportError:  # run from the template's own folder
    from config import NaiveBayesConfig


class NaiveBayes:
    """Naive Bayes. After `fit`: `classes_` (C,), `class_log_prior_` (C,), and the likelihood parameters."""

    def __init__(self, config: NaiveBayesConfig | None = None) -> None:
        self.config = config or NaiveBayesConfig()
        self.classes_: np.ndarray | None = None
        self.class_log_prior_: np.ndarray | None = None
        self.theta_: np.ndarray | None = None  # gaussian: per-class feature means, shape (C, d)
        self.var_: np.ndarray | None = None  # gaussian: per-class feature variances, shape (C, d)
        self.feature_log_prob_: np.ndarray | None = None  # multinomial / bernoulli: log P(feature | class), (C, d)

    def fit(self, X: np.ndarray, y: np.ndarray) -> "NaiveBayes":
        """Estimate priors and likelihood parameters.

        X: shape (n, d). Real values for `gaussian`, non-negative counts for `multinomial`, 0/1 (anything > 0
        counts as present) for `bernoulli`. y: labels of any hashable type, shape (n,).
        """
        X = np.asarray(X, dtype=float)
        y = np.asarray(y)
        if X.ndim != 2 or len(X) != len(y):
            raise ValueError("X must have shape (n, d) and y must have n entries")
        kind = self.config.kind
        if kind == "multinomial" and (X < 0).any():
            raise ValueError("multinomial naive Bayes needs non-negative counts")
        self.classes_, y_index = np.unique(y, return_inverse=True)
        n_classes = len(self.classes_)
        class_count = np.bincount(y_index, minlength=n_classes).astype(float)
        if self.config.fit_prior:
            self.class_log_prior_ = np.log(class_count / class_count.sum())
        else:
            self.class_log_prior_ = np.full(n_classes, -np.log(n_classes))
        one_hot = np.eye(n_classes)[y_index]  # (n, C)
        if kind == "gaussian":
            self.theta_ = one_hot.T @ X / class_count[:, None]
            second_moment = one_hot.T @ X**2 / class_count[:, None]
            self.var_ = second_moment - self.theta_**2 + self.config.var_smoothing * X.var(axis=0).max()
            self.var_ = np.maximum(self.var_, 1e-300)
        elif kind == "multinomial":
            counts = one_hot.T @ X + self.config.alpha  # (C, d) smoothed feature totals per class
            with np.errstate(divide="ignore"):
                self.feature_log_prob_ = np.log(counts) - np.log(counts.sum(axis=1, keepdims=True))
        else:
            present = one_hot.T @ (X > 0) + self.config.alpha  # (C, d) rows of the class that have the feature
            with np.errstate(divide="ignore"):
                self.feature_log_prob_ = np.log(present) - np.log(class_count[:, None] + 2.0 * self.config.alpha)
        return self

    def joint_log_likelihood(self, X: np.ndarray) -> np.ndarray:
        """log P(c) + log P(x | c) for every row and class. X: (n, d). Returns shape (n, C)."""
        if self.classes_ is None:
            raise RuntimeError("call fit before predicting")
        X = np.asarray(X, dtype=float)
        kind = self.config.kind
        if kind == "gaussian":
            diff = X[:, None, :] - self.theta_[None, :, :]  # (n, C, d)
            log_pdf = -0.5 * (np.log(2.0 * np.pi * self.var_)[None] + diff**2 / self.var_[None])
            return self.class_log_prior_ + log_pdf.sum(axis=2)
        if kind == "multinomial":
            with np.errstate(invalid="ignore"):
                terms = np.where(X[:, None, :] == 0, 0.0, X[:, None, :] * self.feature_log_prob_[None])
            return self.class_log_prior_ + terms.sum(axis=2)
        present = (X > 0).astype(float)
        log_p = self.feature_log_prob_
        with np.errstate(divide="ignore"):
            log_not_p = np.log1p(-np.exp(log_p))
        log_p = np.maximum(log_p, -1e300)  # keep 0 * log(0) at 0 when alpha is 0
        log_not_p = np.maximum(log_not_p, -1e300)
        return self.class_log_prior_ + present @ log_p.T + (1.0 - present) @ log_not_p.T

    def predict_log_proba(self, X: np.ndarray) -> np.ndarray:
        """log P(c | x). X: (n, d). Returns shape (n, C), columns follow `classes_`."""
        joint = self.joint_log_likelihood(X)
        top = joint.max(axis=1, keepdims=True)
        return joint - (top + np.log(np.exp(joint - top).sum(axis=1, keepdims=True)))

    def predict_proba(self, X: np.ndarray) -> np.ndarray:
        """P(c | x). X: (n, d). Returns shape (n, C); rows sum to 1."""
        return np.exp(self.predict_log_proba(X))

    def predict(self, X: np.ndarray) -> np.ndarray:
        """Most probable label for each row. X: (n, d). Returns shape (n,), values from `classes_`."""
        return self.classes_[self.joint_log_likelihood(X).argmax(axis=1)]

    def score(self, X: np.ndarray, y: np.ndarray) -> float:
        """Accuracy: the share of rows whose predicted label equals y."""
        return float((self.predict(X) == np.asarray(y)).mean())
Repository
Not published yet
Needs
Python 3.10 and NumPy
Tests
8, run with python3 -m unittest -v

Practice

Build a small word-count matrix for two topics by hand, about ten documents and eight words. Fit NaiveBayes with NaiveBayesConfig kind set to multinomial and alpha 1.0, then again with alpha 0. Call predict_proba on a document that contains one word never seen in the first topic and compare the two answers. Inspect feature_log_prob_ to see which entries changed.

Check on learning

  1. Suppose one word appears twice in your feature list by mistake. How does that change the model's predictions and its confidence?
    A way to think about it

    The model treats the two copies as independent evidence. Follow what happens to the log likelihood sum, and so to the gap between classes.

  2. Naive Bayes often picks the right class even though its probabilities are badly off. How can both be true?
    A way to think about it

    The decision only needs the correct class to have the largest total. Overcounting evidence stretches the totals apart but often leaves their order unchanged.

  3. With a tiny training set, would you expect naive Bayes or logistic regression to do better, and why might that reverse with a lot of data?
    A way to think about it

    Count how many numbers each model estimates and how directly. A strong assumption helps when data is scarce and holds the model back when data is plentiful.

  4. When would you pick the bernoulli kind over the multinomial kind for text?
    A way to think about it

    Think about short messages versus long documents, and about whether the absence of a word should count as evidence.