朴素贝叶斯进行垃圾邮件分类代码
时间: 2023-07-05 11:10:30 浏览: 137
以下是一个简单的朴素贝叶斯垃圾邮件分类的 Python 代码示例:
```python
import os
import numpy as np
from collections import defaultdict
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.naive_bayes import MultinomialNB
# 定义邮件数据路径和类别
data_path = "./data"
categories = ["ham", "spam"]
# 读取数据
data = defaultdict(list)
for category in categories:
folder_path = os.path.join(data_path, category)
for file_name in os.listdir(folder_path):
with open(os.path.join(folder_path, file_name), "r", encoding="utf-8", errors="ignore") as f:
data[category].append(f.read())
# 划分训练集和测试集
train_data = []
train_labels = []
test_data = []
test_labels = []
for category in categories:
data_size = len(data[category])
train_size = int(data_size * 0.8)
train_data += data[category][:train_size]
train_labels += [category] * train_size
test_data += data[category][train_size:]
test_labels += [category] * (data_size - train_size)
# 特征提取
vectorizer = CountVectorizer()
train_features = vectorizer.fit_transform(train_data)
test_features = vectorizer.transform(test_data)
# 训练模型
clf = MultinomialNB()
clf.fit(train_features, train_labels)
# 测试模型
accuracy = clf.score(test_features, test_labels)
print("Accuracy:", accuracy)
```
上述代码使用了 sklearn 中的 `CountVectorizer` 和 `MultinomialNB` 类来进行特征提取和模型训练。首先,读取邮件数据并划分训练集和测试集。然后,使用 `CountVectorizer` 将文本转换为特征向量,再使用 `MultinomialNB` 训练模型。最后,计算模型在测试集上的准确率。
阅读全文