The Wayback Machine - https://web.archive.org/web/20240906001352/https://www.geeksforgeeks.org/ml-naive-bayes-scratch-implementation-using-python/
Open In App

ML | Naive Bayes Scratch Implementation using Python

Last Updated : 10 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

A key concept in probability theory, the Bayes theorem, provides the foundation for the probabilistic classifier known as Naive Bayes. It is a simple yet powerful algorithm that has risen in popularity because of its understanding, simplicity, and ease of implementation. Naive Bayes Algorithm is a popular method for classification applications, especially spam filtering and text classification. In this article, we will learn about Naive Bayes Classifier From Scratch in Python.

What is Naive Bayes? 

Naive Bayes is a family of probabilistic machine learning algorithms based on the Bayes Theorem with an assumption of independence among the features. The Naive Bayes classifier assumes that the presence of a feature in a class is not related to any other feature. Naive Bayes is a classification algorithm for binary and multi-class classification problems.

Naive Bayes Theorem 

  • Based on prior knowledge of conditions that may be related to an event, Bayes theorem describes the probability of the event
  • conditional probability can be found this way
  • Assume we have a Hypothesis(H) and evidence(E), 
    According to Bayes theorem, the relationship between the probability of the Hypothesis before getting the evidence represented as P(H) and the probability of the hypothesis after getting the evidence represented as P(H|E) is:
P(H|E) = P(E|H)*P(H)/P(E)
  • Prior probability = P(H) is the probability before getting the evidence 
    Posterior probability = P(H|E) is the probability after getting evidence
  • In general, 
P(class|data) = (P(data|class) * P(class)) / P(data)

Naive Bayes Theorem Example 

Assume we have to find the probability of the randomly picked card to be king given that it is a face card. 

There are 4 Kings in a Deck of Cards which implies that

P(King) = 4/52 

as all the Kings are face Cards so

P(Face|King) = 1 

there are 3 Face Cards in a Suit of 13 cards and there are 4 Suits in total so

P(Face) = 12/52 

Therefore, 

P(King|face) = P(face|king)*P(king)/P(face) = 1/3

For Dataset: Download dataset here

Naive Bayes Scratch Implementation using Python

Here we are implementing a Naive Bayes Algorithm using Gaussian distributions. It performs all the necessary steps from data preparation and model training to testing and evaluation.

Importing Libraries

Importing necessary libraries:

  • math: for mathematical operations
  • random: for random number generation
  • pandas: for data manipulation
  • numpy: for scientific computing
Python
import math
import random
import pandas as pd
import numpy as np

Encode Class

The encode_class function converts class labels in the dataset into numeric values. It assigns a unique numeric identifier to each class.

Python
def encode_class(mydata):
    classes = []
    for i in range(len(mydata)):
        if mydata[i][-1] not in classes:
            classes.append(mydata[i][-1])
    for i in range(len(classes)):
        for j in range(len(mydata)):
            if mydata[j][-1] == classes[i]:
                mydata[j][-1] = i
    return mydata

Data Splitting

The splitting function is used to split the dataset into training and testing sets based on the given ratio.

Python
def splitting(mydata, ratio):
    train_num = int(len(mydata) * ratio)
    train = []
    test = list(mydata)
    while len(train) < train_num:
        index = random.randrange(len(test))
        train.append(test.pop(index))
    return train, test

Group Data by Class

The groupUnderClass function takes the data and returns a dictionary where each key is a class label and the value is a list of data points belonging to that class.

Python
def groupUnderClass(mydata):
    data_dict = {}
    for i in range(len(mydata)):
        if mydata[i][-1] not in data_dict:
            data_dict[mydata[i][-1]] = []
        data_dict[mydata[i][-1]].append(mydata[i])
    return data_dict

Calculate Mean and Standard Deviation for Class

The MeanAndStdDev function takes a list of numbers and calculates the mean and standard deviation.

The MeanAndStdDevForClass function takes the data and returns a dictionary where each key is a class label and the value is a list of lists, where each inner list contains the mean and standard deviation for each attribute of the class.

Python
def MeanAndStdDev(numbers):
    avg = np.mean(numbers)
    stddev = np.std(numbers)
    return avg, stddev

def MeanAndStdDevForClass(mydata):
    info = {}
    data_dict = groupUnderClass(mydata)
    for classValue, instances in data_dict.items():
        info[classValue] = [MeanAndStdDev(attribute) for attribute in zip(*instances)]
    return info

Calculate Gaussian and Class Probabilities

  • The calculateGaussianProbability function takes a value, mean, and standard deviation and calculates the probability of the value occurring under a Gaussian distribution with that mean and standard deviation.
  • The calculateClassProbabilities function takes the information dictionary and a test data point as arguments. It iterates through each class and calculates the probability of the test data point belonging to that class based on the mean and standard deviation of each attribute for that class.
Python
def calculateGaussianProbability(x, mean, stdev):
    epsilon = 1e-10
    expo = math.exp(-(math.pow(x - mean, 2) / (2 * math.pow(stdev + epsilon, 2))))
    return (1 / (math.sqrt(2 * math.pi) * (stdev + epsilon))) * expo

def calculateClassProbabilities(info, test):
    probabilities = {}
    for classValue, classSummaries in info.items():
        probabilities[classValue] = 1
        for i in range(len(classSummaries)):
            mean, std_dev = classSummaries[i]
            x = test[i]
            probabilities[classValue] *= calculateGaussianProbability(x, mean, std_dev)
    return probabilities

Prediction for Test Set

  • The predict function takes the information dictionary and a test data point as arguments. It calculates the class probabilities and returns the class with the highest probability.
  • The getPredictions function takes the information dictionary and the test set as arguments. It iterates through each test data point and predicts its class using the predict function.
Python
def predict(info, test):
    probabilities = calculateClassProbabilities(info, test)
    bestLabel = max(probabilities, key=probabilities.get)
    return bestLabel

def getPredictions(info, test):
    predictions = [predict(info, instance) for instance in test]
    return predictions

Calculate Accuracy

The accuracy_rate function takes the test set and the predictions as arguments. It compares the predicted classes with the actual classes and calculates the percentage of correctly predicted data points.

Python
def accuracy_rate(test, predictions):
    correct = sum(1 for i in range(len(test)) if test[i][-1] == predictions[i])
    return (correct / float(len(test))) * 100.0
 

Load and Preprocess Data

The code then loads the data from a CSV file using pandas and converts it into a list of lists. It then encodes the class labels and converts all attributes to floating-point numbers.

Python
# Load data using pandas
filename = '/content/diabetes_data.csv'  # Add the correct file path
df = pd.read_csv(filename)
mydata = df.values.tolist()

# Encode classes and convert attributes to float
mydata = encode_class(mydata)
for i in range(len(mydata)):
    for j in range(len(mydata[i]) - 1):
        mydata[i][j] = float(mydata[i][j])

Split Data into Training and Testing Sets

The code splits the data into training and testing sets using a specified ratio. It then trains the model by calculating the mean and standard deviation for each attribute in each class.

Python
# Split the data into training and testing sets
ratio = 0.7
train_data, test_data = splitting(mydata, ratio)

print('Total number of examples:', len(mydata))
print('Training examples:', len(train_data))
print('Test examples:', len(test_data))

Output:

Total number of examples: 768
Training examples: 537
Test examples: 231

Train and Test the Model

Calculate mean and standard deviation for each attribute within each class for the training set. Finally, it tests the model on the test set and calculates the accuracy.

Python
# Train the model
info = MeanAndStdDevForClass(train_data)

# Test the model
predictions = getPredictions(info, test_data)
accuracy = accuracy_rate(test_data, predictions)
print('Accuracy of the model:', accuracy)

Output:

Accuracy of the model: 100.0

Conclusion

In summary, Naive Bayes proves to be an efficient and surprisingly simple algorithm that works well for classification tasks. It is a useful tool for machine learning enthusiasts since it is based on Bayes’ theorem and is simple to use and analyze. Naive Bayes Algorithm -Implementation from scratch in Python can yield useful insights and precise predictions for a variety of applications with careful implementation and analysis.

Frequently Asked Question(FAQs)

1. How to implement Naive Bayes from scratch with Python?

Implementing Naive Bayes from scratch in Python involves defining the necessary functions for calculating the probabilities required for Bayes’ theorem. This includes the prior probability of each class, the conditional probability of each feature given a class, and the likelihood of a given class. Once these probabilities are calculated, Bayes’ theorem can be used to classify new data points.

2. How does Naive Bayes Algorithm works?

Naive Bayes is a probabilistic classifier based on Bayes’ theorem, which states that the probability of an event (hypothesis) given evidence can be calculated as the product of the prior probability of the hypothesis and the likelihood of the evidence given the hypothesis, divided by the marginal probability of the evidence. In the context of Naive Bayes, the hypothesis represents the class label, the evidence represents the features of the data point, and the prior and likelihood probabilities are estimated from the training data.

3. What is Naive Bayes?

Naive Bayes is a classification algorithm based on Bayes’ theorem, which is a statistical method for calculating the probability of an event given a set of conditions. In Naive Bayes, the naive assumption is made that the features of the data are independent of each other, which simplifies the calculations.

4. Why is Naive Bayes a popular algorithm?

Naive Bayes is a popular algorithm due to its simplicity, efficiency, and effectiveness. It is often used as a baseline classifier for comparison with other more complex algorithms.

5. When should I use Naive Bayes?

Naive Bayes is a good choice for problems where the features of the data are relatively independent and where the training data is limited. It is also a good choice for problems where the computational cost is a concern.



Previous Article
Next Article

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
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
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
Gaussian Naive Bayes
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 pop
6 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
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
Variable importance for support vector machine and naive Bayes classifiers in R
Understanding the importance of variables in a model is crucial for interpreting and improving the model's performance. Variable importance helps identify which features contribute most to the prediction. In this article, we will explore how to assess variable importance for Support Vector Machine (SVM) and Naive Bayes classifiers in R Programming
3 min read
How to produce a confusion matrix and find the misclassification rate of the Naive Bayes Classifier in R?
Producing a confusion matrix and calculating the misclassification rate of a Naive Bayes Classifier in R involves a few straightforward steps. In this guide, we'll use a sample dataset to demonstrate how to interpret the results. Understanding Confusion MatrixA confusion matrix is a table that describes the performance of a classification model by
3 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 R. What is Naive Bayes?Naive Bayes is a family of
6 min read
How to create Naive Bayes in R for numerical and categorical variables
Naive Bayes classifiers are simple yet powerful probabilistic classifiers based on Bayes' theorem. They are particularly useful for large datasets and have applications in various domains, including text classification, spam detection, and medical diagnosis. This article will guide you through the process of creating a Naive Bayes classifier in R t
4 min read
Implementation of Ridge Regression from Scratch using Python
Prerequisites: Linear Regression Gradient Descent Introduction: Ridge Regression ( or L2 Regularization ) is a variation of Linear Regression. In Linear Regression, it minimizes the Residual Sum of Squares ( or RSS or cost function ) to fit the training examples perfectly as possible. The cost function is also represented by J. Cost Function for Li
4 min read
Implementation of K-Nearest Neighbors from Scratch using Python
Instance-Based LearningK Nearest Neighbors Classification is one of the classification techniques based on instance-based learning. Models based on instance-based learning to generalize beyond the training examples. To do so, they store the training examples first. When it encounters a new instance (or test example), then they instantly build a rel
8 min read
Linear Regression Implementation From Scratch using Python
Linear Regression is a supervised learning algorithm which is both a statistical and a machine learning algorithm. It is used to predict the real-valued output y based on the given input value x. It depicts the relationship between the dependent variable y and the independent variables xi ( or features ). The hypothetical function used for predicti
4 min read
Implementation of Logistic Regression from Scratch using Python
Introduction:Logistic Regression is a supervised learning algorithm that is used when the target variable is categorical. Hypothetical function h(x) of linear regression predicts unbounded values. But in the case of Logistic Regression, where the target variable is categorical we have to strict the range of predicted values. Consider a classificati
5 min read
Implementation of Lasso Regression From Scratch using Python
For regularization and feature selection, Lasso Regression, also known as the Least Absolute Shrinkage and Selection Operator, is a linear regression technique. The cost function of linear regression, which is the sum of squared discrepancies between predicted and actual values, gains a penalty element. The absolute value of the coefficients multip
11 min read
Sklearn | Multi-dimensional Scaling (MDS) Python Implementation from Scratch
Scikit-learn (sklearn) is a Python machine-learning package that is open-source and free to use. It is Python's most popular machine-learning library, and it is extensively used in business and academics. Scikit-learn includes a wide range of machine learning methods, including supervised learning (classification, regression), unsupervised learning
10 min read
Implementation of Radius Neighbors from Scratch in Python
Radius Neighbors is also one of the techniques based on instance-based learning. Models based on instance-based learning generalize beyond the training examples. To do so, they store the training examples first. When it encounters a new instance (or test example), then they instantly build a relationship between stored training examples and this ne
8 min read
ANN - Implementation of Self Organizing Neural Network (SONN) from Scratch
Prerequisite: ANN | Self Organizing Neural Network (SONN) Learning Algorithm To implement a SONN, here are some essential consideration- Construct a Self Organizing Neural Network (SONN) or Kohonen Network with 100 neurons arranged in a 2-dimensional matrix with 10 rows and 10 columns Train the network with 1500 2-dimensional input vectors randomly
4 min read
Bidirectional Associative Memory (BAM) Implementation from Scratch
Prerequisite: ANN | Bidirectional Associative Memory (BAM) Learning AlgorithmTo implement BAM model, here are some essential consideration and approach- Consider the value of M, as BAM will be constructed with M pairs of patterns. Here the value of M is 4.Set A: Input PatternsSet B: Corresponding Target PatternsAssign the neurons in input and outpu
4 min read
Implementation of Elastic Net Regression From Scratch
Prerequisites: Linear RegressionGradient DescentLasso &amp; Ridge RegressionIntroduction: Elastic-Net Regression is a modification of Linear Regression which shares the same hypothetical function for prediction. The cost function of Linear Regression is represented by J. [Tex]\frac{1}{m} \sum_{i=1}^{m}\left(y^{(i)}-h\left(x^{(i)}\right)\right)^{2}[
5 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 various machine learning algorithms, especially in the
5 min read
Polynomial Regression ( From Scratch using Python )
Prerequisites Linear RegressionGradient DescentIntroductionLinear Regression finds the correlation between the dependent variable ( or target variable ) and independent variables ( or features ). In short, it is a linear model to fit the data linearly. But it fails to fit and catch the pattern in non-linear data. Let's first apply Linear Regression
5 min read
How to Implement Adam Gradient Descent from Scratch using Python?
Grade descent is an extensively used optimization algorithm in machine literacy and deep literacy. It's used to minimize the cost or loss function of a model by iteratively confirming the model's parameters grounded on the slants of the cost function with respect to those parameters. One variant of gradient descent that has gained popularity is the
14 min read
Grid Searching From Scratch using Python
Grid searching is a method to find the best possible combination of hyper-parameters at which the model achieves the highest accuracy. Before applying Grid Searching on any algorithm, Data is used to divided into training and validation set, a validation set is used to validate the models. A model with all possible combinations of hyperparameters i
5 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 algorithms known as Naive Bayes classifiers. It is a family
3 min read
Article Tags :
Practice Tags :