Machine Learning from Scratch – Day 11: Understanding Naive Bayes Algorithm
Understanding Naive Bayes Algorithm
Series: Machine Learning From Scratch (18 articles)
- …
- 11Machine Learning from Scratch – Day 11: Understanding Naive Bayes Algorithm This article
Introduction
In our previous article, we explored K-Nearest Neighbors (KNN), an algorithm that makes predictions by finding similarities between nearby data points.
Today, we are going to explore another important machine learning algorithm: Naive Bayes.
Have you ever wondered how your email application identifies spam messages?
For example, imagine receiving an email containing words such as:
- Congratulations!
- You won a prize!
- Claim your reward now!
- Limited-time offer!
Your email application may classify this message as spam based on patterns learned from previously labeled emails.
One algorithm that can perform this type of classification is Naive Bayes.
It uses probability to estimate which category a particular input is most likely to belong to.
Let's understand how it works.
1. What is Naive Bayes?
Naive Bayes is a supervised machine learning algorithm mainly used for classification problems.
It is based on Bayes' Theorem, a mathematical formula used to calculate the probability of an event based on previously available information.
The algorithm is called "Naive" because it assumes that features are conditionally independent of each other given the target class.
Although this assumption is often not completely true in real-world datasets, Naive Bayes can still perform surprisingly well.
Common applications include:
- Email spam detection
- Sentiment analysis
- Document classification
- News categorization
- Text classification
2. Understanding Bayes' Theorem
Before understanding the algorithm, let's learn the mathematical concept behind it.
Bayes' Theorem is expressed as:
P(A|B) = [P(B|A) × P(A)] / P(B)
Let's understand each term:
- P(A|B): Probability of event A occurring given that B has occurred.
- P(B|A): Probability of event B occurring given that A has occurred.
- P(A): Prior probability of event A.
- P(B): Probability of event B.
In simple terms, Bayes' Theorem helps us update our belief about an event when new information becomes available.
A simple example
Suppose we want to determine whether an email is spam based on whether it contains the word "free".
Assume we have the following information:
- 40% of emails are spam.
- 60% of emails are not spam.
- 70% of spam emails contain the word "free".
- 10% of non-spam emails contain the word "free".
We want to calculate the probability that an email is spam given that it contains the word "free".
Using Bayes' Theorem:
P(Spam | Free) = [P(Free | Spam) × P(Spam)] / P(Free)
First, calculate P(Free):
P(Free) = (0.70 × 0.40) + (0.10 × 0.60)
P(Free) = 0.28 + 0.06 = 0.34
Now:
P(Spam | Free) = (0.70 × 0.40) / 0.34
P(Spam | Free) = 0.28 / 0.34
P(Spam | Free) ≈ 0.8235
Therefore, the probability that an email is spam, given that it contains the word "free", is approximately 82.35%.
Notice that the word "free" alone does not guarantee that an email is spam. It simply increases the estimated probability.
3. How Does Naive Bayes Work?
Naive Bayes uses probabilities to determine the most likely class for a given input.
Its working process can be divided into four steps.
Step 1: Collect training data
The algorithm receives a labeled dataset.
For example, emails labeled as Spam or Not Spam.
Step 2: Calculate prior probabilities
It calculates the probability of each class.
For example:
- P(Spam)
- P(Not Spam)
Step 3: Calculate feature probabilities
It estimates how likely each feature is to occur within each class.
For example:
- P(Free | Spam)
- P(Free | Not Spam)
Step 4: Predict the class
For a new email, the algorithm combines the probabilities and selects the class with the highest posterior probability.
The algorithm generally compares:
P(Spam | Features)
and
P(Not Spam | Features)
The class with the higher probability becomes the prediction.
4. Understanding the Naive Independence Assumption
The most important assumption behind Naive Bayes is that features are conditionally independent given the class.
Let's understand this with an example.
Consider an email containing these words:
- Free
- Prize
- Winner
In real life, these words may be related to one another.
However, Naive Bayes treats their occurrences as conditionally independent when calculating the probability of a class.
This simplifies the calculations considerably.
The assumption may not perfectly represent real-world relationships, but the algorithm can still work well for many classification tasks.
5. Types of Naive Bayes Algorithms
Different versions of Naive Bayes are designed for different types of data.
1. Gaussian Naive Bayes
Used when numerical features are assumed to follow a Gaussian (normal) distribution within each class.
Example:
- Predicting whether a customer will purchase a product based on age and income.
2. Multinomial Naive Bayes
Commonly used for discrete counts, particularly word counts in text classification.
Example:
- Email spam detection.
- News article classification.
3. Bernoulli Naive Bayes
Used when features are binary, usually represented as 0 or 1.
Example:
- Whether a particular word appears in a document.
Algorithm | Suitable data | Example |
|---|---|---|
Gaussian NB | Continuous numerical features | Measurements |
Multinomial NB | Discrete counts | Word frequencies |
Bernoulli NB | Binary features | Word presence or absence |
Choosing the correct variant depends on how your features are represented.
6. What Is Laplace Smoothing?
While calculating probabilities, we may encounter a problem called the zero-frequency problem.
Imagine that the word "discount" has never appeared in the spam emails in our training dataset.
The calculated probability of that word appearing in spam would be zero.
When probabilities are multiplied together, a single zero can make the entire result zero.
To avoid this, Naive Bayes uses a technique called Laplace Smoothing.
For a categorical or word-count feature, a common formula is:
P(word | class) = (Count(word, class) + α) / (Total words in class + α × Vocabulary size)
Here:
- Count(word, class): Number of occurrences of the word in that class.
- α: Smoothing parameter.
- Vocabulary size: Number of distinct words in the vocabulary.
When α = 1, it is commonly called add-one smoothing.
This technique prevents unseen words from receiving a zero probability.
7. Implementing Naive Bayes Using Python
Now let's implement Naive Bayes using Scikit-learn.
We will use the Iris dataset and Gaussian Naive Bayes to classify flower species.
Step 1: Import libraries
from sklearn.datasets import load_irisfrom sklearn.model_selection import train_test_splitfrom sklearn.naive_bayes import GaussianNBfrom sklearn.metrics import accuracy_score, classification_reportStep 2: Load the dataset
iris = load_iris()
X = iris.datay = iris.targetThe dataset contains four numerical features describing three different flower species.
Step 3: Split the dataset
X_train, X_test, y_train, y_test = train_test_split( X, y, test_size=0.2, random_state=42, stratify=y)We use 80% of the dataset for training and 20% for testing.
Step 4: Create and train the model
model = GaussianNB()
model.fit(X_train, y_train)Here, GaussianNB implements the Gaussian Naive Bayes algorithm.
Step 5: Make predictions
y_pred = model.predict(X_test)The model predicts the flower species for the testing data.
Step 6: Evaluate the model
accuracy = accuracy_score(y_test, y_pred)
print("Accuracy:", accuracy)
print(classification_report(y_test, y_pred))The classification report provides precision, recall, and F1-score for each class.
The exact accuracy may vary depending on the dataset split and configuration.
8. Advantages and Disadvantages of Naive Bayes
Advantages | Disadvantages |
|---|---|
Simple and easy to implement | Assumes conditional independence |
Fast training and prediction | Correlated features can affect performance |
Works well with many text classification tasks | Zero-frequency problem without smoothing |
Requires relatively little training data | Probability estimates may be poorly calibrated |
Supports multiple classes | Performance depends on the chosen variant |
9. Real-World Applications of Naive Bayes
Naive Bayes is widely used in applications involving classification and probability estimation.
1. Email Spam Detection
Classifies incoming emails as spam or legitimate messages based on learned patterns.
2. Sentiment Analysis
Identifies whether a review or message expresses positive, negative, or neutral sentiment.
3. News Classification
Categorizes news articles into topics such as sports, business, technology, and politics.
4. Document Classification
Automatically organizes documents into predefined categories.
5. Language Detection
Can help identify the likely language of a text using patterns in its characters or words.
10. Key Takeaways
Let's summarize what we learned today:
- Naive Bayes is a supervised classification algorithm.
- It is based on Bayes' Theorem.
- It predicts classes using probabilities.
- It assumes conditional independence between features given the class.
- Gaussian, Multinomial, and Bernoulli are common variants.
- Laplace Smoothing helps solve the zero-frequency problem.
- It is especially useful for many text classification tasks.
Naive Bayes shows us how probability and statistics can be used to build practical machine learning models.
Understanding this algorithm also gives us a foundation for exploring more advanced probabilistic machine learning techniques.
Coming Next – Day 12: Understanding Support Vector Machines (SVM)
In the next article, we will explore Support Vector Machines, an algorithm that finds an optimal decision boundary to separate different classes.
We will understand hyperplanes, support vectors, margins, and kernels, followed by a practical Python implementation.
Series: Machine Learning From Scratch (18 articles)
- …
- 11Machine Learning from Scratch – Day 11: Understanding Naive Bayes Algorithm This article
Enjoyed reading this content? Let the author know!
Your likes, comments, shares, and saves help creators reach more builders.
Loading recommendations
Loading article