Learn Naive Bayes Algorithm For Machine Learning [With Examples]
Updated on Jul 03, 2023 | 15 min read | 7.8k views
Share:
For working professionals
For fresh graduates
More
Updated on Jul 03, 2023 | 15 min read | 7.8k views
Share:
Table of Contents
In mathematics and programming, some of the simplest solutions are usually the most powerful ones. The naïve Bayes Algorithm comes as a classic example of this statement. Even with the strong and rapid advancement and development in the field of Machine Learning, this Naïve Bayes Algorithm still stands strong as one of the most widely used and efficient algorithms. The naïve Bayes Algorithm finds its applications in a variety of problems including Classification tasks and Natural Language Processing (NLP) problems.
To Explore all our courses, visit our machine learning courses
The mathematical hypothesis of the Bayes Theorem serves as the fundamental concept behind this Naïve Bayes Algorithm. In this article, we shall go through the basics of Bayes Theorem, the Naïve Bayes Algorithm along with its implementation in Python with a real-time example problem. Along with these, we shall also look at some advantages and disadvantages of the Naïve Bayes Algorithm in comparison with its competitors.
Before we venture out on understanding the Bayes Theorem and Naïve Bayes Algorithm, let us brush up our existing knowledge upon the fundamentals of Probability.
Get Machine Learning Certification from the World’s top Universities. Earn Masters, Executive PGP, or Advanced Certificate Programs to fast-track your career.
As we all know by definition, given an event A, the probability of that event occurring is given by P(A). In probability, two events A and B are termed as independent events if the occurrence of event A does not alter the probability of occurrence of event B and vice versa. On the other hand, if one’s occurrence changes the probability of the other, then they are termed as Dependent events.
Let us get introduced to a new term called Conditional Probability. In mathematics, Conditional Probability for two events A and B given by P (A| B) is defined as the probability of the occurrence of event A given that event B has already occurred. Depending upon the relationship between the two events A and B as to whether they are dependent or independent, Conditional Probability is calculated in two ways.
Knowing the math behind Probability and Conditional Probabilities, let us now move on towards the Bayes Theorem.
In statistics and probability theory, the Bayes’ Theorem also known as the Bayes’ rule is used to determine the conditional probability of events. In other words, the Bayes’ theorem describes the probability of an event based on prior knowledge of the conditions that might be relevant to the event.
To understand it in a simpler way, consider that we need to know the probability of the price of a house is very high. If we know about the other parameters such as the presence of schools, medical shops and hospitals nearby, then we can make a more accurate assessment of the same. This is exactly what the Bayes Theorem performs.
Such that,
Suppose we have a simple Machine Learning problem with ‘n’ independent variables and the dependent variable which is the output is a Boolean value (True or False). Suppose the independent attributes are categorical in nature let us consider 2 categories for this example. Hence, with these data, we need to calculate the value of the Likelihood Probability, P(B|A).
Hence, on observing the above we find that we need to calculate 2*(2^n -1) parameters in order to learn this Machine Learning model. Similarly, if we have 30 Boolean independent attributes, then the total number of parameters to be calculated will be close to 3 billion which is extremely high in computational cost.
This difficulty in building a Machine Learning model with the Bayes Theorem led to the birth and development of the Naïve Bayes Algorithm.
In order to be practical, the above-mentioned complexity of the Bayes Theorem needs to be reduced. This is exactly achieved in the Naïve Bayes Algorithm by making few assumptions. The assumptions made are that each feature makes an independent and equal contribution to the outcome.
The naïve Bayes Algorithm is a supervised learning algorithm and it is based on the Bayes theorem which is primarily used in solving classification problems. It is one of the simplest and most accurate Classifiers which build Machine Learning models to make quick predictions. Mathematically, it is a probabilistic classifier as it makes predictions using the probability function of the events.
In order to understand the logic behind the assumptions, let us go through a simple dataset to get a better intuition.
Colour | Type | Origin | Theft? |
Black | Sedan | Imported | Yes |
Black | SUV | Imported | No |
Black | Sedan | Domestic | Yes |
Black | Sedan | Imported | No |
Brown | SUV | Domestic | Yes |
Brown | SUV | Domestic | No |
Brown | Sedan | Imported | No |
Brown | SUV | Imported | Yes |
Brown | Sedan | Domestic | No |
From the above-given dataset, we can derive the concepts of the two assumptions that we defined for the Naïve Bayes Algorithm above.
To sum it up, A and B are conditionally independent given C if and only if, given the knowledge that C occurs, knowledge of whether A occurs provides no information on the likelihood of B occurring, and knowledge of whether B occurs provides no information on the likelihood of A occurring. These assumptions make the Bayes algorithm – Naive. Hence the name, Naïve Bayes Algorithm.
Hence for the above-given problem, the Bayes Theorem can be rewritten as –
Such that,
Hence, by substituting the above values, we obtain the Naïve Bayes Formula as,
In order to calculate the posterior probability P(y|X), we have to create a Frequency Table for each attribute against the output. Then converting the frequency tables to Likelihood Tables after which we finally use the Naïve Bayesian equation to calculate the posterior probability for each class. The class with the highest posterior probability is chosen as the outcome of the prediction. Below are the Frequency and likelihood tables for all three predictors.
Frequency Table of Colour Likelihood Table of Colour
Frequency Table of Type Likelihood Table of Type
Frequency Table of Origin Likelihood Table of Origin
Consider the case where we need to calculate the posterior probabilities for the below-given conditions –
Colour | Type | Origin |
Brown | SUV | Imported |
Thus, from the above given formula, we can calculate the Posterior Probabilities as shown below–
P(Yes | X) = P(Brown | Yes) * P(SUV | Yes) * P(Imported | Yes) * P(Yes)
= 2/5 * 2/4 * 2/5 * 1
= 0.08
P(No | X) = P(Brown | No) * P(SUV | No) * P(Imported | No) * P(No)
= 3/5 * 2/4 * 3/5 * 1
= 0.18
From the above-calculated values, as the Posterior Probabilities for No is Greater than Yes (0.18>0.08), then it can be inferred that a car with Brown Colour, SUV Type of an Imported Origin is classified as “No”. Hence, the car is not stolen.
Now that we have understood the math behind the Naïve Bayes algorithm and also visualized it with an example, let us go through its Machine Learning code in Python language.
Related: Naive Bayes Classifier
In order to implement the Naïve Bayes Classification program in Machine Learning using Python, we will be using the very famous ‘Iris Flower Dataset”. The Iris flower data set or Fisher’s Iris data set is a multivariate data set introduced by the British statistician, eugenicist, and biologist Ronald Fisher in 1998. This is a very small and basic dataset that consists of very less numeric data containing information about 3 classes of flowers belonging to the Iris species which are –
There are 50 samples of each of the three species amounting to a total dataset of 150 rows. The 4 attributes (or) independent variables that are used in this dataset are –
The dependant variable is the “species” of the flower that is identified by the above given four attributes.
As always, the primary step in building any Machine Learning model will be to import the relevant libraries. For this, we shall load the NumPy, Mathplotlib and the Pandas libraries for pre-processing the data.
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
The Iris flower dataset to be used for training the Naïve Bayes Classifier shall be loaded into a Pandas DataFrame. The 4 independent variables shall be assigned to the variable X and the final output species variable is assigned to y.
dataset = pd.read_csv(‘https://raw.githubusercontent.com/mk-gurucharan/Classification/master/IrisDataset.csv’)X = dataset.iloc[:,:4].values
y = dataset[‘species’].valuesdataset.head(5)>>
sepal_length sepal_width petal_length petal_width species
5.1 3.5 1.4 0.2 setosa
4.9 3.0 1.4 0.2 setosa
4.7 3.2 1.3 0.2 setosa
4.6 3.1 1.5 0.2 setosa
5.0 3.6 1.4 0.2 setosa
After loading the dataset and the variables, the next step is to prepare the variables that will undergo the training process. In this step, we have to split the X and y variables to training and the test datasets. For this, we shall assign 80% of the data randomly to the training set which will be used for training purposes and the remaining 20% of the data as the test set on which the trained Naïve Bayes Classifier shall be tested for accuracy.
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2)
Though this is an additional process to this small dataset, I am adding this for you to use it in a larger dataset. In this, the data in the training and test sets are scaled down to a range of values between 0 and 1. This reduces the computational cost.
from sklearn.preprocessing import StandardScaler
sc = StandardScaler()
X_train = sc.fit_transform(X_train)
X_test = sc.transform(X_test)
It is in this step that we import the Naïve Bayes class from sklearn library. For this model, we use the Gaussian model, there are several other models such as Bernoulli, Categorical and Multinomial. Thus, the X_train and y_train are fitted to the classifier variable for training purpose.
from sklearn.naive_bayes import GaussianNB
classifier = GaussianNB()
classifier.fit(X_train, y_train)
We predict the class of the species for the Test set using the model trained and compare it with the Real Values of the species class.
y_pred = classifier.predict(X_test)
df = pd.DataFrame({‘Real Values’:y_test, ‘Predicted Values’:y_pred})
df>>
Real Values Predicted Values
setosa setosa
setosa setosa
virginica virginica
versicolor versicolor
setosa setosa
setosa setosa
… … … … …
virginica versicolor
virginica virginica
setosa setosa
setosa setosa
versicolor versicolor
versicolor versicolor
In the above comparison, we see that there is one incorrect prediction that has predicted Versicolor instead of virginica.
As we are dealing with Classification, the best way to evaluate our classifier model is to print the Confusion Matrix along with its accuracy on the test set.
from sklearn.metrics import confusion_matrix
cm = confusion_matrix(y_test, y_pred)from sklearn.metrics import accuracy_score
print (“Accuracy : “, accuracy_score(y_test, y_pred))
cm>>Accuracy : 0.9666666666666667
array([[14, 0, 0],
[ 0, 7, 0],
[ 0, 1, 8]])
The different types of Naive Bayes classifiers in machine learning are as follows:
A multinomial distribution generates certain events whose frequencies are represented by feature vectors. This event model is particularly useful for document classification.
The Gaussian or normal distribution method is assumed to distribute values associated with different features. When plotted, it provides a bell-shaped curve symmetric to the mean of the feature values.
Features in a multivariate Bernoulli event model are independent binary variables or booleans describing inputs. Similar to the multinomial model, it is popular for performing document classification tasks. During these tasks, binary term occurrence features are leveraged instead of term frequencies.
The optimal Naive Bayes classifiers choose the class with the greatest posterior probability of happenings. Even though the name suggests it is optimal, it will go through multiple possibilities. Therefore, the optimal Naive Bayes classifier is slow and time-consuming.
You will have to combine different preprocessing techniques and build a dictionary of words and every word’s count in training data.
The different benefits of the Naive Bayes algorithm are as follows:
A few applications of the Naive Bayes algorithm in machine learning are as follows:
Thus, in this article, we have gone through the basics of the Naïve Bayes Algorithm, understood the math behind the Classification along with a hand-solved example. Finally, we implemented a Machine Learning code to solve a popular dataset using the Naïve Bayes Classification algorithm.
If you’re interested to learn more about AI, machine learning, check out IIIT-B & upGrad’s PG Diploma in Machine Learning & AI which is designed for working professionals and offers 450+ hours of rigorous training, 30+ case studies & assignments, IIIT-B Alumni status, 5+ practical hands-on capstone projects & job assistance with top firms.
Get Free Consultation
By submitting, I accept the T&C and
Privacy Policy
Top Resources