Naive Bayes is a way of making a first guess and then sharpening it with evidence. It starts with how common each outcome usually is, then looks at each clue in the data and asks how strongly that clue points to each outcome. The outcome with the strongest combined case wins.
It is called "naive" because it treats every clue as if it were unrelated to the others. That is rarely true, but it keeps the calculation simple enough to run almost instantly.
Why it matters: this simple recipe lets a computer sort emails, reviews or support tickets quickly, learn from a small dataset, and show exactly why it made each decision. That is why Naive Bayes is still one of the first models data scientists build for a new classification problem
The Naive Bayes algorithm in machine learning is a simple classifier built on Bayes' theorem, a rule from probability for updating a belief when new evidence arrives. The algorithm uses that rule to work out which category a new data point most likely belongs to, such as spam or not spam. Because it needs only counts and basic multiplication, it trains in a single pass over the data and remains one of the fastest classifiers to build.
That speed is why data scientists still use Naive Bayes as a first baseline for text classification, even though large language models now handle many language tasks.
This guide starts with Bayes' theorem, builds it up into the Naive Bayes formula, and works through a complete prediction by hand. It then reproduces the same result in Python, so you can check every number yourself. If you want to build these models on real projects, the AnalytixLabs machine learning course covers them end to end.
What is the Naive Bayes Algorithm in Machine Learning?
Naive Bayes is a supervised learning method, meaning it learns from examples with known class labels. Like other classification algorithms, it assigns each new observation to a category, such as spam or not spam. Unlike many others, it first estimates a probability for each class and then picks the class with the highest probability.
The word "naive" comes from the one strong assumption the algorithm makes: once the class is known, every feature is treated as independent of every other feature. A spam filter, for example, assumes that seeing the word "free" in a spam email tells it nothing about whether the same email also contains "winner". Real data rarely satisfies this assumption, yet the class rankings Naive Bayes produces are often accurate enough to be useful.
Naive Bayes is also a family of models, not a single algorithm. Each member uses the same theorem and the same assumption. They differ only in how they model the features, which the types section covers later. Since every member rests on Bayes' theorem, it's the natural place to begin.
Bayes' Theorem: An Introduction
Bayes' theorem is named after Thomas Bayes, an 18th-century English statistician and Presbyterian minister. His essay on the idea was published in 1763, two years after his death. Pierre-Simon Laplace later developed it into the general form used today. The theorem tells us how to update a hypothesis's probability once new evidence arrives.
You use this kind of reasoning every time you search online.
Suppose you type a vague phrase such as "automatic food" and the top results show a product from Amazon that cooks Indian household meals rather than showing vending machines or pet feeders.

You never said you wanted Indian home cooking, yet the results guessed it based on how often people in your region who type similar words click that kind of page.
Search engines combine many signals, so this isn't Bayes' theorem running on its own. The underlying idea is the same, though: start with what is usually true, then adjust the guess as each new clue arrives. Bayes' theorem turns that everyday instinct into a precise calculation.
The Bayes' Theorem Formula
Mathematically, Bayes' theorem is written as: P(A | B) = P(B | A) × P(A) / P(B). Each term in this formula has a specific meaning:

P(A|B) is the probability of event A, given that event B has occurred.
P(B|A) is the probability of event B, given that event A has occurred.
P(A) is the probability of event A on its own.
P(B) is the probability of event B on its own.
Key terms you need to understand Bayes' theorem:
The formula combines three kinds of probability, and telling them apart makes the rest of the article easier to follow.
Marginal probability is the probability of a single event, regardless of any other variable, such as P(A).
Joint probability is the probability of two events happening together, written P(A, B).
Conditional probability is the probability of one event given that another has occurred, written P(A|B).
Joint probability is symmetric, so P(A, B) always equals P(B, A). Conditional probability is not symmetric because P(A|B) generally differs from P(B|A). Bayes' theorem exists precisely to convert one conditional probability into the other.
The conversion follows directly from the product rule, which links joint and conditional probability in two equivalent ways:
P(A, B) = P(A | B) × P(B) = P(B | A) × P(A)

Dividing both sides by P(B) gives Bayes' theorem. Once the formula is in this form, each of its terms takes on a name that describes its role in learning from evidence:
Prior, P(A): what we believe about A before seeing the evidence.
Likelihood, P(B|A): how probable the evidence is if A is true.
Evidence, P(B): how probable the evidence is overall, which normalizes the result.
Posterior, P(A|B): our updated belief about A after seeing the evidence.
In words, the theorem therefore reads:

Posterior = (Likelihood × Prior) / Evidence
An Intuitive Explanation of Bayes' Theorem with a Machine Learning Example:
The terms become clearer once you attach real numbers to them, so consider a simple spam filter. Suppose 20% of the emails an inbox receives are spam. The word "free" appears in 60% of spam emails but in only 5% of legitimate (ham) emails. A new email contains "free", and the filter must estimate the probability that it is spam.
The prior and the likelihood come straight from those figures:
Prior: P(Spam) = 0.20, so P(Ham) = 0.80.
Likelihood: P("free" | Spam) = 0.60 and P("free" | Ham) = 0.05.
The evidence term needs one extra step, because "free" can appear in both spam and ham emails. Adding the two routes together gives the overall probability of seeing the word:
P(free) = (0.60 × 0.20) + (0.05 × 0.80) = 0.12 + 0.04 = 0.16
With all three terms known, Bayes' theorem gives the posterior:
P(Spam | free) = (0.60 × 0.20) / 0.16 = 0.75
A single word has therefore raised the probability of spam from 20% to 75%. A real filter checks hundreds of words rather than one, and combining all of that evidence efficiently is exactly the job Naive Bayes was designed to do.
This is not just a textbook exercise. In 2002, programmer Paul Graham's essay "A Plan for Spam" showed that scoring emails word by word with Bayesian probabilities could catch most spam. Bayesian filters soon appeared in widely used tools such as Mozilla Thunderbird's junk mail filter and SpamAssassin.
Bayes' Theorem in Machine Learning
The spam example used one word as evidence, and classification generalizes that idea to many features at once. The hypothesis A becomes a class c, and the evidence B becomes a feature vector x = (x1, x2, ..., xn). Bayes' theorem then reads:
P(c | x) = P(x | c) × P(c) / P(x)
Each term now has a machine learning meaning:
P(c|x) is the posterior probability of class c, given the observed features.
P(c) is the class prior, which is the share of training records that belong to class c.
P(x|c) is the likelihood of seeing these feature values within class c.
P(x) is the evidence, which is the same for every class and only normalizes the result.
A food delivery app guessing your next order shows how several clues combine. Say you open the app at 9 pm on a Friday, from home, after ordering biryani on three of your last five weekends. Each of those details is a feature in x, the overall popularity of each cuisine plays the role of the prior, and every clue shifts the odds towards one dish or another. Real recommendation systems use far more complex models, but the logic of updating a guess with each clue is the same.
The hard part is the likelihood P(x|c). Estimating it directly would require counting every possible combination of feature values, and with even 20 features, most combinations never appear in the training data. The naive assumption solves exactly this problem.
The Naive Bayes Theorem: How the Naive Assumption Works
Naive Bayes assumes that features are conditionally independent once the class is known. Under that assumption, the joint likelihood splits into a product of one-feature likelihoods:
P(x₁, x₂, …, xₙ | c) = P(x₁ | c) × P(x₂ | c) × … × P(xₙ | c)

Each P(xi|c) needs counts for only one feature at a time, so the model stays small and fast even with thousands of features. This is what makes Naive Bayes practical for text, where every word in the vocabulary is a feature.
The Naive Bayes Formula (Naive Bayes Equation)
Substituting the product back into Bayes' theorem gives the Naive Bayes formula:
P(c | x₁, …, xₙ) = [P(c) × P(x₁ | c) × P(x₂ | c) × … × P(xₙ | c)] / P(x₁, …, xₙ)

Conditional independence is an assumption the model imposes, not a property the data automatically has. Words such as "free" and "prize" often appear together in our earlier spam example, so the assumption is broken in almost every real dataset. When features are strongly correlated, Naive Bayes counts the same evidence more than once, pushing its probabilities toward 0 or 1.
Picture a friend predicting rain who treats "dark clouds" and "no sunshine" as two separate warning signs. Both come from the same cloud cover, so counting them twice makes the friend more certain of rain than the sky actually justifies. Naive Bayes makes exactly this mistake whenever two features describe the same underlying thing.
The predicted class often stays correct despite this, because the ranking of classes is more robust than the probabilities themselves. If you need the probabilities as risk scores, calibrate them first, for example with scikit-learn's CalibratedClassifierCV.
Choosing the Class with the MAP Decision Rule
Once the formula gives a posterior for every class, the model still has to pick one. Because the denominator P(x) is identical for every class, it cannot change which class wins, so it is dropped:
Predicted class ĉ = argmax over c of [P(c) × P(x₁ | c) × P(x₂ | c) × … × P(xₙ | c)]

This is the maximum a posteriori (MAP) decision rule, which chooses the class with the highest posterior probability. If every class has the same prior, P(c) also drops out, and the rule reduces to maximum likelihood, which chooses the class under which the observed features are most probable.
Multiplying hundreds of small probabilities can produce a number too small for a computer to store, a problem called numerical underflow. Implementations therefore add log-probabilities instead of multiplying probabilities, which picks the same class:
Predicted class ĉ = argmax over c of [log P(c) + log P(x₁ | c) + log P(x₂ | c) + … + log P(xₙ | c)]

How Each Likelihood P(xi|c) is Estimated?
The decision rule needs a value for every P(xi|c), and how that value is estimated depends on the type of feature:
Categorical features: The share of class-c records that have value xi, usually with smoothing (covered in the worked example).
Count features: Such as how many times each word appears, modeled with a multinomial distribution.
Binary features: Such as whether a word appears at all, modeled with a Bernoulli distribution.
Continuous features: Modeled with an assumed distribution, most often a Gaussian whose mean and variance are estimated for each class, or converted into categories first.
This choice of distribution is the only thing that separates one type of Naive Bayes classifier from another.
Types of Naive Bayes Classifiers in Machine Learning
scikit-learn, the most widely used Python library for classical machine learning, provides five Naive Bayes classifiers in its sklearn.naive_bayes module. Each matches a different feature type, so the right choice depends on your data.
Classifier | Feature type | Distribution assumed | Typical use |
|---|---|---|---|
GaussianNB | Continuous | Normal (Gaussian) | Measurements and sensor readings |
MultinomialNB | Counts or frequencies, including TF-IDF | Multinomial | Text classification with word counts |
ComplementNB | Counts or frequencies | Multinomial, estimated from each class's complement | Text classification with imbalanced classes |
BernoulliNB | Binary (0/1) | Bernoulli | Word presence or absence, short texts |
CategoricalNB | Categorical | Categorical | Customer attributes such as city or income band |
1. Gaussian Naive Bayes
Gaussian Naive Bayes handles continuous features by assuming that, within each class, every feature follows a normal distribution. It estimates one mean and one variance per feature per class, and it reads the likelihood from the bell curve those two values define.
2. Multinomial Naive Bayes
Multinomial Naive Bayes works with counts, which makes it the standard choice for text represented as a bag of words. Here, the likelihood reflects how often each word appears in documents of a class, so a word that appears five times carries more weight than a word that appears once.
3. Complement Naive Bayes
Complement Naive Bayes adapts the multinomial model for imbalanced text data, where one class has far more documents than another. It estimates word statistics from all classes except the one being scored, making its estimates more stable for smaller classes.
4. Bernoulli Naive Bayes
Bernoulli Naive Bayes also suits text, but it records only whether each word is present (1) or absent (0). Unlike the multinomial model, it explicitly penalizes a class when a word typical of that class is missing, which can help with short documents.
5. Categorical Naive Bayes
Categorical Naive Bayes is designed for features that take a fixed set of labels, such as gender, city, or income band. Since the churn dataset in the next section contains only features of this kind, it is the right model for the worked example.
Naive Bayes Classification Example: Predicting Customer Churn
The formula is easiest to trust once you have run it by hand, so this section predicts whether a customer will churn. The training data below holds 10 customers with five categorical features and a known outcome. Customer 11 is new, and the model must predict their churn status.
Customer ID | Gender | Location | Marital Status | Education | Income Group | Churn |
|---|---|---|---|---|---|---|
1 | Male | Bangalore | Married | Post Graduation | High | Yes |
2 | Female | Gurgaon | Married | SSC | Low | No |
3 | Male | Chennai | Unmarried | Graduation | Medium | No |
4 | Male | Hyderabad | Unmarried | SSC | Low | No |
5 | Female | Bangalore | Married | Graduation | Low | Yes |
6 | Female | Gurgaon | Unmarried | Post Graduation | Medium | No |
7 | Female | Chennai | Married | Graduation | Medium | Yes |
8 | Male | Hyderabad | Married | Post Graduation | High | No |
9 | Female | Bangalore | Married | SSC | Low | Yes |
10 | Male | Gurgaon | Unmarried | Graduation | Medium | No |
11 | Male | Bangalore | Unmarried | SSC | Medium | ? |
In a real project, this table would come from data preprocessing, where you handle missing values and clean categories. The calculation itself then follows four steps:
Calculate the prior probability P(c) of each class.
Estimate the likelihood P(xi|c) of each of customer 11's feature values within each class.
Multiply each class's prior by its likelihoods to get a score.
Normalize the scores into probabilities and choose the class with the highest one.
Step 1: Calculate the class priors
The prior is simply the share of training records in each class. Four of the 10 customers churned, so:
P(Churn = Yes) = 4/10 = 0.40 and P(Churn = No) = 6/10 = 0.60
Step 2: Estimate the likelihoods, one feature at a time
Each likelihood is a count within one class divided by that class's size. Taking gender first, one of the four churned customers is male, while four of the six retained customers are male:
P(Male | Yes) = 1/4 = 0.25 and P(Male | No) = 4/6 ≈ 0.67
If gender were the only feature, Bayes' theorem would already give an answer. Five of the 10 customers are male, so P(Male) = 0.50, and the posterior for churn is 0.25 × 0.40 / 0.50 = 0.20. A male customer would therefore be predicted to stay, with an 80% probability.
The zero-frequency problem:
The same counting breaks down for customer 11's other features. None of the four churned customers is unmarried, and none of the six retained customers lives in Bangalore. Both of these likelihoods are therefore zero:
P(Unmarried | Yes) = 0/4 = 0 and P(Bangalore | No) = 0/6 = 0
Because Naive Bayes multiplies likelihoods, a single zero wipes out a class's score, no matter how strong the rest of its evidence is. Here both classes score zero, so the model cannot make any prediction at all. A value missing from a small training set does not mean it is impossible, so the model needs a way to avoid treating unseen values as certain evidence.
Think of a tourist who spends five sunny days in Darjeeling and concludes that it never rains there. Five days are simply too few to have seen rain, and a model trained on 10 customers faces the same problem with unmarried churners and Bangalore-based loyal customers.
Fixing it with Laplace smoothing:
Laplace smoothing solves the problem by adding a small count, alpha, to every feature value in every class. With alpha = 1, the smoothed likelihood is:
P(xᵢ | c) = (count(xᵢ, c) + 1) / (count(c) + k)
Here, k is the number of distinct values the feature can take, such as 4 for location (Bangalore, Chennai, Gurgaon, and Hyderabad). Adding k to the denominator keeps each feature's probabilities summing to 1 within a class. Applying the formula to customer 11's five feature values gives:
Customer 11's value (k) | Count in Yes (n = 4) | P(x|Yes) | Count in No (n = 6) | P(x|No) |
|---|---|---|---|---|
Gender = Male (2) | 1 | 2/6 = 0.333 | 4 | 5/8 = 0.625 |
Location = Bangalore (4) | 3 | 4/8 = 0.500 | 0 | 1/10 = 0.100 |
Marital Status = Unmarried (2) | 0 | 1/6 = 0.167 | 4 | 5/8 = 0.625 |
Education = SSC (3) | 1 | 2/7 = 0.286 | 2 | 3/9 = 0.333 |
Income Group = Medium (3) | 1 | 2/7 = 0.286 | 3 | 4/9 = 0.444 |
Step 3: Multiply the prior by the likelihoods
With no zeros left, each class's score is its prior multiplied by its five likelihoods:
Score(Yes) = 0.40 × 0.333 × 0.500 × 0.167 × 0.286 × 0.286 ≈ 0.000907
Score(No) = 0.60 × 0.625 × 0.100 × 0.625 × 0.333 × 0.444 ≈ 0.003472
Step 4: Normalize and predict
The two scores are not yet probabilities, because the evidence term P(x) was dropped. Dividing each score by their sum restores it:
P(Yes | x) = 0.000907 / (0.000907 + 0.003472) ≈ 0.207 and P(No | x) ≈ 0.793
The model predicts that customer 11 will not churn, with a probability of about 79%. Bangalore's link to churn pulled the score toward Yes, but being unmarried and in the medium-income group pulled it harder toward No. The next section reproduces the same 20.7% and 79.3% in Python.
How to Implement Naive Bayes in Python with scikit-learn
scikit-learn turns the four manual steps into a few lines of code. Its CategoricalNB classifier expects each category encoded as a number, so the first step converts the text labels with OrdinalEncoder.
Example 1: Predicting churn with CategoricalNB
import pandas as pd
from sklearn.preprocessing import OrdinalEncoder
from sklearn.naive_bayes import CategoricalNB
data = pd.DataFrame({
"Gender": ["Male", "Female", "Male", "Male", "Female", "Female", "Female", "Male", "Female", "Male"],
"Location": ["Bangalore", "Gurgaon", "Chennai", "Hyderabad", "Bangalore", "Gurgaon", "Chennai", "Hyderabad", "Bangalore", "Gurgaon"],
"Marital": ["Married", "Married", "Unmarried", "Unmarried", "Married", "Unmarried", "Married", "Married", "Married", "Unmarried"],
"Education": ["Post Graduation", "SSC", "Graduation", "SSC", "Graduation", "Post Graduation", "Graduation", "Post Graduation", "SSC", "Graduation"],
"Income": ["High", "Low", "Medium", "Low", "Low", "Medium", "Medium", "High", "Low", "Medium"],
"Churn": ["Yes", "No", "No", "No", "Yes", "No", "Yes", "No", "Yes", "No"],
})
X = data.drop(columns="Churn")
y = data["Churn"]
encoder = OrdinalEncoder()
X_encoded = encoder.fit_transform(X)
model = CategoricalNB(alpha=1.0) # alpha=1.0 applies Laplace smoothing
model.fit(X_encoded, y)
new_customer = pd.DataFrame([{"Gender": "Male", "Location": "Bangalore", "Marital": "Unmarried",
"Education": "SSC", "Income": "Medium"}])
probabilities = model.predict_proba(encoder.transform(new_customer))
print(dict(zip(model.classes_, probabilities[0].round(4))))
print(model.predict(encoder.transform(new_customer)))The output matches the hand calculation exactly, which confirms that scikit-learn applies the same smoothing formula:
{'No': 0.7929, 'Yes': 0.2071}
['No']Example 2: Building a spam filter with MultinomialNB
Text needs one extra step because the model works with word counts rather than raw sentences. CountVectorizer turns each email into counts, and a pipeline chains it to the classifier so that new emails go through the same conversion:
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.naive_bayes import MultinomialNB
from sklearn.pipeline import make_pipeline
emails = ["Win a free voucher now", "Claim your free prize today",
"Meeting moved to 3 pm", "Please review the attached report",
"Free entry to win cash", "Lunch tomorrow with the team"]
labels = ["spam", "spam", "ham", "ham", "spam", "ham"]
spam_filter = make_pipeline(CountVectorizer(), MultinomialNB())
spam_filter.fit(emails, labels)
print(spam_filter.predict(["Free cash prize waiting for you",
"Can we review the report tomorrow?"]))
# ['spam' 'ham']Six emails are enough to show the mechanics, but a real filter needs thousands of labeled examples and a held-out test set. On that test set, a confusion matrix shows how many spam emails slipped through and how many genuine emails were blocked, which accuracy alone hides. Our data science course covers this full evaluation workflow on industry datasets.
Advantages and Limitations of Naive Bayes
The two examples show why Naive Bayes is popular, and the worked calculation also shows where it can go wrong. Both sides matter when deciding whether to use it.
Advantages
Fast training and prediction: the model needs one pass over the data to count frequencies, so it trains in seconds even on large text collections.
Works with small datasets: it estimates few parameters, so it can give reasonable results where data-hungry models overfit.
Handles many features: each feature is estimated separately, which suits text with vocabularies of tens of thousands of words.
Supports incremental learning: scikit-learn's Naive Bayes classifiers offer partial_fit, so the model can update in batches as new data arrives.
Easy to interpret: every prediction can be traced back to priors and per-feature likelihoods, as the churn example showed.
Limitations
The independence assumption rarely holds: correlated features are counted more than once, which distorts the probabilities.
Probabilities tend to be overconfident: calibrate them before using them as risk scores.
Zero frequencies need smoothing: without it, one unseen value removes a class from consideration.
Accuracy is often lower than discriminative models: on large datasets, logistic regression, gradient boosting, or fine-tuned transformers usually classify more accurately.
Applications of Naive Bayes in Machine Learning
Those strengths and limits explain where Naive Bayes is used today. It fits problems that need speed, simplicity, or a quick benchmark more than marginal accuracy gains.
Spam and phishing filtering: word-based Naive Bayes was among the earliest widely used spam filtering methods and is still used as one signal within modern filters.
Text classification: news categorization, support ticket routing and document tagging, where Multinomial or Complement Naive Bayes handles large vocabularies cheaply.
Sentiment analysis: a quick first model that labels reviews or social posts as positive or negative.
Baselines for NLP projects: teams train Naive Bayes first, so that a more complex model has to justify its extra cost by beating it.
Real-time classification on limited hardware: prediction needs only a lookup and a sum, so it runs where a large model cannot.
The last two uses have become more important as large language models take on many text tasks without any training data. A Naive Bayes baseline shows whether a costly LLM call adds enough accuracy to be worth it, and for high-volume, narrow tasks the simpler model often wins on cost and speed. If you want to work across both ends of that spectrum, the AnalytixLabs Generative AI course covers the LLM side.
Knowing when a fast, low-cost model like Naive Bayes is enough, and when a task needs a large language model, is a core judgment call in applied AI work.
Pairing machine learning fundamentals with generative AI training builds both sides of that decision, so you can choose the right tool for each problem rather than defaulting to the most expensive one.
We recommend a combining our Machine Learning course with the GenAI course as a followup.
Naive Bayes in Machine Learning: FAQs
How does Naive Bayes work in machine learning?
Naive Bayes applies Bayes' theorem to calculate the probability of each class from the feature values. It assumes the features are independent given the class, multiplies the class prior by each feature's likelihood, and predicts the class with the highest result.
What is Bayes' theorem in machine learning?
Bayes' theorem in machine learning updates the probability of a class once features are observed: P(c|x) = P(x|c) × P(c) / P(x). It underpins Naive Bayes, Bayesian networks, and Bayesian approaches to model tuning.
What is the Naive Bayes theorem?
The Naive Bayes theorem is Bayes' theorem combined with the assumption that features are independent once the class is known. That assumption lets you calculate the likelihood of many features as a simple product of one-feature probabilities.
What is the Naive Bayes formula?
The Naive Bayes formula is P(c|x1, ..., xn) = P(c) × P(x1|c) × ... × P(xn|c) / P(x1, ..., xn). In practice, we drop the denominator and choose the class with the highest numerator.
Why is it called "naive"?
It is called naive because it assumes every feature is independent of every other feature once the class is known. This assumption is usually false, but it keeps the model simple and fast.
Is Naive Bayes supervised or unsupervised?
Naive Bayes is a supervised learning algorithm because it learns from training data with known class labels.
What is the difference between conditional probability and Bayes' theorem?
Conditional probability, P(A|B), is the probability of A once B has occurred. Bayes' theorem is a formula derived from conditional probability that converts P(B|A) into P(A|B), which lets you update a belief with new evidence.
How is Naive Bayes different from logistic regression?
Naive Bayes is a generative model, which means it learns how the features are distributed within each class. Logistic regression is a discriminative model that learns the class boundary directly, which is why it usually performs better on large datasets. You can compare the two in practice with our guide to logistic regression in Python.
What is Laplace smoothing in Naive Bayes?
Laplace smoothing adds a small count, usually 1, to every feature value in every class. It prevents a value missing from the training data from producing a zero probability, which would otherwise rule out that class entirely.