因此,我的任务是在Python中为电子邮件数据集创建分类算法:https://archive.ics.uci.edu/ml/datasets/spambase
我需要能够处理数据集,应用我的分类算法(我选择了3个朴素的贝叶斯版本),在终端上打印准确度得分,并执行5或10倍交叉验证,并找出多少电子邮件垃圾邮件。
正如您所看到的,我已经完成了一些任务,但是却缺少交叉验证,并且发现了多少封垃圾邮件。
import numpy as np
import pandas as pd
import sklearn
from sklearn.naive_bayes import BernoulliNB
from sklearn.naive_bayes import GaussianNB
from sklearn.naive_bayes import MultinomialNB
from sklearn.model_selection import train_test_split
from sklearn import metrics
from sklearn.metrics import accuracy_score
# Read data
dataset = pd.read_csv('dataset.csv').values
# What shuffle does? How it helps?
np.random.shuffle(dataset)
X = dataset[ : , :48 ]
Y = dataset[ : , -1 ]
X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size = .33, random_state = 17)
# Bernoulli Naive Bayes
BernNB = BernoulliNB(binarize = True)
BernNB.fit(X_train, Y_train)
y_expect = Y_test
y_pred = BernNB.predict(X_test)
print ("Bernoulli Accuracy Score: ")
print (accuracy_score(y_expect, y_pred))
# Multinomial Naive Bayes
MultiNB = MultinomialNB()
MultiNB.fit(X_train, Y_train)
y_pred = MultiNB.predict(X_test)
print ("Multinomial Accuracy Score: ")
print (accuracy_score(y_expect, y_pred))
# Gaussian Naive Bayes
GausNB = GaussianNB()
GausNB.fit(X_train, Y_train)
y_pred = GausNB.predict(X_test)
print ("Gaussian Accuracy Score: ")
print (accuracy_score(y_expect, y_pred))
# Bernoulli ALTERED Naive Bayes
BernNB = BernoulliNB(binarize = 0.1)
BernNB.fit(X_train, Y_train)
y_expect = Y_test
y_pred = BernNB.predict(X_test)
print ("Bernoulli 'Altered' Accuracy Score: ")
print (accuracy_score(y_expect, y_pred))
我研究了交叉验证,并认为我现在可以应用此验证,但是它发现了我不理解的垃圾邮件数量???我的海军贝叶斯版本的准确性有所不同,但实际上如何找到垃圾邮件的数量?最后一列是1或0,它定义是否为垃圾邮件?所以我不知道该怎么办
答案 0 :(得分:2)
由于类别标签1表示垃圾邮件,因此您使用accuracy_score
计算的准确性值将为您提供被正确识别为垃圾邮件的垃圾邮件数量。例如,90%的测试准确性意味着100个测试垃圾邮件中有90个被正确分类为垃圾邮件。
使用sklearn.metrics.confusion_matrix(y_expect, y_pred)
进行单个班级细分。
例如:
如果y_expect = [1,1,0,0,1]
这意味着您的测试数据中有3封垃圾邮件和2封非垃圾邮件,如果为y_pred = [1,1,1,0,1]
,则表明您的模型已正确检测到3封垃圾邮件,但也检测到1封非垃圾邮件作为垃圾邮件。