您的位置:首页 > 大数据 > 人工智能

机器学习实战(三)——NaiveBayes朴素贝叶斯算法邮件分类

2016-03-22 22:46 501 查看
朴素贝叶斯分类的原理是条件概率的计算:

在已知先验概率的条件下,计算后验概率,后验概率即是在当前数据条件下属于分类1或者分类2 的概率,取概率较大的一个为输出。

贝叶斯准则很熟悉了,不解释了,但在这个算法中引入了一个很重要的思想:将文本等数据对象转化为向量格式进行计算。

其中包含了:1、正则表达式的运用,python中re库的运用

2、留存交叉验证:将样本一部分用作训练,一部分用作测试,当将训练组和测试组随机进行划分时,多次进行测试取平均值可以对算法的性能进行很好的评估。

# -*- coding: utf-8 -*-
############
#classifyNB
#classify the posts into two classes

from numpy import *
import os
import math
import operator
#最重要的思想;将词汇转变为向量;首先将所有出现的词汇纳入一个集合中,创建与集合相对应的一个向量
#系数相等的元素分别表示该词汇和该词汇出现的次数
def createVocabList(docList):
vocabList= set([])
for doc in docList:
vocabList=vocabList|set(doc)
return vocabList

#词袋模型:首先将训练样本中所有出现的词生成一个集合(词汇表),对输入的文本中包含在词汇表中
#的元素统计其出现的次数,生成一个长度为词汇表长度的向量,该向量方便计算各个词汇出现的概率
#与词袋模型对应的是词集模型,生成的词向量只有0和1,表征该词汇在文本中是否出现过
def bagsOfWords2Vec(vocabList,inputSet):
vecVocab=zeros(len(vocabList))
for word in inputSet:
if word in vocabList:
vecVocab[list(vocabList).index(word)]+=1
else:
print 'the word %s is not in the vocablist' %word

return vecVocab

#####trainNB()计算导入的训练矩阵中,各个先验概率的大小;注意为了防止下溢出,用log,
#此时将所有词汇出现的次数初始化为1,将p1,p0情况下的词汇总个数初始化为2,防止log中出现
#0或者分母为0 的情况
def trainNB(trainMat,classList):
numWordP0=ones(len(trainMat[0]))
numWordP1=ones(len(trainMat[0]))
wordP0=0.0;wordP1=0.0
numWord=sum(trainMat,0)
numP1=2.0
numP0=2.0
P1=sum(classList)/float(len(trainMat))
#P0=1-P1
for i in xrange(len(trainMat)):
if classList[i]==1:
#numWordP1+=trainMat[i]
numWordP1=numWordP1+trainMat[i]
numP1=numP1+sum(trainMat[i])
else:
#numWordP0+=trainMat[i]
numWordP0=numWordP0+trainMat[i]
numP0=numP0+sum(trainMat[i])
wordP0=log(numWordP0/numP0)
wordP1=log(numWordP1/numP1)
return wordP0,wordP1,P1

def classifyNB(wordVector,p0,p1,pSpam):
p0=sum(wordVector*p0)+log(1.0-pSpam)
p1=sum(wordVector*p1)+log(pSpam)

if p0>p1:
return 0
else:return 1
#################
#文本处理:1.正则表达式,在文末给出正则表达式学习的链接;2.大小写转换str.lower
def textParse(bigString):
import re
listOfToken=re.split(r'\W*',bigString)
return [tok.lower() for tok in listOfToken if len(tok)>2]

###交叉验证,用样本自身的一部分进行训练。另一部分进行测试
def spamTest():
docList=[];classList=[];fullText=[]
for i in xrange(1,26):
wordList=textParse(open('/home/lvsolo/python/naiveBayes/spam/%d.txt'%i).read())
docList.append(wordList)
fullText.extend(wordList)
classList.append(1)
wordList=textParse(open('/home/lvsolo/python/naiveBayes/ham/%d.txt'%i).read())
docList.append(wordList)
fullText.extend(wordList)
classList.append(0)
###建立总的词汇表
vocabList=createVocabList(docList)

###将samples重新随机分为training组和test组进行交叉验证
trainingSet=range(50);testSet=[]

for i in xrange(10):
testInx=int(random.uniform(0,len(trainingSet)))
testSet.append(trainingSet[testInx])
del(trainingSet[testInx])

trainMat=[];trainClasses=[]
for docInx in trainingSet:
trainMat.append(bagsOfWords2Vec(vocabList,docList[docInx]))
trainClasses.append(classList[docInx])
p0,p1,pAbusive=trainNB(array(trainMat),array(trainClasses))
pError=0.0
for docInx in testSet:
wordVector= bagsOfWords2Vec(vocabList,docList[docInx])
if classifyNB(wordVector,p0,p1,pAbusive)!=classList[docInx]:
pError+=1
#print 'the error rate is %s'%(float(pError)/len(testSet))
return float(pError)/len(testSet)


python正则表达式:

http://www.cnblogs.com/huxi/archive/2010/07/04/1771073.html

DEEPLEARNING资源软件:

http://www.sigvc.org/bbs/thread-557-1-1.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: