mirror of
https://github.com/apachecn/ailearning.git
synced 2026-05-07 14:13:14 +08:00
修改4.NaiveBayes的 朴素贝叶斯.md 文件和 bayes.py
This commit is contained in:
305
docs/4.朴素贝叶斯.md
305
docs/4.朴素贝叶斯.md
@@ -324,6 +324,8 @@ def testingNB():
|
||||
print testEntry, 'classified as: ', classifyNB(thisDoc, p0V, p1V, pAb)
|
||||
```
|
||||
|
||||
[完整代码地址](https://github.com/apachecn/MachineLearning/blob/master/src/python/4.NaiveBayes/bayes.py): <https://github.com/apachecn/MachineLearning/blob/master/src/python/4.NaiveBayes/bayes.py>
|
||||
|
||||
### 项目案例2: 使用朴素贝叶斯过滤垃圾邮件
|
||||
|
||||
#### 项目概述
|
||||
@@ -433,65 +435,284 @@ def trainNB0(trainMatrix, trainCategory):
|
||||
|
||||
> 测试算法: 使用朴素贝叶斯进行交叉验证
|
||||
|
||||
```python
|
||||
文件解析及完整的垃圾邮件测试函数
|
||||
|
||||
```python
|
||||
def textParse(bigString):
|
||||
import re
|
||||
listOfTokens = re.split(r'\W*', bigString)
|
||||
return [tok.lower() for tok in listOfTokens if len(tok) > 2]
|
||||
|
||||
def spamTest():
|
||||
docList = []
|
||||
classList = []
|
||||
fullText = []
|
||||
for i in range(1, 26):
|
||||
wordList = textParse(open('email/spam/%d.txt' % i).read())
|
||||
docList.append(wordList)
|
||||
classList.append(1)
|
||||
wordList = textParse(open('email/ham/%d.txt' % i).read())
|
||||
docList.append(wordList)
|
||||
fullText.extend(wordList)
|
||||
classList.append(0)
|
||||
vocabList = createVocabList(docList)
|
||||
trainingSet = range(50)
|
||||
testSet = []
|
||||
for i in range(10):
|
||||
randIndex = int(random.uniform(0, len(trainingSet)))
|
||||
testSet.append(trainingSet[randIndex])
|
||||
del(trainingSet[randIndex])
|
||||
trainMat = []
|
||||
trainClasses = []
|
||||
for docIndex in trainingSet:
|
||||
trainMat.append(setOfWords2Vec(vocabList, docList[docIndex]))
|
||||
trainClasses.append(classList[docIndex])
|
||||
p0V, p1V, pSpam = trainNB0(array(trainMat), array(trainClasses))
|
||||
errorCount = 0
|
||||
for docIndex in testSet:
|
||||
wordVector = setOfWords2Vec(vocabList, docList[docIndex])
|
||||
if classifyNB(array(wordVector), p0V, p1V, pSpam) != classList[docIndex]:
|
||||
errorCount += 1
|
||||
print 'thr error rate is :', float(errorCount)/len(testSet)
|
||||
```
|
||||
|
||||
> 使用算法: 构建一个完整的程序对一组文档进行分类,将错分的文档输出到屏幕上
|
||||
|
||||
[完整代码地址](https://github.com/apachecn/MachineLearning/blob/master/src/python/4.NaiveBayes/bayes.py): <https://github.com/apachecn/MachineLearning/blob/master/src/python/4.NaiveBayes/bayes.py>
|
||||
|
||||
|
||||
### 项目案例3: 使用朴素贝叶斯分类器从个人广告中获取区域倾向
|
||||
|
||||
#### 项目概述
|
||||
|
||||
广告商往往想知道关于一个人的一些特定人口统计信息,以便能更好地定向推销广告。
|
||||
|
||||
## 解析RSS源数据
|
||||
我们将分别从美国的两个城市中选取一些人,通过分析这些人发布的信息,来比较这两个城市的人们在广告用词上是否不同。如果结论确实不同,那么他们各自常用的词是那些,从人们的用词当中,我们能否对不同城市的人所关心的内容有所了解。
|
||||
|
||||
机器学习的一个重要应用就是文档的自动分类。在文档分类中,整个文档(如一封电子邮件)是实例,而电子邮件中的某些元素则构成特征。
|
||||
虽然电子邮件是一种会不断增加的文本,但我们同样也可以对新闻报道、用户留言、政府公文等其他任何类型的文本进行分类。
|
||||
我们可以观察文档中出现的词,并把每个词的出现或者不出现作为一个特征,这样得到的特征数目就会跟词汇表中的词目一样多。
|
||||
朴素贝叶斯是上节介绍的贝叶斯分类器的一个扩展,是用于文档分类的常用算法。
|
||||
|
||||
## 使用朴素贝叶斯来分析不同地区的态度
|
||||
|
||||
> 示例:使用朴素贝叶斯来发现低于相关的用词
|
||||
#### 开发流程
|
||||
|
||||
```
|
||||
(1) 收集数据:从RSS源收集内容,这里需要对RSS源构建一个接口。
|
||||
(2) 准备数据:将文本文件解析成词条向量。
|
||||
(3) 分析数据:检查词条确保解析的正确性。
|
||||
(4) 训练算法:使用我们之前建立的 trainNB0()函数。
|
||||
(5) 测试算法:观察错误率,确保分类器可用。可以修改切分程序,以降低错误率,提高分类结果。
|
||||
(6) 使用算法:构建一个完整的程序,封装所有内容。给定两个RSS源,该程序会显示最常用的公共词。
|
||||
收集数据: 从 RSS 源收集内容,这里需要对 RSS 源构建一个接口
|
||||
准备数据: 将文本文件解析成词条向量
|
||||
分析数据: 检查词条确保解析的正确性
|
||||
训练算法: 使用我们之前简历的 trainNB0() 函数
|
||||
测试算法: 观察错误率,确保分类器可用。可以修改切分程序,以降低错误率,提高分类结果
|
||||
使用算法: 构建一个完整的程序,封装所有内容。给定两个 RSS 源,改程序会显示最常用的公共词
|
||||
```
|
||||
|
||||
* 假设: 特征之间强(朴素)独立
|
||||
* 概率模型
|
||||
* P(C|F1F2...Fn) = P(F1F2...Fn|C)P(C) / P(F1F2...Fn)
|
||||
* 由于对于所有类别,P(F1F2...Fn)都是相同的,比较P(C|F1F2...Fn)只用比较P(F1F2...Fn|C)P(C)就好了
|
||||
* 朴素贝叶斯的特点
|
||||
* 优点:在数据较少的情况下仍然有效,可以处理多类别问题
|
||||
* 缺点:对于输入数据的准备方式较为敏感
|
||||
* 适用数据类型:标称型数据
|
||||
* 朴素贝叶斯的一般过程
|
||||
* 收集数据:可以使用任何方法
|
||||
* 准备数据:需要数值型或者布尔型数据
|
||||
* 分析数据:有大量特征时,绘制特征作用不大,此时使用直方图效果更好。
|
||||
* 训练算法:计算不同的独立特征的条件概率
|
||||
* 测试算法:计算错误率
|
||||
* 使用算法:文本分类等
|
||||
* 优化
|
||||
* 为了避免一个概率为0导致P(F1|C)*P(F2|C)....P(Fn|C)整个为0,所以优化为将所有词的出现数都初始化为1,并将分母初始化为2.
|
||||
* 由于大部分因子比较小,乘积之后得到的数不易比较,程序误差较大。所以取对数后可将乘法转化为加法:P(F1|C)*P(F2|C)....P(Fn|C)P(C) -> log(P(F1|C))+log(P(F2|C))+....+log(P(Fn|C))+log(P(C))
|
||||
* 总结
|
||||
* 这一块代码比较乱,最好先把公式理一理再看
|
||||
* 可以参考一下[阮一峰的博客](http://www.ruanyifeng.com/blog/2013/12/naive_bayes_classifier.html)
|
||||
* 对于分类而言,使用概率有时要比使用硬规则更为有效。贝叶斯概率及贝叶斯准则提供了一种利用已知值来估计未知概率的有效方法。
|
||||
* 可以通过特征之间的条件独立性假设,降低对数据量的需求。独立性假设是指一个词的出现概率并不依赖于文档中的其他词。当然我们也知道这个假设过于简单。
|
||||
这就是之所以成为朴素贝叶斯的原因。尽管条件独立性假设并不正确,但是朴素贝叶斯仍然是一种有效的分类器。
|
||||
* 利用现代编程语言来实现朴素贝叶斯时需要考虑很多实际因素。下溢出就是其中一个问题,它可以通过对概率取对数来解决。
|
||||
> 收集数据: 从 RSS 源收集内容,这里需要对 RSS 源构建一个接口
|
||||
|
||||
* * *
|
||||
也就是导入 RSS 源,我们使用 python 下载文本,在http://code.google.com/p/feedparser/ 下浏览相关文档,安装 feedparse,首先解压下载的包,并将当前目录切换到解压文件所在的文件夹,然后在 python 提示符下输入:
|
||||
|
||||
```python
|
||||
>>> python setup.py install
|
||||
```
|
||||
|
||||
> 准备数据: 将文本文件解析成词条向量
|
||||
|
||||
```python
|
||||
#创建一个包含在所有文档中出现的不重复词的列表
|
||||
def createVocabList(dataSet):
|
||||
vocabSet=set([]) #创建一个空集
|
||||
for document in dataSet:
|
||||
vocabSet=vocabSet|set(document) #创建两个集合的并集
|
||||
return list(vocabSet)
|
||||
def setOfWords2VecMN(vocabList,inputSet):
|
||||
returnVec=[0]*len(vocabList) #创建一个其中所含元素都为0的向量
|
||||
for word in inputSet:
|
||||
if word in vocabList:
|
||||
returnVec[vocabList.index(word)]+=1
|
||||
return returnVec
|
||||
|
||||
#文件解析
|
||||
def textParse(bigString):
|
||||
import re
|
||||
listOfTokens=re.split(r'\W*',bigString)
|
||||
return [tok.lower() for tok in listOfTokens if len(tok)>2]
|
||||
```
|
||||
|
||||
> 分析数据: 检查词条确保解析的正确性
|
||||
|
||||
> 训练算法: 使用我们之前简历的 trainNB0() 函数
|
||||
|
||||
```python
|
||||
def trainNB0(trainMatrix, trainCategory):
|
||||
"""
|
||||
训练数据优化版本
|
||||
:param trainMatrix: 文件单词矩阵
|
||||
:param trainCategory: 文件对应的类别
|
||||
:return:
|
||||
"""
|
||||
# 总文件数
|
||||
numTrainDocs = len(trainMatrix)
|
||||
# 总单词数
|
||||
numWords = len(trainMatrix[0])
|
||||
# 侮辱性文件的出现概率
|
||||
pAbusive = sum(trainCategory) / float(numTrainDocs)
|
||||
# 构造单词出现次数列表
|
||||
# p0Num 正常的统计
|
||||
# p1Num 侮辱的统计
|
||||
# 避免单词列表中的任何一个单词为0,而导致最后的乘积为0,所以将每个单词的出现次数初始化为 1
|
||||
p0Num = ones(numWords)#[0,0......]->[1,1,1,1,1.....]
|
||||
p1Num = ones(numWords)
|
||||
|
||||
# 整个数据集单词出现总数,2.0根据样本/实际调查结果调整分母的值(2主要是避免分母为0,当然值可以调整)
|
||||
# p0Denom 正常的统计
|
||||
# p1Denom 侮辱的统计
|
||||
p0Denom = 2.0
|
||||
p1Denom = 2.0
|
||||
for i in range(numTrainDocs):
|
||||
if trainCategory[i] == 1:
|
||||
# 累加辱骂词的频次
|
||||
p1Num += trainMatrix[i]
|
||||
# 对每篇文章的辱骂的频次 进行统计汇总
|
||||
p1Denom += sum(trainMatrix[i])
|
||||
else:
|
||||
p0Num += trainMatrix[i]
|
||||
p0Denom += sum(trainMatrix[i])
|
||||
# 类别1,即侮辱性文档的[log(P(F1|C1)),log(P(F2|C1)),log(P(F3|C1)),log(P(F4|C1)),log(P(F5|C1))....]列表
|
||||
p1Vect = log(p1Num / p1Denom)
|
||||
# 类别0,即正常文档的[log(P(F1|C0)),log(P(F2|C0)),log(P(F3|C0)),log(P(F4|C0)),log(P(F5|C0))....]列表
|
||||
p0Vect = log(p0Num / p0Denom)
|
||||
return p0Vect, p1Vect, pAbusive
|
||||
```
|
||||
|
||||
> 测试算法: 观察错误率,确保分类器可用。可以修改切分程序,以降低错误率,提高分类结果
|
||||
|
||||
```python
|
||||
#RSS源分类器及高频词去除函数
|
||||
def calcMostFreq(vocabList,fullText):
|
||||
import operator
|
||||
freqDict={}
|
||||
for token in vocabList: #遍历词汇表中的每个词
|
||||
freqDict[token]=fullText.count(token) #统计每个词在文本中出现的次数
|
||||
sortedFreq=sorted(freqDict.iteritems(),key=operator.itemgetter(1),reverse=True) #根据每个词出现的次数从高到底对字典进行排序
|
||||
return sortedFreq[:30] #返回出现次数最高的30个单词
|
||||
def localWords(feed1,feed0):
|
||||
import feedparser
|
||||
docList=[];classList=[];fullText=[]
|
||||
minLen=min(len(feed1['entries']),len(feed0['entries']))
|
||||
for i in range(minLen):
|
||||
wordList=textParse(feed1['entries'][i]['summary']) #每次访问一条RSS源
|
||||
docList.append(wordList)
|
||||
fullText.extend(wordList)
|
||||
classList.append(1)
|
||||
wordList=textParse(feed0['entries'][i]['summary'])
|
||||
docList.append(wordList)
|
||||
fullText.extend(wordList)
|
||||
classList.append(0)
|
||||
vocabList=createVocabList(docList)
|
||||
top30Words=calcMostFreq(vocabList,fullText)
|
||||
for pairW in top30Words:
|
||||
if pairW[0] in vocabList:vocabList.remove(pairW[0]) #去掉出现次数最高的那些词
|
||||
trainingSet=range(2*minLen);testSet=[]
|
||||
for i in range(20):
|
||||
randIndex=int(random.uniform(0,len(trainingSet)))
|
||||
testSet.append(trainingSet[randIndex])
|
||||
del(trainingSet[randIndex])
|
||||
trainMat=[];trainClasses=[]
|
||||
for docIndex in trainingSet:
|
||||
trainMat.append(bagOfWords2VecMN(vocabList,docList[docIndex]))
|
||||
trainClasses.append(classList[docIndex])
|
||||
p0V,p1V,pSpam=trainNBO(array(trainMat),array(trainClasses))
|
||||
errorCount=0
|
||||
for docIndex in testSet:
|
||||
wordVector=bagOfWords2VecMN(vocabList,docList[docIndex])
|
||||
if classifyNB(array(wordVector),p0V,p1V,pSpam)!=classList[docIndex]:
|
||||
errorCount+=1
|
||||
print 'the error rate is:',float(errorCount)/len(testSet)
|
||||
return vocabList,p0V,p1V
|
||||
|
||||
#朴素贝叶斯分类函数
|
||||
def classifyNB(vec2Classify,p0Vec,p1Vec,pClass1):
|
||||
p1=sum(vec2Classify*p1Vec)+log(pClass1)
|
||||
p0=sum(vec2Classify*p0Vec)+log(1.0-pClass1)
|
||||
if p1>p0:
|
||||
return 1
|
||||
else:
|
||||
return 0
|
||||
```
|
||||
|
||||
> 使用算法: 构建一个完整的程序,封装所有内容。给定两个 RSS 源,改程序会显示最常用的公共词
|
||||
|
||||
函数 localWords() 使用了两个 RSS 源作为参数,RSS 源要在函数外导入,这样做的原因是 RSS 源会随时间而改变,重新加载 RSS 源就会得到新的数据
|
||||
|
||||
```python
|
||||
>>> reload(bayes)
|
||||
<module 'bayes' from 'bayes.pyc'>
|
||||
>>> import feedparser
|
||||
>>> ny=feedparser.parse('http://newyork.craigslist.org/stp/index.rss')
|
||||
>>> sy=feedparser.parse('http://sfbay.craigslist.org/stp/index.rss')
|
||||
>>> vocabList,pSF,pNY=bayes.localWords(ny,sf)
|
||||
the error rate is: 0.2
|
||||
>>> vocabList,pSF,pNY=bayes.localWords(ny,sf)
|
||||
the error rate is: 0.3
|
||||
>>> vocabList,pSF,pNY=bayes.localWords(ny,sf)
|
||||
the error rate is: 0.55
|
||||
```
|
||||
为了得到错误率的精确估计,应该多次进行上述实验,然后取平均值
|
||||
|
||||
接下来,我们要分析一下数据,显示地域相关的用词
|
||||
|
||||
可以先对向量pSF与pNY进行排序,然后按照顺序打印出来,将下面的代码添加到文件中:
|
||||
|
||||
```python
|
||||
#最具表征性的词汇显示函数
|
||||
def getTopWords(ny,sf):
|
||||
import operator
|
||||
vocabList,p0V,p1V=localWords(ny,sf)
|
||||
topNY=[];topSF=[]
|
||||
for i in range(len(p0V)):
|
||||
if p0V[i]>-6.0:topSF.append((vocabList[i],p0V[i]))
|
||||
if p1V[i]>-6.0:topNY.append((vocabList[i],p1V[i]))
|
||||
sortedSF=sorted(topSF,key=lambda pair:pair[1],reverse=True)
|
||||
print "SF**SF**SF**SF**SF**SF**SF**SF**SF**SF**SF**SF**SF**SF**"
|
||||
for item in sortedSF:
|
||||
print item[0]
|
||||
sortedNY=sorted(topNY,key=lambda pair:pair[1],reverse=True)
|
||||
print "NY**NY**NY**NY**NY**NY**NY**NY**NY**NY**NY**NY**NY**NY**"
|
||||
for item in sortedNY:
|
||||
print item[0]
|
||||
```
|
||||
|
||||
函数 getTopWords() 使用两个 RSS 源作为输入,然后训练并测试朴素贝叶斯分类器,返回使用的概率值。然后创建两个列表用于元组的存储,与之前返回排名最高的 X 个单词不同,这里可以返回大于某个阈值的所有词,这些元组会按照它们的条件概率进行排序。
|
||||
|
||||
保存 bayes.py 文件,在python提示符下输入:
|
||||
|
||||
```python
|
||||
>>> reload(bayes)
|
||||
<module 'bayes' from 'bayes.pyc'>
|
||||
>>> bayes.getTopWords(ny,sf)
|
||||
the error rate is: 0.55
|
||||
SF**SF**SF**SF**SF**SF**SF**SF**SF**SF**SF**SF**SF**SF**
|
||||
how
|
||||
last
|
||||
man
|
||||
...
|
||||
veteran
|
||||
still
|
||||
ends
|
||||
late
|
||||
off
|
||||
own
|
||||
know
|
||||
NY**NY**NY**NY**NY**NY**NY**NY**NY**NY**NY**NY**NY**NY**
|
||||
someone
|
||||
meet
|
||||
...
|
||||
apparel
|
||||
recalled
|
||||
starting
|
||||
strings
|
||||
```
|
||||
|
||||
当注释掉用于移除高频词的三行代码,然后比较注释前后的分类性能,去掉这几行代码之后,错误率为54%,,而保留这些代码得到的错误率为70%。这里观察到,这些留言中出现次数最多的前30个词涵盖了所有用词的30%,vocabList的大小约为3000个词,也就是说,词汇表中的一小部分单词却占据了所有文本用词的一大部分。产生这种现象的原因是因为语言中大部分都是冗余和结构辅助性内容。另一个常用的方法是不仅移除高频词,同时从某个预定高频词中移除结构上的辅助词,该词表称为停用词表。
|
||||
|
||||
最后输出的单词,可以看出程序输出了大量的停用词,可以移除固定的停用词看看结果如何,这样做的花,分类错误率也会降低。
|
||||
|
||||
[完整代码地址](https://github.com/apachecn/MachineLearning/blob/master/src/python/4.NaiveBayes/bayes.py): <https://github.com/apachecn/MachineLearning/blob/master/src/python/4.NaiveBayes/bayes.py>
|
||||
|
||||
***
|
||||
|
||||
* **作者:[羊三](http://www.apache.wiki/display/~xuxin) [小瑶](http://www.apache.wiki/display/~chenyao)**
|
||||
* [GitHub地址](https://github.com/apachecn/MachineLearning): <https://github.com/apachecn/MachineLearning>
|
||||
|
||||
@@ -11,7 +11,7 @@ from numpy import *
|
||||
p(xy)=p(x|y)p(y)=p(y|x)p(x)
|
||||
p(x|y)=p(y|x)p(x)/p(y)
|
||||
"""
|
||||
|
||||
# 项目案例1: 屏蔽社区留言板的侮辱性言论
|
||||
|
||||
def loadDataSet():
|
||||
"""
|
||||
@@ -21,7 +21,7 @@ def loadDataSet():
|
||||
postingList = [['my', 'dog', 'has', 'flea', 'problems', 'help', 'please'], #[0,0,1,1,1......]
|
||||
['maybe', 'not', 'take', 'him', 'to', 'dog', 'park', 'stupid'],
|
||||
['my', 'dalmation', 'is', 'so', 'cute', 'I', 'love', 'him'],
|
||||
['stop', 'posting', 'stupid', 'worthless', 'garbage'],
|
||||
['stop', 'posting', 'stupid', 'worthless', 'gar e'],
|
||||
['mr', 'licks', 'ate', 'my', 'steak', 'how', 'to', 'stop', 'him'],
|
||||
['quit', 'buying', 'worthless', 'dog', 'food', 'stupid']]
|
||||
classVec = [0, 1, 0, 1, 0, 1] # 1 is abusive, 0 not
|
||||
@@ -154,7 +154,7 @@ def classifyNB(vec2Classify, p0Vec, p1Vec, pClass1):
|
||||
# 计算公式 log(P(F1|C))+log(P(F2|C))+....+log(P(Fn|C))+log(P(C))
|
||||
# 使用 NumPy 数组来计算两个向量相乘的结果,这里的相乘是指对应元素相乘,即先将两个向量中的第一个元素相乘,然后将第2个元素相乘,以此类推。
|
||||
# 我的理解是:这里的 vec2Classify * p1Vec 的意思就是将每个词与其对应的概率相关联起来
|
||||
# 可以理解为 1.单词在词汇表中的条件下,文件是good 类别的概率 也可以理解为 2.在整个空间下,文件既在词汇表中又是good类别的概率
|
||||
# 可以理解为 1.单词在词汇表中的条件下,文件是good 类别的概率 也可以理解为 2.在整个空间下,文件既在词汇表中又是good类别的概率
|
||||
p1 = sum(vec2Classify * p1Vec) + log(pClass1)
|
||||
p0 = sum(vec2Classify * p0Vec) + log(1.0 - pClass1)
|
||||
if p1 > p0:
|
||||
@@ -195,5 +195,137 @@ def testingNB():
|
||||
print testEntry, 'classified as: ', classifyNB(thisDoc, p0V, p1V, pAb)
|
||||
|
||||
|
||||
# ------------------------------------------------------------------------------------------
|
||||
# 项目案例2: 使用朴素贝叶斯过滤垃圾邮件
|
||||
|
||||
# 切分文本
|
||||
def textParse(bigString):
|
||||
import re
|
||||
# 使用正则表达式来切分句子,其中分隔符是除单词、数字外的任意字符串
|
||||
listOfTokens = re.split(r'\W*', bigString)
|
||||
return [tok.lower() for tok in listOfTokens if len(tok) > 2]
|
||||
|
||||
def spamTest():
|
||||
docList = []
|
||||
classList = []
|
||||
fullText = []
|
||||
for i in range(1, 26):
|
||||
wordList = textParse(open('input/4.NaiveBayes/email/spam/%d.txt' % i).read())
|
||||
docList.append(wordList)
|
||||
classList.append(1)
|
||||
wordList = textParse(open('input/4.NaiveBayes/email/ham/%d.txt' % i).read())
|
||||
docList.append(wordList)
|
||||
fullText.extend(wordList)
|
||||
classList.append(0)
|
||||
# 创建词汇表
|
||||
vocabList = createVocabList(docList)
|
||||
trainingSet = range(50)
|
||||
testSet = []
|
||||
# 随机取 10 个邮件用来测试
|
||||
for i in range(10):
|
||||
# random.uniform(x, y) 随机生成一个范围为 x - y 的实数
|
||||
randIndex = int(random.uniform(0, len(trainingSet)))
|
||||
testSet.append(trainingSet[randIndex])
|
||||
del(trainingSet[randIndex])
|
||||
trainMat = []
|
||||
trainClasses = []
|
||||
for docIndex in trainingSet:
|
||||
trainMat.append(setOfWords2Vec(vocabList, docList[docIndex]))
|
||||
trainClasses.append(classList[docIndex])
|
||||
p0V, p1V, pSpam = trainNB0(array(trainMat), array(trainClasses))
|
||||
errorCount = 0
|
||||
for docIndex in testSet:
|
||||
wordVector = setOfWords2Vec(vocabList, docList[docIndex])
|
||||
if classifyNB(array(wordVector), p0V, p1V, pSpam) != classList[docIndex]:
|
||||
errorCount += 1
|
||||
print 'the errorCount is: ', errorCount
|
||||
print 'the testSet length is :', len(testSet)
|
||||
print 'the error rate is :', float(errorCount)/len(testSet)
|
||||
|
||||
|
||||
def testParseTest():
|
||||
print textParse(open('input/4.NaiveBayes/email/ham/1.txt').read())
|
||||
|
||||
# -----------------------------------------------------------------------------------
|
||||
# 项目案例3: 使用朴素贝叶斯从个人广告中获取区域倾向
|
||||
|
||||
# 将文本文件解析成 词条向量
|
||||
def setOfWords2VecMN(vocabList,inputSet):
|
||||
returnVec=[0]*len(vocabList) #创建一个其中所含元素都为0的向量
|
||||
for word in inputSet:
|
||||
if word in vocabList:
|
||||
returnVec[vocabList.index(word)]+=1
|
||||
return returnVec
|
||||
|
||||
|
||||
#文件解析
|
||||
def textParse(bigString):
|
||||
import re
|
||||
listOfTokens=re.split(r'\W*',bigString)
|
||||
return [tok.lower() for tok in listOfTokens if len(tok)>2]
|
||||
|
||||
#RSS源分类器及高频词去除函数
|
||||
def calcMostFreq(vocabList,fullText):
|
||||
import operator
|
||||
freqDict={}
|
||||
for token in vocabList: #遍历词汇表中的每个词
|
||||
freqDict[token]=fullText.count(token) #统计每个词在文本中出现的次数
|
||||
sortedFreq=sorted(freqDict.iteritems(),key=operator.itemgetter(1),reverse=True) #根据每个词出现的次数从高到底对字典进行排序
|
||||
return sortedFreq[:30] #返回出现次数最高的30个单词
|
||||
def localWords(feed1,feed0):
|
||||
import feedparser
|
||||
docList=[];classList=[];fullText=[]
|
||||
minLen=min(len(feed1['entries']),len(feed0['entries']))
|
||||
for i in range(minLen):
|
||||
wordList=textParse(feed1['entries'][i]['summary']) #每次访问一条RSS源
|
||||
docList.append(wordList)
|
||||
fullText.extend(wordList)
|
||||
classList.append(1)
|
||||
wordList=textParse(feed0['entries'][i]['summary'])
|
||||
docList.append(wordList)
|
||||
fullText.extend(wordList)
|
||||
classList.append(0)
|
||||
vocabList=createVocabList(docList)
|
||||
top30Words=calcMostFreq(vocabList,fullText)
|
||||
for pairW in top30Words:
|
||||
if pairW[0] in vocabList:vocabList.remove(pairW[0]) #去掉出现次数最高的那些词
|
||||
trainingSet=range(2*minLen);testSet=[]
|
||||
for i in range(20):
|
||||
randIndex=int(random.uniform(0,len(trainingSet)))
|
||||
testSet.append(trainingSet[randIndex])
|
||||
del(trainingSet[randIndex])
|
||||
trainMat=[];trainClasses=[]
|
||||
for docIndex in trainingSet:
|
||||
trainMat.append(bagOfWords2VecMN(vocabList,docList[docIndex]))
|
||||
trainClasses.append(classList[docIndex])
|
||||
p0V,p1V,pSpam=trainNBO(array(trainMat),array(trainClasses))
|
||||
errorCount=0
|
||||
for docIndex in testSet:
|
||||
wordVector=bagOfWords2VecMN(vocabList,docList[docIndex])
|
||||
if classifyNB(array(wordVector),p0V,p1V,pSpam)!=classList[docIndex]:
|
||||
errorCount+=1
|
||||
print 'the error rate is:',float(errorCount)/len(testSet)
|
||||
return vocabList,p0V,p1V
|
||||
|
||||
|
||||
# 最具表征性的词汇显示函数
|
||||
def getTopWords(ny,sf):
|
||||
import operator
|
||||
vocabList,p0V,p1V=localWords(ny,sf)
|
||||
topNY=[];topSF=[]
|
||||
for i in range(len(p0V)):
|
||||
if p0V[i]>-6.0:topSF.append((vocabList[i],p0V[i]))
|
||||
if p1V[i]>-6.0:topNY.append((vocabList[i],p1V[i]))
|
||||
sortedSF=sorted(topSF,key=lambda pair:pair[1],reverse=True)
|
||||
print "SF**SF**SF**SF**SF**SF**SF**SF**SF**SF**SF**SF**SF**SF**"
|
||||
for item in sortedSF:
|
||||
print item[0]
|
||||
sortedNY=sorted(topNY,key=lambda pair:pair[1],reverse=True)
|
||||
print "NY**NY**NY**NY**NY**NY**NY**NY**NY**NY**NY**NY**NY**NY**"
|
||||
for item in sortedNY:
|
||||
print item[0]
|
||||
|
||||
if __name__ == "__main__":
|
||||
testingNB()
|
||||
# testingNB()
|
||||
spamTest()
|
||||
# laTest()
|
||||
|
||||
Reference in New Issue
Block a user