Naive Bayes Algorithm in Machine Learning: Working, Types, Formulas, and Examples

By Rahul Singh

Updated on Nov 26, 2026

Share:

Quick Overview:

  • Naive Bayes algorithm is a classification algorithm which is based on Bayes theorem. It is a supervised machine learning algorithm which predicts the class of most likely outcomes.

  • Naive Bayes algorithm uses the prior probability and conditional probability concept to compute the posterior probability.

  • There are five types of Naive Bayes algorithm such as Gaussian, Multinomial, Bernoulli, Complement and Categorical Naive Bayes.

  • Naive Bayes is a fast algorithm for prediction. It is used in various applications like spam detection, sentiment analysis, and document classification.

  • In this blog you will learn the Naive Bayes algorithm, its mathematical formulas, pseudocode, numerical examples, Python code using Scikit-learn, applications, and limitations.

Want to apply algorithms like Naive Bayes to real projects? Explore IIT Kharagpur's Applied AI & Machine Learning Course – Executive Post Graduate Certificate to build practical machine learning skills.

What Is Naive Bayes Algorithm in Machine Learning?

It is a supervised learning ML algorithm for classification purposes. The idea is to determine the class that is the most likely class for a particular data point using probability. With a new example, the model determines the class that makes the particular values of the features most likely.

The naive bayes classifier algorithm is named after two concepts.

  • The first one is "bayes," which is the Bayes' theorem, the 18th-century rule on how to update probability when new evidence is received.

  • The second concept is "naive," which means that the algorithm makes a naive assumption that each feature is independent of other features, given the class.

The naive bayes algorithm in machine learning is used mainly for text classification, such as spam detection and sentiment analysis, but it also handles medical screening, recommendation, and any problem where you need a fast, probabilistic classifier.

Also Read: Supervised vs Unsupervised Learning: Differences, Examples, and Applications

Mathematical Foundation of the Naive Bayes Algorithm

Everything starts with Bayes' theorem. For a class C and a feature vector X, it says:

P(C | X) = P(X | C) * P(C) / P(X)

Each term has a name and a job.

Term

Name

Meaning

P(C | X)

Posterior probability

How likely class C is, given the features we observed

P(X | C)

Likelihood

How likely these features are, if the class were C

P(C)

Prior probability

How common class C is overall, before looking at features

P(X)

Evidence

How likely these features are across all classes

Computing P(X | C) directly would need data for every possible combination of feature values, which explodes quickly. This is where the naive assumption helps. If features are independent given the class, the joint likelihood breaks into a product of simple terms:

P(X | C) = P(x1 | C) P(x2 | C) ... * P(xn | C)

Since P(X) is the same for every class, it can be ignored when comparing classes. The prediction rule becomes:

predicted class = argmax over C of  P(C) P(x1 | C) P(x2 | C) ... P(xn | C)

In practice, multiplying many small numbers can underflow to zero, so implementations add logarithms instead. The class with the highest total log score wins.

Core Assumptions of the Naive Bayes Classifier

The naive bayes classifier rests on two assumptions.

Assumption

What It Means

Reality Check

Conditional independence

Given the class, each feature tells you nothing extra about the others

Rarely true. "Free" and "prize" often appear together in spam, yet the model treats them as unrelated

Equal importance

Every feature contributes with the same kind of weight in the product

Features differ in usefulness, but the learned probabilities partly adjust for this

A third working assumption is that training data represents what the model will see later, since the priors and likelihoods come straight from counts. When the independence assumption fails, the probability estimates become overconfident, often pushing values close to 0 or 1. 

How Does the Naive Bayes Algorithm Work?

The naive bayes algorithm has a training phase that's mostly counting and a prediction phase that's mostly multiplication.


Naive Bayes algorithm workflow showing five steps: estimating prior probabilities, calculating likelihoods, applying smoothing to avoid zero probabilities, scoring a new example, and selecting the class with the highest probability.
  1. Estimate the priors. Count how often each class appears in the training data and divide by the total.

  2. Estimate the likelihoods. For each class and each feature value, calculate how often that value appears within the class.

  3. Apply smoothing. Add a small count to every feature value so that none has a probability of exactly zero.

  4. Score a new example. For each class, multiply the prior by the likelihood of each observed feature value.

  5. Pick the winner. Choose the class with the highest score, or normalize the scores to get probabilities.

Laplace Smoothing

If a feature value never appears with a class in the training data, its likelihood is zero, and the product for that class collapses to zero no matter what the other features say. This is the zero-frequency problem. Laplace smoothing fixes it by adding a small constant, usually 1, to each count:

P(x | C) = (count(x, C) + α) / (count(C) + α * k)

where α is the smoothing constant and k is the number of possible values of the feature. In scikit-learn, this is the alpha parameter.

Naive Bayes Algorithm Pseudocode

Here is the pseudo code for naive bayes algorithm in a form that maps directly to code, and anyone looking for pseudo code for naive bayes algorithm tutorials will find the same two functions at the core. This naive bayes algorithm pseudocode covers both training and prediction for categorical features.

TRAIN(dataset D with features x1..xn and class labels):

    for each class c in D:

        prior[c] = count(rows with class c) / count(all rows)

        for each feature i:

            for each value v of feature i:

                likelihood[c][i][v] = (count(rows with class c and xi = v) + alpha)

                                      / (count(rows with class c) + alpha * number_of_values(i))

    return prior, likelihood

PREDICT(new example x1..xn):

    for each class c:

        score[c] = log(prior[c])

        for each feature i:

            score[c] = score[c] + log(likelihood[c][i][xi])

    return class c with the highest score[c]

For continuous features, the likelihood lines are replaced by a probability density, usually a normal distribution fitted to each feature within each class. That variant is covered in the types section below.

Worked Numerical Example

The classic way to see the naive bayes algorithm in action is the Play Tennis dataset. It has 14 days of weather, with a record of whether tennis was played.

Day

Outlook

Temperature

Humidity

Wind

Play

1

Sunny

Hot

High

Weak

No

2

Sunny

Hot

High

Strong

No

3

Overcast

Hot

High

Weak

Yes

4

Rain

Mild

High

Weak

Yes

5

Rain

Cool

Normal

Weak

Yes

6

Rain

Cool

Normal

Strong

No

7

Overcast

Cool

Normal

Strong

Yes

8

Sunny

Mild

High

Weak

No

9

Sunny

Cool

Normal

Weak

Yes

10

Rain

Mild

Normal

Weak

Yes

11

Sunny

Mild

Normal

Strong

Yes

12

Overcast

Mild

High

Strong

Yes

13

Overcast

Hot

Normal

Weak

Yes

14

Rain

Mild

High

Strong

No

Suppose a new day is Sunny, Cool, High humidity, and Strong wind. Will tennis be played? The counts give nine Yes days and five No days, so the priors are 9/14 and 5/14.

Feature Value

P(value | Yes)

P(value | No)

Outlook = Sunny

2/9

3/5

Temperature = Cool

3/9

1/5

Humidity = High

3/9

4/5

Wind = Strong

3/9

3/5

Multiplying each class's prior by its four likelihoods:

Score(Yes) = 9/14 x 2/9 x 3/9 x 3/9 x 3/9 = 0.00529

Score(No)  = 5/14 x 3/5 x 1/5 x 4/5 x 3/5 = 0.02057

Dividing each score by their sum gives posterior probabilities of about 20.5% for Yes and 79.5% for No. The model predicts that tennis will not be played. 

Notice that no day in the data had Overcast weather together with a No outcome. If we asked about an Overcast day, the No score would be zero because of that missing combination, which is exactly the case Laplace smoothing is designed to handle.

Different Types of Naive Bayes Algorithms

All the variants share the same Bayes-plus-independence core. They differ in how they model P(feature | class), which depends on the kind of data.

Type

Feature Data

Likelihood Model

Typical Use

Gaussian

Continuous numbers

Normal distribution per feature and class

Measurements, sensor data, medical values

Multinomial

Counts or frequencies

Multinomial distribution

Text classification with word counts

Bernoulli

Binary yes or no features

Bernoulli distribution

Short text, presence or absence of words

Complement

Counts, especially imbalanced classes

Statistics from the complement of each class

Imbalanced text classification

Categorical

Discrete categories

Categorical distribution per feature

Survey or tabular data with categories

Gaussian Naive Bayes 

Gaussian Naive Bayes deserves a closer look because it extends the naive bayes algorithm to numeric data. During training, it calculates the mean and variance of each feature separately for each class. 

To score a new value, it plugs the value into the normal curve for that class and feature, which gives a likelihood in place of a simple count ratio. The formula is:

P(x | C) = 1 / sqrt(2 pi var) exp(-(x - mean)^2 / (2 var))

Because only a mean and a variance are stored per feature and class, the model stays very small. The weakness is the bell-curve assumption. A feature with two humps, or a long tail, will be modeled badly, and a log or power transform often helps before fitting.

Multinomial vs Bernoulli for Text

These two are often confused. 

Multinomial Naive Bayes cares how many times a word appears, so a message with the word "free" five times scores higher than one with it once. Bernoulli Naive Bayes cares only whether the word appears, and it also penalizes the absence of words that are typical for a class. In short messages, Bernoulli can win. On longer documents, Multinomial usually does.

Naive Bayes Algorithm in Python Using Scikit-learn

Scikit-learn includes ready-made versions of each type, which makes the naive bayes algorithm one of the easiest models to try in Python. 

The code below shows two common cases: a tiny spam filter built with Multinomial Naive Bayes on word counts, and Gaussian Naive Bayes on the numeric Iris dataset.

Python Code Example

from sklearn.feature_extraction.text import CountVectorizer

from sklearn.naive_bayes import MultinomialNB, GaussianNB

from sklearn.datasets import load_iris

from sklearn.model_selection import train_test_split

from sklearn.metrics import accuracy_score

# 1. Text classification with Multinomial Naive Bayes

texts = [

    "win a free prize now", "limited offer claim your free reward",

    "urgent claim cash prize today", "free entry win money now",

    "meeting moved to 3 pm tomorrow", "please review the attached report",

    "lunch with the team on friday", "can you send the project schedule",

]

labels = ["spam", "spam", "spam", "spam", "ham", "ham", "ham", "ham"]

vec = CountVectorizer()

X = vec.fit_transform(texts)

model = MultinomialNB(alpha=1.0)  # alpha=1.0 is Laplace smoothing

model.fit(X, labels)

new = ["claim your free prize", "send the report before the meeting"]

pred = model.predict(vec.transform(new))

proba = model.predict_proba(vec.transform(new))

for text, p, pr in zip(new, pred, proba):

    print(f"{text!r} -> {p}  (ham={pr[0]:.2f}, spam={pr[1]:.2f})")

# 2. Gaussian Naive Bayes on numeric features

Xi, yi = load_iris(return_X_y=True)

Xtr, Xte, ytr, yte = train_test_split(Xi, yi, test_size=0.3, random_state=42, stratify=yi)

gnb = GaussianNB().fit(Xtr, ytr)

print("Iris accuracy:", round(accuracy_score(yte, gnb.predict(Xte)), 3))

The output from a test run:

'claim your free prize' -> spam  (ham=0.01, spam=0.99)

'send the report before the meeting' -> ham  (ham=0.99, spam=0.01)

Iris accuracy: 0.911

Tips for Real Projects

Use more data than this example, and evaluate with precision, recall, and F1 as well as accuracy when classes are uneven. 

Tune alpha with cross-validation, since the best value is often below 1 for large text datasets. Try TF-IDF features in place of raw counts. For text with a heavy class imbalance, compare ComplementNB against MultinomialNB. Because training involves only counting, you can also update a model with new data using partial_fit on streaming or very large datasets.

Real-World Applications of the Naive Bayes Algorithm

The naive bayes algorithm is used in several applications including spam filtering, sentiment analysis and more. Let’s explore each application in detail.

Application

How Naive Bayes Is Used

Why It Fits

Spam filtering

Scores emails by the words they contain

Fast on huge vocabularies and learns from user feedback

Sentiment analysis

Classifies reviews or posts as positive, negative, or neutral

Strong baseline for text with little tuning

Document and news categorization

Assigns articles to topics such as sports or finance

Handles thousands of word features easily

Medical screening

Estimates the chance of a condition from test results and symptoms

Produces probabilities and works with limited records

Recommendation and personalization

Predicts whether a user will like an item based on past behavior

Cheap to train and to update

Real-time prediction

Classifies events as they stream in

Prediction cost is tiny, so latency is low

Fraud detection and intrusion detection

Flags unusual transactions or network events

Quick baseline, and easy to retrain as patterns shift

Language identification

Guesses the language of a text from character patterns

Simple counts work well

Weather and risk forecasting

Predicts categories like rain or no rain from conditions

Works with categorical and numeric inputs

In many of these cases the algorithm isn't the final system. Teams often use it as a quick first model to check whether a problem is learnable, and then move to a heavier method only if the gain justifies the added cost.

When to Use and When to Avoid Naive Bayes

The naive bayes algorithm is a strong first choice in some situations and a weak one in others. The table lists common scenarios with the reason for each call.

Scenario

Use or Avoid

Reason

Text classification with many word features

Use

Handles very high-dimensional sparse data quickly and accurately enough

Small training dataset

Use

Needs few examples to estimate probabilities, and has low risk of overfitting

Need a fast baseline

Use

Trains in seconds and is easy to explain

Real-time or low-latency predictions

Use

Prediction is a few multiplications

Streaming or very large data

Use

Supports incremental updates with partial_fit

Multiclass problems

Use

Extends to many classes without changes

Features that are strongly correlated

Avoid

Breaks the independence assumption and double-counts evidence

Need well-calibrated probabilities

Avoid

Outputs are often overconfident, so calibrate them or use another model

Complex interactions between features

Avoid

Can't capture that one feature matters only in combination with another

Regression, where you predict a number

Avoid

It's a classification method, so use a regression model

Continuous features that aren't bell-shaped

Avoid, or transform first

Gaussian Naive Bayes will fit them poorly

Maximum accuracy on a rich, large tabular dataset

Avoid

Gradient boosting or neural networks usually do better

Many of the "avoid" rows have workarounds. Correlated features can be reduced with feature selection or PCA in ML before fitting, probability outputs can be calibrated with isotonic or sigmoid calibration, and skewed continuous features can be transformed. If you find yourself applying several of these fixes at once, it's usually a sign that a different model suits the data better, such as logistic regression or a tree-based method.

Conclusion

The Naive Bayes algorithm proves that good machine learning does not necessarily mean complicated models. Simple, quick training, and ability to deal with scarce data make it a convenient classifier.

Use Naive Bayes as a starting point; assess its predictions and restrictions. Think about complicated models only in case of necessity.


Rahul Singh

Rahul Singh

40+ of articles published


Current role in the industry :

Associate - Content Marketing

Education Qualification :

B.Tech in Computer Science & Engineering

Expertise :

Artificial intelligenceMachine Learning (ML)Data ScienceFull-Stack DevelopmentData Structures & Algorithms

Tools & Technologies :

PythonReact.js & Next.jsJavaScript (ES6+)SQLTailwind CSSNode.js & MongoDBGit & GitHubSEO Tools (SEMRush)Google Search ConsoleTableau / Power BIFigma

About

Rahul Singh is an Associate Content Writer, with a strong interest in Generative AI, Agentic AI and AI-Native Software Engineering. He combines technical development skills with data-driven strategies to build scalable applications and optimize digital content. Rahul specializes in simplifying complex concepts across AI, ML and software development into practical, easy-to-understand insights, helping learners understand how AI products, systems and services are built and applied. He focuses on real world applications and explains advanced topics in a clear, step by step manner so you can follow along without confusion. His work connects theory with hands-on examples, covering AI-assisted development, intelligent automation and AI integration in software applications. He aims to help you learn faster, create better projects, and apply your knowledge confidently in real scenarios.

Follow me on :

No blogs published yet.

Frequently Asked Questions

FAQ

Ready to Take the Next Step? Enroll Today!