我正在尝试构建一个垃圾邮件分类器,我从互联网上收集了多个数据集(例如SpamAssassin数据库中的垃圾邮件/火腿邮件)并构建了这个:
import os
import numpy
from pandas import DataFrame
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.pipeline import Pipeline
from sklearn.cross_validation import KFold
from sklearn.metrics import confusion_matrix, f1_score
from sklearn import svm
NEWLINE = '\n'
HAM = 'ham'
SPAM = 'spam'
SOURCES = [
('C:/data/spam', SPAM),
('C:/data/easy_ham', HAM),
# ('C:/data/hard_ham', HAM), Commented out, since they take too long
# ('C:/data/beck-s', HAM),
# ('C:/data/farmer-d', HAM),
# ('C:/data/kaminski-v', HAM),
# ('C:/data/kitchen-l', HAM),
# ('C:/data/lokay-m', HAM),
# ('C:/data/williams-w3', HAM),
# ('C:/data/BG', SPAM),
# ('C:/data/GP', SPAM),
# ('C:/data/SH', SPAM)
]
SKIP_FILES = {'cmds'}
def read_files(path):
for root, dir_names, file_names in os.walk(path):
for path in dir_names:
read_files(os.path.join(root, path))
for file_name in file_names:
if file_name not in SKIP_FILES:
file_path = os.path.join(root, file_name)
if os.path.isfile(file_path):
past_header, lines = False, []
f = open(file_path, encoding="latin-1")
for line in f:
if past_header:
lines.append(line)
elif line == NEWLINE:
past_header = True
f.close()
content = NEWLINE.join(lines)
yield file_path, content
def build_data_frame(path, classification):
rows = []
index = []
for file_name, text in read_files(path):
rows.append({'text': text, 'class': classification})
index.append(file_name)
data_frame = DataFrame(rows, index=index)
return data_frame
data = DataFrame({'text': [], 'class': []})
for path, classification in SOURCES:
data = data.append(build_data_frame(path, classification))
data = data.reindex(numpy.random.permutation(data.index))
pipeline = Pipeline([
('count_vectorizer', CountVectorizer(ngram_range=(1, 2))),
('classifier', svm.SVC(gamma=0.001, C=100))
])
k_fold = KFold(n=len(data), n_folds=6)
scores = []
confusion = numpy.array([[0, 0], [0, 0]])
for train_indices, test_indices in k_fold:
train_text = data.iloc[train_indices]['text'].values
train_y = data.iloc[train_indices]['class'].values.astype(str)
test_text = data.iloc[test_indices]['text'].values
test_y = data.iloc[test_indices]['class'].values.astype(str)
pipeline.fit(train_text, train_y)
predictions = pipeline.predict(test_text)
confusion += confusion_matrix(test_y, predictions)
score = f1_score(test_y, predictions, pos_label=SPAM)
scores.append(score)
print('Total emails classified:', len(data))
print('Support Vector Machine Output : ')
print('Score:' + str((sum(scores) / len(scores))*100) + '%')
print('Confusion matrix:')
print(confusion)
我注释掉的行是邮件的集合,即使我注释掉大多数数据集并选择邮件数量最少的数据集,它仍然运行得非常慢(约15分钟)并且给出准确性大约91%。如何提高速度和准确度?
答案 0 :(得分:2)
您正在使用内核SVM。这有两个问题。
内核SVM的运行时复杂度:执行内核SVM的第一步是构建一个相似度矩阵,它成为特征集。使用30,000个文档,相似度矩阵中的元素数量变为90,000,000。随着语料库的增长,这种情况会迅速增长,因为矩阵会增加语料库中文档数量的平方。在scikit-learn中使用RBFSampler
可以解决此问题,但您可能不希望使用它,原因如下。
维度:您使用term和bigram计数作为功能集。这是一个极高维度的数据集。在高维空间中使用RBF内核,即使很小的差异(噪声)也会在相似性结果中产生很大的影响。请参阅curse of dimensionality。这可能是你的RBF内核产生比线性内核更差的结果的原因。
随机梯度下降:可以使用SGD代替标准SVM,并且通过良好的参数调整,它可以产生类似甚至更好的结果。缺点是SGD有更多关于学习率和学习率计划的参数。此外,少数通行证SGD并不理想。在这种情况下,像Follow the Regularized Leader(FTRL)这样的其他算法会做得更好。但是Scikit-learn并没有实现FTRL。将SGDClassifier与loss="modified_huber"
一起使用通常效果很好。
现在我们已经解决了问题,有几种方法可以提高性能:
tf-idf权重:使用tf-idf,更常见的字词加权较少。这允许分类器更好地表示更有意义的罕见单词。这可以通过将CountVectorizer
切换为TfidfVectorizer
参数调整:使用线性SVM时,没有gamma
参数,但C
参数可用于极大地改善结果。在SGDClassifier
的情况下,也可以调整alpha和学习速率参数。
集合:在多个子样本上运行模型并对结果求平均值通常会产生比单次运行更强大的模型。这可以使用BaggingClassifier
在scikit-learn中完成。结合不同的方法可以产生明显更好的结果。如果使用截然不同的方法,请考虑使用具有树模型(RandomForestClassifier或GradientBoostingClassifier)的堆叠模型作为最后阶段。