Bernoulli Naive Bayes is a subcategory of the Naive Bayes Algorithm. It is typically used when the data is binary and it models the occurrence of features using Bernoulli distribution. It is used for the classification of binary features such as 'Yes' or 'No', '1' or '0', 'True' or 'False' etc. Here it is to be noted that the features are independent of one another. In this article we will be discussing more about it.
Mathematics behind Bernoulli Naive Bayes
The core of Bernoulli Naive Bayes is based on Bayes' Theorem which helps in calculating the conditional probability of a given class y given some data x = (x_1, x_2, ..., x_n). Now in the Bernoulli Naive Bayes model we assume that each feature is conditionally independent given the class y. This means that we can calculate the likelihood of each feature occurring as:
p(x_i|y)=p(i|y)x_i+(1-p(i|y))(1-x_i)
- Here, p(x_i |y) is the conditional probability of xi occurring provided y has occurred.
- i is the event
- x_i holds binary value either 0 or 1
Now we will learn Bernoulli distribution as Bernoulli Naive Bayes works on that.
Bernoulli distribution
Bernoulli distribution is used for discrete probability calculation. It either calculates success or failure. Here the random variable is either 1 or 0 whose chance of occurring is either denoted by p or (1-p) respectively.
The mathematical formula is given
f(x)=\begin{cases} p^x*(1-p)^{1-x} & \text{if x=0,1} \\ 0 \; otherwise\\ \end{cases}
Now in the above function if we put x=1 then the value of f(x) is p and if we put x=0 then the value of f(x) is 1-p. Here p denotes the success of an event.
Implementing Bernoulli Naive Bayes
For performing classification using Bernoulli Naive Bayes we have considered an email dataset.
The email dataset comprises of four columns named Unnamed: 0, label, label_num and text. The category of label is either ham or spam. For ham the number assigned is 0 and for spam 1 is assigned. Text comprises the body of the mail. The length of the dataset is 5171. The dataset can be downloaded from here.
Python
import numpy as np
import pandas as pd
from sklearn.naive_bayes import BernoulliNB
from sklearn.feature_extraction.text import CountVectorizer
In the above code we have imported necessary libraries like pandas, numpy and sklearn. Bernoulli Naive Bayes is a part of sklearn package.
Python
df=pd.read_csv("spam_ham_dataset.csv")
print(df.shape)
print(df.columns)
df= df.drop(['Unnamed: 0'], axis=1)
Output:
(5171, 4) Index(['Unnamed: 0', 'label', 'text', 'label_num'], dtype='object')
In this above code we have performed a quick data analysis that includes reading the data, dropping unnecessary columns, printing shape of data, information about dataset etc.
Python
x = df["text"].values
y = df["label_num"].values
cv = CountVectorizer()
x = cv.fit_transform(x)
In the above code since text data is used to train our classifier we convert the text into a matrix comprising numbers using Count Vectorizer so that the model can perform well.
Python
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(x, y, test_size=0.20, random_state=0)
bnb = BernoulliNB(binarize=0.0)
model = bnb.fit(X_train, y_train)
y_pred = bnb.predict(X_test)
from sklearn.metrics import classification_report
print(classification_report(y_test, y_pred))
Output:
precision recall f1-score support
0 0.84 0.98 0.91 732
1 0.92 0.56 0.70 303
accuracy 0.86 1035
macro avg 0.88 0.77 0.80 1035
weighted avg 0.87 0.86 0.84 1035
The classification report shows that for class 0 (not spam) precision, recall and F1 score are 0.84, 0.98 and 0.91 respectively. For class 1 (spam) they are 0.92, 0.56 and 0.70. The recall for class 1 drops due to the 13% spam data. The overall accuracy of the model is 86%, which is good.
Bernoulli Naive Bayes is used for spam detection, text classification, Sentiment Analysis and used to determine whether a certain word is present in a document or not.
Difference Between Different Naive Bayes Model
| Aspect | Gaussian Naive Bayes | Multinomial Naive Bayes | Bernoulli Naive Bayes |
|---|
| Feature Type | Continuous (real-valued features) | Discrete (count data or frequency-based features) | Binary (presence or absence of features) |
|---|
| Assumption | Assumes data follows a Gaussian (normal) distribution | Assumes data follows a multinomial distribution | Assumes data follows a Bernoulli (binary) distribution |
|---|
| Common Use Case | Suitable for continuous features like height, weight, etc. | Suitable for text classification (word counts) | Suitable for binary classification tasks (e.g., spam detection) |
|---|
| Data Representation | Features are treated as continuous variables | Features are treated as discrete counts or frequencies | Features are treated as binary (0 or 1) values |
|---|
| Mathematical Model | Uses Gaussian distribution (mean and variance) for each feature | Uses the multinomial distribution for word counts in text classification | Uses Bernoulli distribution (probability of a feature being present) |
|---|
| Example | Predicting whether an email is spam based on numeric features | Predicting whether a document is spam based on word counts | Classifying a document as spam or not based on word presence |
|---|
Here is the quick comparison between types of Naive Bayes that are Gaussian Naive Bayes, Multinomial Naive Bayes and Bernoulli Naive Bayes
Bernoulli Naive Bayes is a simple yet effective for binary classification tasks. Its efficiency in handling binary data makes it suitable for applications like spam detection, sentiment analysis and many more. Its simplicity and speed makes it suitable for real-time classification problems.
Similar Reads
Bernoulli Naive Bayes
Bernoulli Naive Bayes is a subcategory of the Naive Bayes Algorithm. It is typically used when the data is binary and it models the occurrence of features using Bernoulli distribution. It is used for the classification of binary features such as 'Yes' or 'No', '1' or '0', 'True' or 'False' etc. Here
5 min read
Gaussian Naive Bayes
Gaussian Naive Bayes is a type of Naive Bayes method working on continuous attributes and the data features that follows Gaussian distribution throughout the dataset. Before diving deep into this topic we must gain a basic understanding of principles on which Gaussian Naive Bayes work. Here are some
5 min read
Multinomial Naive Bayes
Multinomial Naive Bayes is one of the variation of Naive Bayes algorithm. A classification algorithm based on Bayes' Theorem ideal for discrete data and is typically used in text classification problems. It models the frequency of words as counts and assumes each feature or word is multinomially dis
6 min read
Naive Bayes Classifiers
Naive Bayes classifiers are supervised machine learning algorithms used for classification tasks, based on Bayes' Theorem to find probabilities. This article will give you an overview as well as more advanced use and implementation of Naive Bayes in machine learning. Key Features of Naive Bayes Clas
9 min read
Bernoulli's Principle
Bernoulli's Principle is a very important concept in Fluid Mechanics which is the study of fluids (like air and water) and their interaction with other fluids. Bernoulli's principle is also referred to as Bernoulli's Equation or Bernoulli Theorem. This principle was first stated by Daniel Bernoulli
15+ min read
Multinomial Naive Bayes Classifier in R
The Multinomial Naive Bayes (MNB) classifier is a popular machine learning algorithm, especially useful for text classification tasks such as spam detection, sentiment analysis, and document categorization. In this article, we discuss about the basics of the MNB classifier and how to implement it in
6 min read
Complement Naive Bayes (CNB) Algorithm
Naive Bayes algorithms are a group of very popular and commonly used Machine Learning algorithms used for classification. There are many different ways the Naive Bayes algorithm is implemented like Gaussian Naive Bayes, Multinomial Naive Bayes, etc. To learn more about the basics of Naive Bayes, you
7 min read
Bayes' Theorem
Bayes' Theorem is a mathematical formula that helps determine the conditional probability of an event based on prior knowledge and new evidence. It adjusts probabilities when new information comes in and helps make better decisions in uncertain situations. Bayes Theorem helps us update probabilities
11 min read
Building Naive Bayesian classifier with WEKA
The use of the Naive Bayesian classifier in Weka is demonstrated in this article. The âweather-nominalâ data set used in this experiment is available in ARFF format. This paper assumes that the data has been properly preprocessed. The Bayes' Theorem is used to build a set of classification algorithm
3 min read
Bayes Theorem in Machine learning
Bayes' theorem is fundamental in machine learning, especially in the context of Bayesian inference. It provides a way to update our beliefs about a hypothesis based on new evidence. What is Bayes theorem?Bayes' theorem is a fundamental concept in probability theory that plays a crucial role in vario
5 min read