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

Gaussian Naive Bayes

Last Updated : 13 Nov, 2023
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

In the vast field of machine learning, classification algorithms play a pivotal role in making sense of data. One such algorithm, Gaussian Naive Bayes, stands out for its simplicity, efficiency, and effectiveness. In this article, we will delve into the principles behind Gaussian Naive Bayes, explore its applications, and understand why it is a popular choice for various tasks.

Gaussian Naive Bayes

Gaussian Naive Bayes is a type of Naive Bayes method where continuous attributes are considered and the data features follow a Gaussian distribution throughout the dataset. In Sklearn library terminology, Gaussian Naive Bayes is a type of classification algorithm working on continuous normally distributed features that is based on the Naive Bayes algorithm. Before diving deep into this topic we must gain a basic understanding of the principles on which Gaussian Naive Bayes work. Here are some terminologies that can help us gain knowledge and ease our further study:

Naive Bayes Classifier:

The Naive Bayes Classifier is based on a simple concept from probability theory called the Bayes Theorem. This classification algorithm does really well in predicting the correct class the present features belong to. The ‘naive’ in the name of this algorithm is used based on the assumption that this algorithm considers while predicting the label of the features. The assumption here is that all the features are independent of each other, though this might not be true in a real-world scenario. Still, the algorithm works fine. In the training process of a Naive Bayes classifier, the algorithm mainly focuses on two factors based on the dataset it fits:

  • Prior Probability (P(y)): This is the probability of a specific class to happen, this algorithm calculates the prior probability by dividing the occurrence of the class ‘y’ by the total number of instances.
  • Class Conditional Probability(P(\textbf x_i     |y)): This states the presence of each feature x_i     given that the class occurring is the class y. This probability is considered for each class and each feature.

Now discussing about how this algorithm makes prediction or what happens behind the scene of this algorithm, Naive Bayes considers the probability of occurrence of each class and assigns the label value to the class with higher probability.

  • Posterior Probability(P(y|x)): This is the probability that will help the algorithm determine each class’ probability of occurrence. Here P(y|x) tells us about the occurrence of class y given the feature x. It is calculated by the help of Bayes theorem given by: P(y|x) = (P(x|y)*P(y))/(P(x)) we will also talk about Bayes theorem in a while.
  • P(x|y): This is the product of all the conditional probabilities of each feature x_i     given a class y. It is given by P(x_1|y) * P(x_2|y) * P(x_3|y)     … and so on.
  • P(x): This is the probability of occurrence of feature x, it reduces a probability function to a distributed function where the total probability is 1.

This algorithm then compares different posterior probabilities according to the number of classes present in the data and the class with higher probability is assigned to the feature set present.

Bayes Theorem:

Bayes theorem is a way to develops a way to update probabilities based on new information. The theorem is given as:

\begin{aligned} P(A|B)& = \frac{P(A \cap B)}{P(B)} \\ &= \frac{P(B|A)\cdot P(A) }{P(B)} \end{aligned}

Where P(A|B) is the posterior probability and states probability of occurrence of A given B has happened, P(A) is the prior probability, P(B) is the probability of occurrence of event B, P(B|A) is the probability of occurrence of B given A has already happened.

Gaussian Naive Bayes:

Gaussian Naive Bayes is the application of Naive Bayes on a normally distributed data. Gaussian Naive Bayes assumes that the likelihood(P(x_i|y    )) follows the Gaussian Distribution for each x_i    within y_k    . Therefore,

P(x_i|y) = \frac{1}{\sigma \sqrt{2\pi}} e^{-\frac{(x - \mu)^2}{2\sigma^2}}

To classify each new data point x the algorithm finds out the maximum value of the posterior probability of each class and assigns the data point to that class.

Real life example with Gaussian Naive Bayes:

Here we will be applying Gaussian Naive Bayes to the Iris Dataset, this dataset consists of four features namely Sepal Length in cm, Sepal Width in cm, Petal Length in cm, Petal Width in cm and from these features we have to identify which feature set belongs to which specie class. The iris flower dataset could be obtained from here.

Now we will be using Gaussian Naive Bayes in predicting the correct specie of Iris flower.

Lets break down the above code step by step:

  • First we will be importing the required libraries: pandas for data manipulation, train_test_split to split the data into training and testing sets, GaussianNB for the Gaussian Naive Bayes classifier, accuracy_score to evaluate the model, and LabelEncoder to encode the categorical target variable.

Python3

import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.naive_bayes import GaussianNB
from sklearn.metrics import accuracy_score
from sklearn.preprocessing import LabelEncoder

                    
  • After that we will load the Iris dataset from a CSV file named “Iris.csv” into a pandas DataFrame.
  • Then we will separate the features (X) and the target variable (y) from the dataset. Features are obtained by dropping the “Species” column, and the target variable is set to the “Species” column which we will be predicting.

Python3

# Load the Iris dataset
data = pd.read_csv("Iris.csv")
 
# Select features and target
X = data.drop("Species", axis=1)
y = data['Species']

                    
  • Since the target variable “Species” is categorical, we will be using LabelEncoder to convert it into numerical form. This is necessary for the Gaussian Naive Bayes classifier, as it requires numerical inputs.
  • We will be splitting the dataset into training and testing sets using the train_test_split function. 70% of the data is used for training, and 30% is used for testing. The random_state parameter ensures reproducibility of the same data.

Python3

# Encoding the Species column to get numerical class
le = LabelEncoder()
y = le.fit_transform(y)
 
# Split the data into training and testing sets
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)

                    
  • We will be creating a Gaussian Naive Bayes Classifier(gnb) and then training it on the training data using the fit method.

Python3

# Gaussian Naive Bayes classifier
gnb = GaussianNB()
 
# Train the classifier on the training data
gnb.fit(X_train, y_train)

                    
  • At last we will be using the trained model to make predictions on the testing data.

Python3

# Make predictions on the testing data
y_pred = gnb.predict(X_test)
 
# Calculate the accuracy of the model
accuracy = accuracy_score(y_test, y_pred)
print(f"The Accuracy of Prediction on Iris Flower is: {accuracy}")

                    

Output:

The Accuracy of Prediction on Iris Flower is: 1.0


Similar Reads

Gaussian Naive Bayes using Sklearn
In the world of machine learning, Gaussian Naive Bayes is a simple yet powerful algorithm used for classification tasks. It belongs to the Naive Bayes algorithm family, which uses Bayes' Theorem as its foundation. The goal of this post is to explain the Gaussian Naive Bayes classifier and offer a detailed implementation tutorial for Python users ut
8 min read
How to plot the decision boundary for a Gaussian Naive Bayes classifier in R?
Gaussian Naive Bayes (GNB) is a simple yet powerful algorithm often used for classification problems. One of the key ways to understand and interpret the behavior of this classifier is by visualizing the decision boundary. This article provides a step-by-step guide on how to plot the decision boundary for a Gaussian Naive Bayes classifier in R. Int
3 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 can follow this link. Complement Naive Bayes is s
7 min read
Bernoulli Naive Bayes
Supervised learning is a subcategory of machine learning algorithms. In this way, the models are trained on labeled datasets. Under supervised learning, there are two categories: one is classification, and the other is regression. Classification is used for discrete prediction, while regression is used for continuous value prediction. Naive Bayes T
5 min read
Classification of Text Documents using the approach of Naive Bayes
In natural language processing and machine learning, the Naïve Bayes approach is a potent and popular method for classifying text documents. This method classifies documents into predetermined types based on the likelihood of a word occurring, utilizing the concepts of the Bayes theorem. This article aims to implement Document Classification using
10 min read
Multinomial Naive Bayes
Multinomial Naive Bayes (MNB) is a very popular and efficient machine learning algorithm that is based on Bayes' theorem. It is commonly used for text classification tasks where we need to deal with discrete data like word counts in documents. In this article, we will discuss MNB and implement it. What is Multinomial Naive Bayes?Naive Bayes is a pr
9 min read
Naive Bayes vs. SVM for Text Classification
Text classification is a fundamental task in natural language processing (NLP), with applications ranging from spam detection to sentiment analysis and document categorization. Two popular machine learning algorithms for text classification are Naive Bayes classifier (NB) and Support Vector Machines (SVM). Both approaches have their strengths and w
9 min read
Naive Bayes vs Logistic Regression in Machine Learning
In the vast landscape of machine learning, selecting the most appropriate algorithm for a classification task. Two widely-used algorithms in this context are Naive Bayes and Logistic Regression. Before delving into the detailed comparison, let's establish a clear understanding of each algorithm. Table of Content Naive BayesLogistic RegressionNaive
5 min read
Naive Bayes Classifiers
A Naive Bayes classifiers, a family of algorithms based on Bayes' Theorem. Despite the "naive" assumption of feature independence, these classifiers are widely utilized for their simplicity and efficiency in machine learning. The article delves into theory, implementation, and applications, shedding light on their practical utility despite oversimp
12 min read
Applying Multinomial Naive Bayes to NLP Problems
Multinomial Naive Bayes (MNB) is a popular machine learning algorithm for text classification problems in Natural Language Processing (NLP). It is particularly useful for problems that involve text data with discrete features such as word frequency counts. MNB works on the principle of Bayes theorem and assumes that the features are conditionally i
7 min read
three90RightbarBannerImg