Estimate the priors. Count how often each class appears in the training data and divide by the total.
Estimate the likelihoods. For each class and each feature value, calculate how often that value appears within the class.
Apply smoothing. Add a small count to every feature value so that none has a probability of exactly zero.
Score a new example. For each class, multiply the prior by the likelihood of each observed feature value.
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.