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
- Count the rows of each class and set the log prior from the class shares, or use equal priors when fit_prior is false.
- For kind gaussian, store the mean and variance of every feature within every class, adding a small amount to each variance for stability.
- 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.
- To predict, add the log prior and the log likelihood of every feature for each class. Working in logs avoids multiplying many tiny numbers.
- 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
- 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
| If | Use instead |
|---|---|
| You need well calibrated probabilities | Logistic regression |
| Features are strongly correlated or interact | A random forest or gradient boosted trees |
| You have a large labelled text corpus and need the best accuracy | A fine-tuned Transformer model |
Math foundations
Bayes' rule
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.
The naive assumption
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.
The decision rule
The denominator is the same for all classes, so it can be dropped. Sums of logs replace products. This is what joint_log_likelihood returns.
Gaussian likelihood
For real-valued features. and are the mean and variance of feature among the rows of class .
Multinomial likelihood with smoothing
For counts. is the share of class 's total count that falls on feature . Adding to every count keeps unseen features from getting probability zero.
Bernoulli likelihood with smoothing
For present or absent features. Unlike the multinomial form, a feature that is absent also counts as evidence, through the factor .
Symbols
- a class
- feature vector and its j-th feature
- number of features
- prior: the share of training rows in class c
- mean and variance of feature j within class c
- total count of feature j over the rows of class c
- total count of all features over the rows of class c
- number of rows of class c in which feature j is present
- number of rows of class c
- estimated probability of feature j in class c
- additive (Laplace) smoothing
Worked by hand
Bernoulli model, . 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.
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
- 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.
- 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.
- 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.
- 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.