白手起家学习数据科学 ——Naive Bayes之“测试模型篇”(十)

这有一个好的数据集 [ SpamAssassin public corpus ]。

我们使用前缀为20021010的文件(在Windows中你可能需要像7-Zip的软件用于解压它们)。

在抽取数据之后(例如,放到C:\spam中),你得到3个文件夹:spameasy_hamhard_ham,每个文件夹包含许多邮件,每个邮件包含在单独的文件中,为了让事情变得变得简单些,我们只考虑每个邮件的标题行。

那么,我们怎样识别标题行?浏览所有的文件,它们似乎所有都是以”Subject:”开始,所以我们会寻找这个:

import glob, re

# modify the path with wherever you've put the files
path = r"C:\spam\*\*"

data = []

# glob.glob returns every filename that matches the wildcarded path
for fn in glob.glob(path):
    is_spam = "ham" not in fn

    with open(fn,'r') as file:
        for line in file:
            if line.startswith("Subject:"):
                # remove the leading "Subject: " and keep what's left
                subject = re.sub(r"^Subject: ", "", line).strip()
                data.append((subject, is_spam))

现在我们能把数据分成训练集和测试集,然后我们准备建立分类器:

random.seed(0) # just so you get the same answers as me
train_data, test_data = split_data(data, 0.75)

classifier = NaiveBayesClassifier()
classifier.train(train_data)

然后我们能检测模型的性能:

# triplets (subject, actual is_spam, predicted spam probability)
classified = [(subject, is_spam, classifier.classify(subject))
            for subject, is_spam in test_data]

# assume that spam_probability > 0.5 corresponds to spam prediction
# and count the combinations of (actual is_spam, predicted is_spam)
counts = Counter((is_spam, spam_probability > 0.5)
                for _, is_spam, spam_probability in classified)

预测结果有101个 true positives(实际是spam,预测也为spam),33个 false positives(实际是nonspam,预测为spam),704 true negatives(实际是nonspam,预测为nonspam),38 false negatives(实际是spam,预测为nonspam)。这个意味着我们的精度(precision)是 101/(101+33)=75 ,我们的召回度(recall)是 101/(101+38)=73 ,对于这样一个简单的模型不算一个坏的数字。

同时也对大多数误检感兴趣:

# sort by spam_probability from smallest to largest
classified.sort(key=lambda row: row[2])

# the highest predicted spam probabilities among the non-spams
spammiest_hams = filter(lambda row: not row[1], classified)[-5:]

# the lowest predicted spam probabilities among the actual spams
hammiest_spams = filter(lambda row: row[1], classified)[:5]

有2个spammiest hams同时有单词”needed”(77 times likely to appear in spam),”insurance”(30 times more likely to appear in spam),以及”important”(10 times more likely to appear in spam)。

hammiest spam 是太短了而不能做出判断,第二个 hammiest 是一个信用卡询价,它的大多数单词没有出现在训练集中。

我们能看spammiest单词:

def p_spam_given_word(word_prob):
    """uses bayes's theorem to compute p(spam | message contains word)"""

    # word_prob is one of the triplets produced by word_probabilities
    word, prob_if_spam, prob_if_not_spam = word_prob
    return prob_if_spam / (prob_if_spam + prob_if_not_spam)
words = sorted(classifier.word_probs, key=p_spam_given_word)

spammiest_words = words[-5:]
hammiest_words = words[:5]

spammiest单词是”money”、”systemworks”、”rates”、”sale”以及”year”,它们似乎涉及尝试让人们买东西。hammiest单词是”spambayes”、”users”、”razor”、”zzzteana”以及”sadev”,它们似乎涉及阻止垃圾邮件,足够的奇特。

我们怎样得到更好的性能?很显然的一个办法是得到更多的数据到训练模型上,也有许多方法改善模型,下面是一些可能的方法,你可以尝试一下:

  • 训练消息内容,而不只是题目行;
  • 我们的分类器考虑每个出现在训练集中的单词,甚至只出现一次。修改分类器,接受一个可选的min_count的阈值,忽略出现次数小于阈值的单词;
  • 分词器没有相似单词的概念(例如:”cheap”和”cheapest”)。修改分类器,添加一个可选的stemmer函数,把单词转换到等价层面上。例如,一个简单的stemmer函数可以是:
def drop_final_s(word):
    return re.sub("s$", "", word)

创建一个好的stemmer函数是难的,人们频繁的使用Porter Stemmer算法。
* 虽然我们的特征全部都是形如”包含单词 wi 的消息”,没有理由为什么就一定是这个样子的,在我们执行中,我们能添加额外的特征例如”包含一个数字的消息”。

下一章节中我们将介绍线性回归。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值