码迷,mamicode.com
首页 > 其他好文 > 详细

【数据挖掘】分类之Naïve Bayes(转载)

时间:2017-08-09 17:27:38      阅读:219      评论:0      收藏:0      [点我收藏+]

标签:replace   spel   logs   edit   com   htm   讲解   检查   另一个   

【数据挖掘】分类之Na?ve Bayes

1.算法简介

朴素贝叶斯(Naive Bayes)是监督学习的一种常用算法,易于实现,没有迭代,并有坚实的数学理论(即贝叶斯定理)作为支撑。

 

本文以拼写检查作为例子,讲解Naive Bayes分类器是如何实现的。对于用户输入的一个单词(words),拼写检查试图推断出最有可能的那个正确单词(correct)。当然,输入的单词有可能本身就是正确的。比如,输入的单词thew,用户有可能是想输入the,也有可能是想输入thaw。为了解决这个问题,Naive Bayes分类器采用了后验概率P(c|w)来解决这个问题。P(c|w)表示在发生了w的情况下推断出c的概率。为了找出最有可能c,应找出有最大值的P(c|w),即求解问题

argmaxc P(c|w)

 

根据贝叶斯定理,

P(c|w)=P(w|c) P(c) / P(w)

 

对于任意的c,P(w)均相等,问题等价与

argmaxc P(w|c) P(c)

 

P(w|c)表示的是用户输入w而是想输入c的概率。为了得到P(c),我们可以从文本库中统计c出现的频率。但是,P(w|c)似乎计算起来不那么容易。Norvig [1]中给出了一个简化计算办法:

(1)如果w拼写正确并且出现在文本库中,返回w;

(2)如果(1)没发生,计算与w的编辑距离为1的所有候选c,选出文本库中出现频率最高者;

(3)如果(1)(2)均没发生,计算与w的编辑距离为2的所有候选c,选出文本库中出现频率最高者;

(4)如果(1)(2)(3)均没发生,返回w。

一个单词通过删除、交换、更改、插入四个操作中一种,变换成另一个单词,这两个单词之间的编辑距离为1。

import re, collections  
  
def words(text): return re.findall([a-z]+, text.lower())   
  
def train(features):  
    model=collections.defaultdict(lambda: 1)  
    for f in features:  
        model[f] += 1  
    return model  
  
NWORDS = train(words(file(big.txt).read()))  
  
alphabet = abcdefghijklmnopqrstuvwxyz  
  
def edits1(word):  
    splits=[(word[:i], word[i:]) for i in range(len(word) + 1)]  
    deletes=[a + b[1:] for a, b in splits if b]  
    transposes=[a + b[1] + b[0] + b[2:] for a, b in splits if len(b)>1]  
    replaces=[a + c + b[1:] for a, b in splits for c in alphabet if b]  
    inserts=[a + c + b  for a, b in splits for c in alphabet]  
    return set(deletes + transposes + replaces + inserts)  
  
def known_edits2(word):  
    return set(e2 for e1 in edits1(word) for e2 in edits1(e1) if e2 in NWORDS)  
  
def known(words): return set(w for w in words if w in NWORDS)  
  
def correct(word):  
    candidates = known([word]) or known(edits1(word)) or known_edits2(word) or [word]  
    return max(candidates, key=NWORDS.get)  

2.Referrence

[1] Peter Norvig, How to Write a Spelling Corrector.

[2] 阮一峰, 贝叶斯推断及其互联网应用(三):拼写检查.

【数据挖掘】分类之Naïve Bayes(转载)

标签:replace   spel   logs   edit   com   htm   讲解   检查   另一个   

原文地址:http://www.cnblogs.com/Vae1990Silence/p/7326422.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!