Start with an uncertain decision
An inbox receives a new message containing the words “limited offer.” Should it be marked as spam? One clue is not enough: legitimate shops also send promotions, and spam messages sometimes contain ordinary language.
A probabilistic classifier weighs evidence for different possible labels. Instead of declaring that a phrase always means spam, it estimates how likely the message is to belong to each class based on patterns in training examples. Bayes’ theorem provides a way to update an initial belief after observing evidence.
Naive Bayes makes this calculation manageable by treating features as independent once the class is known. In a text example, it acts as though the words contribute separately after we know whether a message is spam. That assumption is rarely literally true, since words occur together in phrases, but the resulting classifier is often effective and fast.
To understand the method, separate three ideas: prior probability (how common spam was before seeing the message), likelihood (how common the observed words are within each class), and posterior probability (the updated belief after observing those words). The formal equations and worked example below make that distinction precise.
Probabilistic classification uses a model of uncertainty to estimate how strongly available evidence supports different classes. Rather than only choosing a label, a probabilistic classifier computes a score or probability for each possible class. Naive Bayes is a family of classifiers that applies Bayes’ theorem while assuming that input features are conditionally independent given the class.
Naive Bayes is simple, computationally efficient, and useful as a baseline, particularly in text classification. Its independence assumption is often unrealistic, but the classifier can still make useful predictions.
1. Classification as probabilistic reasoning
In a classification problem, the input is a feature vector , and the output is one of several class labels . For example, an email classifier might decide whether a message is spam or not spam.
A probabilistic classifier estimates a posterior class probability:
This represents the model’s probability for class after observing the features . A common decision rule selects the class with the largest posterior probability:
This is the maximum a posteriori (MAP) decision rule. A probability estimate and a decision are different things: the estimate describes uncertainty, while the decision also depends on the cost of different errors. In an important application, the best decision threshold may not simply be the class with the largest probability.
2. Bayes’ theorem
Bayes’ theorem connects the probability of a class before observing data with its probability after observing evidence:
| Term | Name | Meaning |
|---|---|---|
| Prior | Probability assigned to the class before seeing this observation | |
| Likelihood | How compatible the observation is with the class | |
| Evidence | Overall probability of the observation | |
| Posterior | Updated probability of the class after seeing the observation |
For continuous features, probability densities replace point probabilities in the likelihood and evidence. This distinction matters because the probability of an exact value of a continuous random variable is generally zero.
For class comparison, the evidence is shared by every candidate class. Therefore, a classifier can compare the products:
The proportionality symbol means that an omitted factor is the same for every class, not that the expression is necessarily already a normalized probability.
3. The Naive Bayes assumption
Modeling the full joint likelihood can be difficult when there are many features. Naive Bayes simplifies the likelihood by assuming that features are conditionally independent given the class:
Combining this with Bayes’ theorem yields:
The adjective naive refers to the assumption, not to a lack of statistical reasoning. Words in a sentence, for example, are often correlated even when the topic is known. Nonetheless, their separate contributions can still produce a practical text classifier.
Important: Naive Bayes does not assume all features are independent in the entire dataset. It assumes independence conditional on the class. These are different claims.
Why the assumption helps
Without a simplifying assumption, estimating a joint probability distribution over many variables can require a large amount of data. Naive Bayes instead estimates one class prior and a relatively small number of per-feature likelihood parameters for each class.
The result is usually fast to train and inexpensive to run. Its tradeoff is that it cannot explicitly capture interactions between features under the basic model.
4. Worked example: classifying a message
Suppose a training dataset contains 100 messages: 40 spam messages and 60 legitimate messages. We record whether a message contains each of two words: prize and meeting.
Assume the following estimated probabilities for this simplified illustration:
| Quantity | Spam | Not spam |
|---|---|---|
| Prior class probability | ||
Probability of prize being present | ||
Probability of meeting being absent |
We want to classify a message in which prize is present and meeting is absent. Under the conditional-independence assumption, calculate an unnormalized class score.
For spam:
For not spam:
Normalize by the sum of the two scores:
The model predicts spam, with an estimated posterior probability of about .
This example uses deliberately chosen likelihood values to illustrate the calculation. A real system learns these quantities from training data, applies a suitable smoothing method, and evaluates whether its probabilities are well calibrated.
5. From observations to a Naive Bayes classifier
The usual supervised-learning workflow is:
- Collect labeled training examples and decide how each example will be represented as features.
- Estimate class priors from the labels, or specify appropriate priors.
- Estimate the feature likelihood distributions separately for each class.
- At inference, combine the class prior and observed feature likelihoods.
- Normalize scores if posterior probabilities are required, and choose a class or a decision threshold.
- Evaluate predictions on data not used to fit the model.
6. Major Naive Bayes variants
The appropriate Naive Bayes variant depends on the distribution assumed for each feature, not simply on whether the task is text classification.
| Variant | Feature model | Typical use |
|---|---|---|
| Gaussian Naive Bayes | Continuous features follow a Gaussian (normal) distribution within each class | Numerical measurements |
| Multinomial Naive Bayes | Nonnegative count-like features are modeled using a multinomial formulation | Word counts and document classification |
| Bernoulli Naive Bayes | Binary features record whether an attribute is present or absent | Binary indicators such as word presence |
| Complement Naive Bayes | A variation of Multinomial Naive Bayes that uses statistics of the complement of each class | Often useful for imbalanced text datasets |
| Categorical Naive Bayes | Each categorical feature follows a categorical distribution for each class | Discrete categories encoded as integer feature values |
Gaussian Naive Bayes
For a numerical feature , the model estimates a class-specific mean and variance . Its likelihood density is:
This model can work well when numerical features have approximately Gaussian class-conditional distributions. It does not require the entire dataset to follow one normal distribution.
Multinomial Naive Bayes
A document may be represented as a vector of nonnegative token counts. The model estimates the probability of each token under each class, then combines those estimates according to how many times the token occurs.
For class , a common estimate for token uses additive smoothing:
where is the count of token in class , is the total token count for that class, is vocabulary size, and controls smoothing. With , this is often called Laplace smoothing.
Smoothing avoids assigning zero likelihood to a document solely because a particular word never appeared in a class’s training examples.
Bernoulli Naive Bayes
Here, each feature indicates presence () or absence (). Both outcomes contribute to the score:
This distinguishes a word that is absent from a word that appears zero times because of a different representation. Bernoulli and Multinomial Naive Bayes are therefore not interchangeable even when they are applied to the same text dataset.
7. Why log probabilities are used
Multiplying many small probabilities can lead to numerical underflow, where a nonzero mathematical result is rounded to zero in floating-point arithmetic. Taking logarithms converts products into sums:
Because the logarithm is strictly increasing for positive inputs, comparing log scores gives the same winning class as comparing the original positive scores. Implementations also use stable normalization techniques when converting log scores into posterior probabilities.
For zero probabilities, is undefined as a finite real number. Appropriate smoothing or distribution-specific handling is essential.
8. Python example: classifying short messages
The following example trains a Multinomial Naive Bayes classifier from labeled short messages. CountVectorizer turns text into word-count features, and Pipeline keeps the text transformation with the estimator.
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.naive_bayes import MultinomialNB
from sklearn.pipeline import Pipeline
messages = [
"claim your prize today",
"win a prize now",
"limited offer claim reward",
"free reward and bonus",
"meeting moved to tomorrow",
"please review the report",
"team meeting about project",
"project report is ready",
]
labels = ["spam", "spam", "spam", "spam",
"ham", "ham", "ham", "ham"]
classifier = Pipeline([
("counts", CountVectorizer()),
("model", MultinomialNB(alpha=1.0)),
])
classifier.fit(messages, labels)
new_messages = [
"claim your bonus prize",
"review the project report",
]
predictions = classifier.predict(new_messages)
probabilities = classifier.predict_proba(new_messages)
for message, label, class_probabilities in zip(
new_messages, predictions, probabilities
):
scores = dict(zip(classifier.classes_, class_probabilities))
print(message)
print("prediction:", label)
print("model probabilities:", scores)
What to observe: The vectorizer builds a vocabulary from the training messages, the model estimates class-specific token probabilities, and inference returns both labels and estimated probabilities. The dataset is intentionally tiny and illustrative: do not interpret its predictions or probabilities as evidence of real-world reliability.
In a real project, separate training and test data before fitting text transformations, compare against a baseline, and evaluate on representative messages. Cross-validation can help when data is limited, but each fold must fit its own vectorizer and model.
9. Model evaluation and probability calibration
A probabilistic classifier needs evaluation on two distinct questions:
Does it classify examples correctly? Use a confusion matrix, precision, recall, F1-score, or other metrics appropriate to the impact of errors. Accuracy alone can be misleading when one class dominates.
Do its numerical probabilities reflect observed outcomes? A model can rank cases correctly while producing probabilities that are overconfident or underconfident. Evaluate calibration using tools such as reliability diagrams, log loss, or Brier score where appropriate.
Naive Bayes may produce useful class rankings while giving poorly calibrated probabilities because the independence assumption counts correlated evidence as if it were separate. Do not treat a reported probability of as a guaranteed 99% chance of correctness.
If calibrated probabilities are required, evaluate calibration on held-out data and consider established calibration procedures. Calibration itself must not leak information from the final test set.
10. Strengths and limitations
| Strength | Limitation |
|---|---|
| Fast fitting and inference | Conditional independence is often violated |
| Works with many high-dimensional sparse representations | Interactions between correlated features are not directly modeled |
| Can work with modest amounts of training data | Assumed likelihood distribution may be unsuitable |
| Simple baseline for text classification | Estimated probabilities may be poorly calibrated |
| Supports multiple feature-distribution variants | Unseen tokens, class imbalance, and distribution shift require care |
Common mistakes
- Choosing the wrong likelihood family: Gaussian Naive Bayes is not a drop-in replacement for Multinomial Naive Bayes on raw word counts.
- Ignoring preprocessing: Tokenization, vocabulary design, missing values, and feature representation affect predictions.
- Confusing a posterior estimate with certainty: Model outputs depend on assumptions and training data.
- Allowing leakage: Do not fit the vocabulary or feature selection process on the test set.
- Evaluating on training examples: A training score does not estimate generalization to future messages.
- Assuming independence must be true for the model to work: It is a simplifying approximation; evaluate the consequences empirically.
11. Naive Bayes compared with logistic regression
Naive Bayes is usually described as a generative classifier because it models a class prior and feature distributions given a class, . Logistic regression is a discriminative classifier that models directly.
| Question | Naive Bayes | Logistic regression |
|---|---|---|
| What is estimated? | Class priors and class-conditional feature distributions | Conditional class probabilities from learned coefficients |
| Key assumption | Conditional feature independence, plus a likelihood family | A specified linear form for log-odds in standard logistic regression |
| How are features combined? | Product of per-feature likelihood terms | Weighted sum of features passed through a link function |
| Typical benefit | Simple, efficient, strong baseline | Often flexible for correlated features with appropriate regularization |
Neither approach is always better. Compare them with the same properly separated datasets and metrics.
12. When should you use Naive Bayes?
Naive Bayes is worth testing when you need a simple, interpretable baseline, a fast text classifier, or a lightweight model for a resource-constrained task. It is especially convenient when feature representations naturally fit one of its likelihood assumptions.
Choose or compare alternatives when important patterns depend on feature interactions, model calibration is crucial, or more expressive decision boundaries are needed. A baseline is useful precisely because it gives a reference against which a more complicated model must justify its additional cost.
13. Check your understanding
- What does the prior probability represent in Bayes’ theorem?
- What does conditionally independent given the class mean?
- Why can Naive Bayes work when two words are correlated?
- When would you use Multinomial rather than Bernoulli Naive Bayes?
- Why is additive smoothing important for text classification?
- Why does a classifier compute log probabilities?
- Is a predicted probability of sufficient evidence of calibration?
- Why must a text vectorizer be fitted only on the training portion of an evaluation split?
Show suggested answers
- The class probability before examining the current observation.
- After conditioning on the class, knowledge of one feature does not change the assumed distribution of another feature.
- The assumption is an approximation that may still yield useful decisions, although it can distort estimated probabilities.
- Use Multinomial for nonnegative count-like features and Bernoulli for binary presence/absence indicators.
- It prevents zero likelihoods caused by unseen feature values in a class.
- To replace products of small numbers with numerically safer sums.
- No. Calibration needs evaluation against observed outcomes on held-out data.
- Learning the vocabulary from test data introduces information from the held-out dataset into model development.
14. Related concepts
- AI Knowledge Map — the complete learning path.
- Probability and Bayes’ Theorem — conditional probability and Bayesian updating.
- Entropy, Cross-Entropy, and KL Divergence — probabilistic losses and uncertainty.
- Machine Learning Paradigms — supervised and other learning settings.
- Linear and Logistic Regression — a discriminative alternative.
- Data Splitting, Labeling, and Leakage — proper evaluation separation.
- Model Training, Overfitting, and Generalization — next topic in the learning sequence.
- Evaluating Machine Learning Models — classification metrics and calibration.
References and further reading
- scikit-learn User Guide: Naive Bayes — model families, assumptions, and parameter estimation.
- scikit-learn API: MultinomialNB — additive smoothing and classifier options.
- scikit-learn User Guide: Probability Calibration — calibration curves and methods.
- scikit-learn User Guide: Working With Text Data — supervised text classification workflows.
- An Introduction to Statistical Learning — foundational classification methods.
Related articles in
- Clustering and K-Means — Learn how unsupervised clustering discovers groups in data, how K-Means optimizes cluster centroids, and how to evaluate and use its results responsibly.
- Data, Model, and Experiment Versioning — Learn to trace ML results to exact datasets, code revisions, configurations, and artifacts.
- Decision Trees, Random Forests, and Boosting — Learn how decision trees partition data, how random forests reduce variance through bagging, and how boosting combines sequential learners to improve predictions.