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).
- A: The event that an email is "spam."
- B: The feature that an email contains the word "free."
- P(A): The prior probabilitythat any given email is spam (for example, based on historical data, 20 out of 100 emails are spam, so P(spam) = 0.2).
- P(B|A): The conditional probabilitythat the word "free" appears given that the email is spam (for example, 80% of spam emails contain "free", so P(free|spam) = 0.8).
- P(B): The total probability that the word "free" appears in any given email.。
- P(A|B): What we ultimately want to find, given that the email contains the word "free" , is the posterior probability。
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
,
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
(
f
'Email content: "{email}"'
)
(
f
" Predicted class: {pred}"
)
Dynamically output the probability of each class (more robust)
for
cls
,
prob
in
zip
(
class_names
,
proba
)
:
(
f
" Probability of belonging to '{cls}': {prob:.4f}"
)
(
"-"
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:
CountVectorizer(): This is a Text feature extractor. It converts each email (a piece of text) into a numeric vector. Each position in the vector represents a word (such as "free" or "meeting"), and the value represents the number of times that word appears in the email.MultinomialNB(): This is our Multinomial Naive Bayes classifier. It takes the numeric vectors produced in the previous step and learns the probabilistic relationship between these vectors and the labels (spam/ham).make_pipeline()automatically chains these two steps together, transforming first and then classifying during training, and the same during prediction.
Model training:model.fit(texts, labels) is the core training process. The algorithm computes here:
- prior probability
P(ham)andP(spam)。 - the conditional probability of each word
hamandspamunder theP(单词 | ham)andP(单词 | spam)。
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
- Simple and Efficient: The principle is simple, training and prediction are very fast, and it is suitable for large-scale datasets.
- Good performance on small-scale data: Even with not much training data, it can achieve good results.
- Suitable for high-dimensional data: Particularly good at handling data with very high feature dimensions (number of words), such as text.
- Relatively robust to irrelevant features: Due to the "naive" independence assumption, individual irrelevant features have little impact on the overall result.
Disadvantages and Considerations
- Limitations of the "Naive" Assumption: In reality, features are often correlated, and this strong assumption may affect accuracy. For example, in text, "New York" and "Times" often appear together and are not independent.
- Accuracy of Probability Estimates: The calculated "probability" values are more for ranking classifications; their absolute values may not be entirely accurate.
- The Zero-Probability Problem: If a feature never appears in a certain class in the training set, its conditional probability is 0, causing the entire posterior probability to be 0. A common solution is Laplace smoothing(in
sklearnthroughalphaparameter), which adds a small constant to the counts of all features to avoid zero values.
VI. Exercises and Challenges
To reinforce your understanding of Naive Bayes, try the following exercises:
- 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.
- Parameter tuning: Consult the
sklearndocumentation to learn about theMultinomialNBThealphaparameter (smoothing parameter). Try setting it to 0.1, 0.5, 1.0, and see what effect it has on the prediction probabilities. - Change the Classifier: Replace
MultinomialNB()withBernoulliNB()(Bernoulli Naive Bayes) in the code, and note thatCountVectorizermay need to be set tobinary=Trueto generate binary features. Compare the performance of the two on a simple example. - Practical Challenge: When using
sklearnbuilt-infetch_20newsgroupsdataset (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.