博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
白手起家学习数据科学 ——Naive Bayes之“测试模型篇”(十)
阅读量:4057 次
发布时间:2019-05-25

本文共 3212 字,大约阅读时间需要 10 分钟。

这有一个好的数据集

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

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

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

import glob, re# modify the path with wherever you've put the filespath = r"C:\spam\*\*"data = []# glob.glob returns every filename that matches the wildcarded pathfor 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 metrain_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 largestclassified.sort(key=lambda row: row[2])# the highest predicted spam probabilities among the non-spamsspammiest_hams = filter(lambda row: not row[1], classified)[-5:]# the lowest predicted spam probabilities among the actual spamshammiest_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 的消息”,没有理由为什么就一定是这个样子的,在我们执行中,我们能添加额外的特征例如”包含一个数字的消息”。

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

转载地址:http://wimci.baihongyu.com/

你可能感兴趣的文章
Encoding Schemes
查看>>
移植QT
查看>>
如此调用
查看>>
计算机的发展史
查看>>
带WiringPi库的交叉编译如何处理一
查看>>
带WiringPi库的交叉笔译如何处理二之软链接概念
查看>>
Spring事务的七种传播行为
查看>>
ES写入找不到主节点问题排查
查看>>
Java8 HashMap集合解析
查看>>
欢迎使用CSDN-markdown编辑器
查看>>
Android计算器实现源码分析
查看>>
Android系统构架
查看>>
Android 跨应用程序访问窗口知识点总结
查看>>
各种排序算法的分析及java实现
查看>>
SSH框架总结(框架分析+环境搭建+实例源码下载)
查看>>
自定义 select 下拉框 多选插件
查看>>
js获取url链接携带的参数值
查看>>
gdb 调试core dump
查看>>
gdb debug tips
查看>>
linux和windows内存布局验证
查看>>