- 垃圾邮件样本和正常邮件样本各25份,20份用作训练,剩下的用来测试
- 使用sklearn包的CountVectorizer类来统计词频
- 使用联合概率来计算
贝叶斯公式 P(A|B)=P(B|A)*P(A)/P(B)
在多条件下 P(S|W1 W2) = P(W1 W2|S)P(S) / (P(W1 W2|S)P(S) + P(W1 W2|~S)P(~S))
W1,W2独立:P(W1 W2) = P(W1)P(W2), P(W1 W2|S) = P(W1|S)P(W2|S)
因此上式 = P(W1|S)P(W2|S)P(S) / (P(W1|S)P(W2|S)P(S) + P(W1|~S)P(W2|~S)P(~S))
应用Bayesian 原理,将 P(Wi|S) 用 P(S|Wi) 表示:
上式 = (P(S|W1)P(S|W2)P(S) * P(W1)P(W2) / P(S)^2) / ((P(S|W1)P(S|W2)P(S) * P(W1)P(W2) / P(S)^2) + (P(~S|W1)P(~S|W2)P(~S) * P(W1)P(W2) / P(~S)^2))
在 P(S) = P(~S) = 50% 的条件下:
上式 = P(S|W1)P(S|W2) / (P(S|W1)P(S|W2) + P(~S|W1)P(~S|W2))
= P1P2 / (P1P2 + (1-P1)(1-P2));
在这步推导中,我们可以直接用 P(W1|S)P(W2|S)P(S) / (P(W1|S)P(W2|S)P(S) + P(W1|~S)P(W2|~S)P(~S)) 这个式子来写程序,推导只是为了把他转化为联合概率的形式,而这个公式是多条件下的概率公式,结论是更一般的,当出现概率为0.5的时候他们等价。
- 利用正则表达式分词,去除标点和多余空格
- 统计词频,作为训练集,生成一个关键字字典
- 用同样的方法对测试集进行处理
- 计算每个词的条件概率,然后再带入联合概率公式计算
- 设置一个阈值,判断和分类
朴素贝叶斯模型是一个很简单的模型,但是程序中还是有一个关键的数据处理点。 在很多的参考资料中,有这样一种写法:
如果某个词只出现在垃圾邮件中,Paul Graham就假定,它在正常邮件的出现频率是1%,反之亦然。这样做是为了避免概率为0。
刚开始,我认为在这两种情况下的值是经验值,虽然推荐是0.01,但是可以根据实际情况进行调整。然而事实上这是一种平滑的处理措施,叫拉普拉斯平滑,是为了避免概率为0而存在的
基本公式为: (分子+1)/(分母+n)
这个平滑好像很博大精深,但我太懒了,所以就记了个公式QAQ