对于事件A和B,贝叶斯定理的表达式可写成P(A|B) = P(A)P(B|A) / P(B)
P(A) :先验概率
P(A|B) :后验概率
P(B|A) :似然度
P(B) :标准化常量
朴素贝叶斯机器学习实战:
#encoding:utf-8
from numpy import *
#下载数据
#贝努力模型~多项式模型
#贝努力~~不考虑词出现的次数~~只考虑出不出现
def loadDataSet():
postingList=[['my', 'dog', 'has', 'flea', 'problems', 'help', 'please'],
['maybe', 'not', 'take', 'him', 'to', 'dog', 'park', 'stupid'],
['my', 'dalmation', 'is', 'so', 'cute', 'I', 'love', 'him'],
['stop', 'posting', 'stupid', 'worthless', 'garbage'],
['mr', 'licks', 'ate', 'my', 'steak', 'how', 'to', 'stop', 'him'],
['quit', 'buying', 'worthless', 'dog', 'food', 'stupid']]
classVec = [0,1,0,1,0,1] #1代表侮辱性文字~0表示正常言论
return postingList,classVec
#不重复词列表
def createVocabList(dataSet):
vocabSet = set([]) #创建一个空集~~set类型数据~返回的是不重复词的列表
for document in dataSet:
vocabSet = vocabSet | set(document) #创建两个集合的并集
return list(vocabSet)
#输入:文档,不重复词列表 输出:文档向量~~向量每一元素为1或0~~分别表示单词在文档中是否出现
#即:将单词转换为数字
def setOfWords2Vec(vocabList, inputSet):
returnVec = [0]*len(vocabList) #创建一个所含元素都为0的向量
for word in inputSet:
if word in vocabList:
returnVec[vocabList.index(word)] = 1
else: print "the word: %s is not in my Vocabulary!" % word
return returnVec
#输入:文档矩阵、类别向量 输出:正常词概率、侮辱性词概率、属于侮辱性文档概率
def trainNB0(trainMatrix,trainCategory):
#计算class=1的概率p(1)~因为是二分类~因此class=0的概率为p(0)=1-p(1)
numTrainDocs = len(trainMatrix)
numWords = len(trainMatrix[0])
pAbusive = sum(trainCategory)/float(numTrainDocs)
p0Num = ones(numWords); p1Num = ones(numWords) #change to ones()
p0Denom = 2.0; p1Denom = 2.0 #change to 2.0~初始化概率~~值均为0是作用于二分类,值均为2可以直接应用于多类别分类
for i in range(numTrainDocs):
if trainCategory[i] == 1:#出现侮辱性文字
p1Num += trainMatrix[i]#该侮辱性词个数+1
p1Denom += sum(trainMatrix[i]) #文档侮辱性总词数+1
else:
p0Num += trainMatrix[i]#正常词数
p0Denom += sum(trainMatrix[i])
p1Vect = log(p1Num/p1Denom) #change to log()
p0Vect = log(p0Num/p0Denom) #change to log()#对每个元素作除法
return p0Vect,p1Vect,pAbusive
#贝叶斯分类函数
#输入:要分类的向量vec2Classify,以及trainNB0得到的3个概率 输出:得到类别
def classifyNB(vec2Classify, p0Vec, p1Vec, pClass1):
p1 = sum(vec2Classify * p1Vec) + log(pClass1) #element-wise mult~元素相乘
p0 = sum(vec2Classify * p0Vec) + log(1.0 - pClass1)#元素相乘
if p1 > p0:
return 1
else:
return 0
#输入:文档、词列表 输出:文档向量~~向量的值表示单词在文档中出现的次数
#即:将单词转换为数字
def bagOfWords2VecMN(vocabList, inputSet):
returnVec = [0]*len(vocabList)
for word in inputSet:
if word in vocabList:
returnVec[vocabList.index(word)] += 1
return returnVec
#贝叶斯测试~~应用:过滤网站恶意留言
def testingNB():
listOPosts,listClasses = loadDataSet()#下载数据和类别
myVocabList = createVocabList(listOPosts)#建立不重复词列表
trainMat=[]#训练数据
for postinDoc in listOPosts:
trainMat.append(setOfWords2Vec(myVocabList, postinDoc))#词转换成向量
p0V,p1V,pAb = trainNB0(array(trainMat),array(listClasses))#正常词概率、侮辱性词概率、属于侮辱性文档概率
testEntry = ['love', 'my', 'dalmation']#测试数据
thisDoc = array(setOfWords2Vec(myVocabList, testEntry))#测试数据转向量
print testEntry,'classified as: ',classifyNB(thisDoc,p0V,p1V,pAb)#测试结果
testEntry = ['stupid', 'garbage']
thisDoc = array(setOfWords2Vec(myVocabList, testEntry))
print testEntry,'classified as: ',classifyNB(thisDoc,p0V,p1V,pAb)
#文件解析。email
#输入:比较大的字符串数据 输出:单词列表
def textParse(bigString): #input is big string, #output is word list
import re
listOfTokens = re.split(r'\W*', bigString)#正则匹配、字符串分割
return [tok.lower() for tok in listOfTokens if len(tok) > 2] #1.将所有字符串转为小写,2.找出字符串长度大于2的
#垃圾邮件测试~得到分类错误率 email
def spamTest():
docList=[]; classList = []; fullText =[]
#导入并解析文本文件
for i in range(1,26):
wordList = textParse(open('email/spam/%d.txt' % i).read())
docList.append(wordList)
fullText.extend(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=[] #create test set
for i in range(10):#随机选取10个为测试集
randIndex = int(random.uniform(0,len(trainingSet)))
testSet.append(trainingSet[randIndex])
del(trainingSet[randIndex])
trainMat=[]; trainClasses = []
for docIndex in trainingSet:#train the classifier (get probs) trainNB0
trainMat.append(bagOfWords2VecMN(vocabList, docList[docIndex]))
trainClasses.append(classList[docIndex])
p0V,p1V,pSpam = trainNB0(array(trainMat),array(trainClasses))
errorCount = 0
#对测试集分类
for docIndex in testSet: #classify the remaining items
wordVector = bagOfWords2VecMN(vocabList, docList[docIndex])
if classifyNB(array(wordVector),p0V,p1V,pSpam) != classList[docIndex]:
errorCount += 1
print "classification error",docList[docIndex]
print 'the error rate is: ',float(errorCount)/len(testSet)#分类错误的占比
测试代码:
#贝叶斯测试~~应用:过滤网站恶意留言
bayes.testingNB()
#垃圾邮件测试~得到分类错误率 email
bayes.spamTest()
bayes.spamTest()#输出错误率~以及哪些文档出错