Machine Learning • Machine Learning Algorithms • 14 min read

Naive Bayes and Probabilistic Classification

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 x=(x1,…,xd)x=(x_1,\ldots,x_d), and the output is one of several class labels y∈{c1,…,ck}y\in\{c_1,\ldots,c_k\}. For example, an email classifier might decide whether a message is spam or not spam.

A probabilistic classifier estimates a posterior class probability:

P(Y=c∣X=x).P(Y=c\mid X=x).

This represents the model’s probability for class cc after observing the features xx. A common decision rule selects the class with the largest posterior probability:

y^=argmax⁡c  P(Y=c∣X=x).\hat y=\underset{c}{\operatorname{argmax}}\;P(Y=c\mid X=x).

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:

P(Y=c∣X=x)=P(X=x∣Y=c)P(Y=c)P(X=x).P(Y=c\mid X=x)=\frac{P(X=x\mid Y=c)P(Y=c)}{P(X=x)}.
TermNameMeaning
P(Y=c)P(Y=c)PriorProbability assigned to the class before seeing this observation
P(X=x∣Y=c)P(X=x\mid Y=c)LikelihoodHow compatible the observation is with the class
P(X=x)P(X=x)EvidenceOverall probability of the observation
P(Y=c∣X=x)P(Y=c\mid X=x)PosteriorUpdated 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:

P(Y=c∣X=x)∝P(X=x∣Y=c)P(Y=c).P(Y=c\mid X=x)\propto P(X=x\mid Y=c)P(Y=c).

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 P(X=x∣Y=c)P(X=x\mid Y=c) can be difficult when there are many features. Naive Bayes simplifies the likelihood by assuming that features are conditionally independent given the class:

P(X=x∣Y=c)=∏j=1dP(Xj=xj∣Y=c).P(X=x\mid Y=c)=\prod_{j=1}^{d}P(X_j=x_j\mid Y=c).

Combining this with Bayes’ theorem yields:

P(Y=c∣X=x)∝P(Y=c)∏j=1dP(Xj=xj∣Y=c).P(Y=c\mid X=x)\propto P(Y=c)\prod_{j=1}^{d}P(X_j=x_j\mid Y=c).

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:

QuantitySpamNot spam
Prior class probability0.400.400.600.60
Probability of prize being present0.750.750.100.10
Probability of meeting being absent0.800.800.300.30

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:

sspam=0.40×0.75×0.80=0.24.s_{\text{spam}}=0.40\times0.75\times0.80=0.24.

For not spam:

snot spam=0.60×0.10×0.30=0.018.s_{\text{not spam}}=0.60\times0.10\times0.30=0.018.

Normalize by the sum of the two scores:

P(spam∣x)=0.240.24+0.018≈0.9302.P(\text{spam}\mid x)=\frac{0.24}{0.24+0.018}\approx0.9302. P(not spam∣x)=0.0180.24+0.018≈0.0698.P(\text{not spam}\mid x)=\frac{0.018}{0.24+0.018}\approx0.0698.

The model predicts spam, with an estimated posterior probability of about 93.0%93.0\%.

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:

  1. Collect labeled training examples and decide how each example will be represented as features.
  2. Estimate class priors from the labels, or specify appropriate priors.
  3. Estimate the feature likelihood distributions separately for each class.
  4. At inference, combine the class prior and observed feature likelihoods.
  5. Normalize scores if posterior probabilities are required, and choose a class or a decision threshold.
  6. Evaluate predictions on data not used to fit the model.
Naive Bayes pipeline from labeled data through learned class priors and feature likelihoods to class scores and prediction
Naive Bayes learns per-class feature distributions, then combines them when predicting a new example.

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.

VariantFeature modelTypical use
Gaussian Naive BayesContinuous features follow a Gaussian (normal) distribution within each classNumerical measurements
Multinomial Naive BayesNonnegative count-like features are modeled using a multinomial formulationWord counts and document classification
Bernoulli Naive BayesBinary features record whether an attribute is present or absentBinary indicators such as word presence
Complement Naive BayesA variation of Multinomial Naive Bayes that uses statistics of the complement of each classOften useful for imbalanced text datasets
Categorical Naive BayesEach categorical feature follows a categorical distribution for each classDiscrete categories encoded as integer feature values

Gaussian Naive Bayes

For a numerical feature XjX_j, the model estimates a class-specific mean μjc\mu_{jc} and variance σjc2\sigma_{jc}^2. Its likelihood density is:

p(xj∣Y=c)=12πσjc2exp⁡(−(xj−μjc)22σjc2).p(x_j\mid Y=c)=\frac{1}{\sqrt{2\pi\sigma_{jc}^{2}}}\exp\left(-\frac{(x_j-\mu_{jc})^2}{2\sigma_{jc}^{2}}\right).

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 cc, a common estimate for token jj uses additive smoothing:

θ^jc=Njc+αNc+αd,\hat\theta_{jc}=\frac{N_{jc}+\alpha}{N_c+\alpha d},

where NjcN_{jc} is the count of token jj in class cc, NcN_c is the total token count for that class, dd is vocabulary size, and α>0\alpha>0 controls smoothing. With α=1\alpha=1, 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 (11) or absence (00). Both outcomes contribute to the score:

P(X=x∣Y=c)=∏jθjcxj(1−θjc)1−xj.P(X=x\mid Y=c)=\prod_j\theta_{jc}^{x_j}(1-\theta_{jc})^{1-x_j}.

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:

log⁡sc=log⁡P(Y=c)+∑j=1dlog⁡P(Xj=xj∣Y=c).\log s_c=\log P(Y=c)+\sum_{j=1}^{d}\log P(X_j=x_j\mid Y=c).

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, log⁡0\log 0 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 0.990.99 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

StrengthLimitation
Fast fitting and inferenceConditional independence is often violated
Works with many high-dimensional sparse representationsInteractions between correlated features are not directly modeled
Can work with modest amounts of training dataAssumed likelihood distribution may be unsuitable
Simple baseline for text classificationEstimated probabilities may be poorly calibrated
Supports multiple feature-distribution variantsUnseen 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, P(X∣Y)P(X\mid Y). Logistic regression is a discriminative classifier that models P(Y∣X)P(Y\mid X) directly.

QuestionNaive BayesLogistic regression
What is estimated?Class priors and class-conditional feature distributionsConditional class probabilities from learned coefficients
Key assumptionConditional feature independence, plus a likelihood familyA specified linear form for log-odds in standard logistic regression
How are features combined?Product of per-feature likelihood termsWeighted sum of features passed through a link function
Typical benefitSimple, efficient, strong baselineOften 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

  1. What does the prior probability represent in Bayes’ theorem?
  2. What does conditionally independent given the class mean?
  3. Why can Naive Bayes work when two words are correlated?
  4. When would you use Multinomial rather than Bernoulli Naive Bayes?
  5. Why is additive smoothing important for text classification?
  6. Why does a classifier compute log probabilities?
  7. Is a predicted probability of 0.950.95 sufficient evidence of calibration?
  8. Why must a text vectorizer be fitted only on the training portion of an evaluation split?
Show suggested answers
  1. The class probability before examining the current observation.
  2. After conditioning on the class, knowledge of one feature does not change the assumed distribution of another feature.
  3. The assumption is an approximation that may still yield useful decisions, although it can distort estimated probabilities.
  4. Use Multinomial for nonnegative count-like features and Bernoulli for binary presence/absence indicators.
  5. It prevents zero likelihoods caused by unseen feature values in a class.
  6. To replace products of small numbers with numerically safer sums.
  7. No. Calibration needs evaluation against observed outcomes on held-out data.
  8. Learning the vocabulary from test data introduces information from the held-out dataset into model development.

References and further reading

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.

Image preview

Fit