The Wayback Machine - https://web.archive.org/web/20250214112142/https://www.geeksforgeeks.org/bernoulli-naive-bayes/
Open In App

Bernoulli Naive Bayes

Last Updated : 29 Jan, 2025
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Share
Report
News Follow

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

AspectGaussian Naive BayesMultinomial Naive BayesBernoulli Naive Bayes
Feature TypeContinuous (real-valued features)Discrete (count data or frequency-based features)Binary (presence or absence of features)
AssumptionAssumes data follows a Gaussian (normal) distributionAssumes data follows a multinomial distributionAssumes data follows a Bernoulli (binary) distribution
Common Use CaseSuitable for continuous features like height, weight, etc.Suitable for text classification (word counts)Suitable for binary classification tasks (e.g., spam detection)
Data RepresentationFeatures are treated as continuous variablesFeatures are treated as discrete counts or frequenciesFeatures are treated as binary (0 or 1) values
Mathematical ModelUses Gaussian distribution (mean and variance) for each featureUses the multinomial distribution for word counts in text classificationUses Bernoulli distribution (probability of a feature being present)
ExamplePredicting whether an email is spam based on numeric featuresPredicting whether a document is spam based on word countsClassifying 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.


Next Article

Similar Reads

three90RightbarBannerImg