Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Naive Bayes

Naive Bayes

Imagine you are browsing an online bookstore, and the system recommends "Ball Lightning" based on your previous purchases of "The Three-Body Problem" and "The Wandering Earth." Behind this "you might also like" feature is very likely what we are discussing today: Naive Bayes algorithm.

Naive Bayes is a Bayes' theorem-based simple and efficient probabilistic classification algorithm.。

The core idea of Naive Bayes is to calculate, from certain known features (such as books you have bought), the probability of an event (such as you liking another book), and select the category with the highest probability as the prediction result.

Its "naive" aspect lies in a key assumption:all features are mutually independent. That is, when judging whether you like "Ball Lightning," the algorithm considers the two features of having bought "The Three-Body Problem" and having bought "The Wandering Earth" to have no correlation with each other in your decision. Although in reality features are often related, this simplifying assumption makes computation very efficient and works surprisingly well in many practical scenarios (especially text classification).


Core Principle: Bayes' Theorem

To understand Naive Bayes, we must first understand its foundation —Bayes' theorem-based. It describes how to update the probability of an event occurring when some conditions are known.

1. Bayes' Formula

The formula may look a bit abstract, but let's understand it with an example:

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

Scenario: Determine whether an email is spam (Spam).

The Essence of Bayes' Theorem: It uses information we already know (the general patterns of spam P(A) and the word usage habits of spam P(B|A)), combined with newly observed evidence (this email contains "free"), to revise our judgment of this specific event (the probability that this email is spam P(A|B))。

2. Where Is the "Naive" Part?

A true Bayes classifier, when computing P(B|A) , needs to consider the joint probability of all features (B1, B2, B3...), P(B1, B2, B3... | A), which is very complex.

Naive Bayes makes a powerful simplifying assumption:all features are conditionally independent of each other. This means:

P(B1, B2, B3... | A) ≈ P(B1|A) * P(B2|A) * P(B3|A) * ...

This assumption simplifies the complex joint probability calculation into a product of multiple simple probabilities, greatly reducing computational cost.


III. Workflow and Classifier Types

The workflow of a Naive Bayes classifier can be summarized in the following steps:

Depending on the type of feature data, Naive Bayes mainly has the following variants:

Classifier type Applicable feature data type Core assumptions and notes Typical use cases
Gaussian Naive Bayes Continuous data Assume each feature under each class follows aGaussian distribution (normal distribution)。 Classify gender by height and weight; classify iris species by petal dimensions.
Multinomial Naive Bayes Discrete count data Assume features are generated by amultinomial distribution. Especially suitable forText classification, where features are usually word occurrence counts or TF-IDF values. Spam filtering, news topic classification, sentiment analysis (positive/negative reviews).
Bernoulli Naive Bayes Binary data (0/1) Assume features arebinary(present or absent), following a Bernoulli distribution. It focuses on "whether it appears" rather than "how many times it appears." Text classification (using the bag-of-words set model), user behavior analysis (whether clicked, whether purchased).

IV. Hands-On Practice: Implementing Spam Classification with Python

Let's use a simplified example to implement a spam classifier based on Multinomial Naive Bayes by hand.

1. Scenario and Data Preparation

We have some labeled email texts (spam or ham normal emails).

Example

Sample training data: each line is an email content followed by a label ('spam' or 'ham')

train_data

=

[

   

(

"Get a free iPhone prize! Click the link"

,

"spam"

)

,

   

(

"Boss, meeting at 3 PM, please attend on time"

,

"ham"

)

,

   

(

"Congratulations, you've won! Claim your prize now"

,

"spam"

)

,

   

(

"The project report has been sent to your email, please check"

,

"ham"

)

,

   

(

"Limited-time special, 50% off everything, today only"

,

"spam"

)

,

   

(

"Weekend dinner is set for 7 PM, the usual place"

,

"ham"

)

]

2. Code Implementation Steps

Example

Import the necessary libraries

from

sklearn.

feature_extraction

.

text

import

CountVectorizer

from

sklearn.

naive_bayes

import

MultinomialNB

from

sklearn.

pipeline

import

make_pipeline

import

numpy

as

np

Sample training data: each line is an email content followed by a label ('spam' or 'ham')

train_data

=

[

   

(

"Get a free iPhone prize! Click the link"

,

"spam"

)

,

   

(

"Boss, meeting at 3 PM, please attend on time"

,

"ham"

)

,

   

(

"Congratulations, you've won! Claim your prize now"

,

"spam"

)

,

   

(

"The project report has been sent to your email, please check"

,

"ham"

)

,

   

(

"Limited-time special, 50% off everything, today only"

,

"spam"

)

,

   

(

"Weekend dinner is set for 7 PM, the usual place"

,

"ham"

)

]

1. Prepare data: separate texts and labels

texts

=

[

data

[

0

]

for

data

in

train_data

]

 

Email text list

labels

=

[

data

[

1

]

for

data

in

train_data

]

Corresponding label list

2. Create and train a model pipeline

model

=

make_pipeline

(

CountVectorizer

(

)

,

MultinomialNB

(

)

)

model.

fit

(

texts

,

labels

)

3. Prepare new emails for prediction

new_emails

=

[

   

"Get a free coupon, don't miss this chance!"

,

 

Expected spam

   

"Telephone conference at 10 AM tomorrow to discuss the budget"

 

Expected ham

]

4. Make Predictions

predictions

=

model.

predict

(

new_emails

)

prediction_proba

=

model.

predict_proba

(

new_emails

)

Get prediction probabilities

5. Output results (fix quote issues + dynamically match probability labels)

Get the model's class order (avoid hardcoding indices)

class_names

=

model.

classes_

for

email

,

pred

,

proba

in

zip

(

new_emails

,

predictions

,

prediction_proba

)

:

   

Fix nested quote issues: use single quotes for the inner layer, or single quotes for the outer layer

   

print

(

f

'Email content: "{email}"'

)

   

print

(

f

" Predicted class: {pred}"

)

   

Dynamically output the probability of each class (more robust)

   

for

cls

,

prob

in

zip

(

class_names

,

proba

)

:

       

print

(

f

" Probability of belonging to '{cls}': {prob:.4f}"

)

   

print

(

"-"

40

)

3. Code Explanation

Data separation: Store the texts and labels in the training data into two separate lists, which is the format required by the sklearn library.

Build the model pipeline:

Model training:model.fit(texts, labels) is the core training process. The algorithm computes here:

Prediction and Output: For a new email, the model first converts it into a feature vector, then computes the probability of it belonging to each class according to Bayes' formula, and finally outputs the class with the higher probability.

Output:



  属于'ham'的概率: 0.5000

  属于'spam'的概率: 0.5000

----------------------------------------

邮件内容: "明天上午十点电话会议讨论预算"

  预测类别: ham

  属于'ham'的概率: 0.5000

  属于'spam'的概率: 0.5000


V. Advantages, Disadvantages, and Considerations

Advantages

Disadvantages and Considerations


VI. Exercises and Challenges

To reinforce your understanding of Naive Bayes, try the following exercises:

  1. Modification Exercise: In the code above, try adding more training data, especially emails containing words such as "link," "meeting," and "report," and observe how the prediction results and probabilities change.
  2. Parameter tuning: Consult the sklearn documentation to learn about the MultinomialNB The alpha parameter (smoothing parameter). Try setting it to 0.1, 0.5, 1.0, and see what effect it has on the prediction probabilities.
  3. Change the Classifier: Replace MultinomialNB() with BernoulliNB()(Bernoulli Naive Bayes) in the code, and note that CountVectorizer may need to be set to binary=True to generate binary features. Compare the performance of the two on a simple example.
  4. Practical Challenge: When using sklearn built-in fetch_20newsgroups dataset (a classic news text classification dataset), and try using Naive Bayes to classify news on different topics.

As an excellent starting point for entry-level machine learning, Naive Bayes demonstrates the charm of probability theory with concise mathematical formulas, and firmly occupies a place in text classification, recommendation systems, sentiment analysis, and other fields thanks to its practicality. Understand it, and you will hold the first key to unlocking the black box of many intelligent applications.