模型:采用朴素贝叶斯、逻辑回归和多层感知机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(