利用Scikit Learn库进行垃圾邮件过滤

模型:采用朴素贝叶斯、逻辑回归和多层感知机3个模型。

输出:画出混淆矩阵,计算准确率、精准率、召回率。

精度:至少一个模型的准确率>0.96

使用朴素贝叶斯模型

代码如下:

import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.naive_bayes import MultinomialNB
from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score, classification_report
# 二元分类指标
from sklearn.metrics import confusion_matrix
import matplotlib.pyplot as plt

# 通过read_table给分割成两份的信息设置标签
df = pd.read_table('./SMSSpamCollection', sep='\t', names=['label', 'sms_message'])

# 需要首先将label标签都转换成数字,0表示有用邮件,1表示垃圾邮件
df['label'] = df.label.map({
   
   'ham':0, 'spam':1})
# 将数据划分成训练集和测试集,其中因为test_size=0.2时,精确率达到了0.99,所以我便设置了test_size=0.2
X_train, X_test, y_train, y_test = train_test_split(df['sms_message'],
                                                    df['label'],
                                                    test_size=0.2,
                                                    random_state=1)
# 统计一下邮件总数、训练集大小、测试集大小
print('Number of rows in the total set: {}'.format(df.shape[0]))
print('Number of rows in the training set: {}'.format(X_train.shape[0]))
print('Number of rows in the test set: {}'.format(X_test.shape[0]))

# 对数据进行特征向量的提取,这里使用的是CountVectorizer,一种相对简单的提取方法
count_vector = CountVectorizer()
# 拟合训练数据,然后返回矩阵
training_data = count_vector.fit_transform(X_train)
# 转换测试数据并返回矩阵
testing_data = count_vector.transform(X_test)

# 通过朴素贝叶斯对训练集进行拟合,以及预测
naive_bayes = MultinomialNB()
naive_bayes.fit(training_data, y_train)
predictions = naive_bayes.predict(testing_data)

# 输出该模型的准确率、精准率、召回率、F1值
print('Accuracy score: ', format(accuracy_score(y_test, predictions)))
print('Precision score: ', format(precision_score(y_test, predictions)))
print(
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

花无凋零之时

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值