Naive Bayes Spam Classifier
Naive Bayes Spam Classifier
Implement a simple Chinese spam classifier using the most basic conditional probability formula, without using sklearn.
After studying this case, you will understand: Bayes' theorem + "word independence" assumption = a usable text classifier.
Real-life introduction
**Email spam filtering
Your email receives 100 emails every day. How can the program automatically determine if a new email is spam? The program's approach: calculate the probability of words like "free" or "win" appearing in spam emails from historical emails, and the probability of words like "meeting" or "project" appearing in normal emails.
New emails have arrived, let's calculate: the probability of these words appearing simultaneously under the assumption of spam vs. under the assumption of a normal email. The higher probability wins.
Intuitive understanding
The key simplification of Naive Bayes—the "naive assumption": assuming that the appearance of each word is independent of the others. Although this assumption is not true in reality ("free" and "prize" often appear together), its practical effect is surprisingly good.
| Technique | Approach | Problem solved |
|---|---|---|
| Log probability | Convert multiplication to addition using log | Many multiplications of small decimals will become 0 (numerical underflow) |
| Laplace smoothing | Each word count is incremented by +1 instead of +0 | Words not seen in the training set result in a probability of 0 |
Python hands-on practice
Example
from
collections
import
defaultdict
import
math
Training data (8 labeled Chinese SMS messages)
train_data
=
[
(
"Win Free Prizes Click Now"
,
"spam"
)
,
(
"Congratulations on winning a cash discount"
,
"spam"
)
,
(
Limited time offer Click link free
,
spam
)
,
(
Loan low interest apply cash immediately
,
"spam"
)
,
(
"Meeting schedule tomorrow morning discussion"
,
"ham"
)
,
(
"Project Progress Report Meeting Minutes"
,
"ham"
)
,
(
"Weekend dinner arrangement everyone participate"
,
"ham"
)
,
(
"Report Data Analysis Project Completion"
,
"ham"
)
,
]
Count the word frequency for each category
class_word_counts
=
defaultdict
(
lambda
: defaultdict
(
int
)
)
class_doc_counts
=
defaultdict
(
int
)
vocab
=
set
(
)
for
text
,
label
in
train_data:
class_doc_counts
[
label
]
=
1
for
word
in
text.
split
(
)
:
class_word_counts
[
label
]
[
word
]
=
1
vocab.
add
(
word
)
vocab_size
=
len
(
vocab
)
total_docs
=
len
(
train_data
)
Naive Bayes classification (log probability + Laplace smoothing)
def
predict
(
text
,
alpha
=
1.0
)
:
words
=
text.
split
(
)
scores
=
{
}
for
label
in
class_doc_counts:
log_prob
=
math
.
log
(
class_doc_counts
[
label
]
/ total_docs
)
total_words
=
sum
(
class_word_counts
[
label
]
.
values
(
)
)
for
word
in
words:
word_count
=
class_word_counts
[
label
]
[
word
]
word_prob
=
(
word_count + alpha
)
/
(
total_words + alpha * vocab_size
)
log_prob +
=
math
.
log
(
word_prob
)
scores
[
label
]
=
log_prob
return
max
(
scores
,
key
=
scores.
get
)
,
scores
Test
test_emails
=
[
"Free claim cash prizes"
,
"Tomorrow meeting project report"
,
"Limited time click discount link"
,
"Weekend, everyone, let's discuss the report"
,
]
(
"RUNOOB Naive Bayes classification results:\n"
)
for
in
test_emails:
label
,
scores
=
predict
(
)
(
f
"{email!r:28s} -> 【{label}】"
)
Original prompt (Chinese, left untranslated)
RUNOOB Naive Bayes Classification Results:
'免费 领取 现金 奖品' -> 【spam】
'明天 会议 项目 汇报' -> 【ham】
'限时 点击 优惠 链接' -> 【spam】
'周末 大家 一起 讨论 报告' -> 【ham】
Application scenarios in AI
| Scenarios | Description |
|---|---|
| Text classification | Spam filtering, news classification, sentiment analysis—Naive Bayes is a classic baseline |
| Document topic modeling | Mathematical foundation of LDA (Latent Dirichlet Allocation) |
| Anomaly detection | Calculate the probability that a new sample belongs to the "normal distribution"; if it is too low, it is judged as an anomaly |