D Dev Duniya
Back to Journal
4 min read

Naive Bayes Classifier Algorithm in Machine Learning | DevDuniya

Ashish Yadav

Ashish Yadav

Published on Dev Duniya
Keep exploring
Compare the details before you buy.

The Naive Bayes algorithm is a powerful and surprisingly effective supervised machine learning algorithm, particularly popular for text classification tasks. It's based on Bayes' Theorem, a fundamental concept in probability theory.

What is Naive Bayes?

Core Idea: Naive Bayes classifiers are a family of probabilistic algorithms that utilize Bayes' Theorem to predict the class of a given data point.

"Naive" Assumption: The key assumption behind Naive Bayes is the "naive" assumption of independence between features. This means the algorithm assumes that the presence or absence of one feature is unrelated to the presence or absence of any other feature, given the class label. While this assumption is often violated in real-world scenarios, Naive Bayes still performs remarkably well in many practical applications.

Bayes' Theorem

Bayes' Theorem describes the probability of an event occurring given the probability of another event that has already occurred.

Formula:

P(A|B) = (P(B|A) * P(A)) / P(B)

where:

  • P(A|B) is the posterior probability of event A given that event B has occurred.
  • P(B|A) is the likelihood of event B given that event A has occurred.
  • P(A) is the prior probability of event A.
  • P(B) is the prior probability of event B.

Types of Naive Bayes

1. Gaussian Naive Bayes:

  • Assumes that the features follow a continuous Gaussian (normal) distribution.
  • Suitable for continuous data.

2. Multinomial Naive Bayes:

  • Designed for discrete data, often used in text classification.
  • Features represent the frequencies or counts of words in a document.

3. Bernoulli Naive Bayes:

  • Deals with binary features (presence/absence of a word, occurrence/non-occurrence of an event).
  • Commonly used in text classification where features represent the presence or absence of words in a document.

Applications of Naive Bayes

Text Classification:

  • Spam detection (classifying emails as spam or not spam)
  • Sentiment analysis (determining the sentiment of a piece of text, e.g., positive, negative, neutral)
  • Topic classification (categorizing documents into different topics)

Image Classification:

  • Classifying images based on their content (e.g., identifying objects in images)

Medical Diagnosis:

  • Predicting the presence or absence of a disease based on patient symptoms.

Example: Text Classification with Multinomial Naive Bayes

from sklearn.naive_bayes import MultinomialNB
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score

# Sample dataset (simplified)
messages = ['This is a spam message', 
            'Urgent! Win a free prize!', 
            'Hello, how are you?', 
            'Order now and save!', 
            'Meeting tomorrow at 10 AM']
labels = ['spam', 'spam', 'ham', 'spam', 'ham'] 

# Create a CountVectorizer to convert text into numerical features
vectorizer = CountVectorizer()
X = vectorizer.fit_transform(messages) 

# Split data into training and testing sets
X_train, X_test, y_train, y_test = train_test_split(X, labels, test_size=0.2, random_state=42)

# Create a Multinomial Naive Bayes classifier
clf = MultinomialNB()

# Train the model
clf.fit(X_train, y_train)

# Make predictions
y_pred = clf.predict(X_test)

# Evaluate accuracy
accuracy = accuracy_score(y_test, y_pred)
print("Accuracy:", accuracy)

Import necessary libraries:

  • MultinomialNB: Imports the Multinomial Naive Bayes classifier from scikit-learn.
  • CountVectorizer: Converts text data into numerical features (e.g., word frequencies).
  • train_test_split: Splits the data into training and testing sets.
  • accuracy_score: Calculates the accuracy of the model.

Prepare the data:

  • Create a list of sample messages and their corresponding labels (spam/ham).
  • Use CountVectorizer to convert the text messages into a numerical representation (e.g., a matrix of word frequencies).
  • Split the data into training and testing sets.

Create and train the model:

  • Create a MultinomialNB classifier.
  • Train the model using the fit() method with the training data.

Make predictions and evaluate:

  • Use the trained model to predict the class labels for the test data.
  • Calculate and print the accuracy of the model.

Advantages of Naive Bayes

  • Simple and easy to implement.
  • Fast training and prediction.
  • Performs well with high-dimensional data (like text data).

Disadvantages of Naive Bayes

  • Naive Assumption: The assumption of feature independence can sometimes be violated.
  • Can be sensitive to the quality of the training data.

Naive Bayes is a valuable algorithm in the machine learning toolkit, particularly for text classification tasks. Its simplicity, speed, and effectiveness make it a popular choice for various real-world applications.

From the product catalog

Explore device specifications

Specification cards update automatically from published catalog products, grouped by brand.

Apple specifications

Explore Apple devices →
Apple Apple iPhone Duo
Apple Apple iPhone Duo specifications

Apple iPhone Duo is a new-generation iPhone model focused on a sleek design, powerful performance, and everyday usability. Explore iPhone Duo specifications, features, display, cameras, battery, and expected price in the USA. Get the latest information about Apple iPhone Duo and its key features. Compare iPhone Duo with other popular Apple iPhone models.

Size (inches)
Open: 4.64 x 6.48 x 0.21 Closed: 4.64 x 3.31 x 0.44
Weight (ounces)
8.96
Display size (inches)
Inner: 7.6-inch (diagonal) all-screen OLED folding display Outer: 5.4-inch (diagonal) all-screen OLED display
Resolution (pixels)
Inner: 1878-by-2670-pixel resolution at 430 ppi Outer: 1398-by-2034-pixel resolution at 460 ppi
See all specifications →
Apple Apple iPhone 18 Pro Max
Apple Apple iPhone 18 Pro Max specifications

Apple iPhone 18 Pro Max is a high-end flagship smartphone designed for powerful performance and advanced photography. Explore iPhone 18 Pro Max specifications, features, display, cameras, battery, and expected price in the USA. Discover the latest upgrades and key features of Apple’s largest Pro iPhone. Compare iPhone 18 Pro Max with other premium flagship smartphones.

Size (inches)
6.43 x 3.07 x 0.34
Weight (ounces)
8.78
Display size (inches)
6.9-inch (diagonal) all-screen OLED display
Resolution (pixels)
2868-by-1320-pixel resolution at 460 ppi
See all specifications →
Apple Apple iPhone 18 Pro
Apple Apple iPhone 18 Pro specifications

Apple iPhone 18 Pro is a premium flagship smartphone with advanced performance and an upgraded camera system. Explore iPhone 18 Pro specifications, features, display, cameras, battery, and expected price in the USA. Get the latest details about Apple’s new Pro model and its key upgrades. Compare iPhone 18 Pro features with other flagship smartphones.

Size (inches)
5.91 x 2.83 x 0.34
Weight (ounces)
7.44
Display size (inches)
6.3-inch (diagonal) all-screen OLED display
Resolution (pixels)
2622-by-1206-pixel resolution at 460 ppi
See all specifications →

Google specifications

Explore Google devices →

Samsung specifications

Explore Samsung devices →