学习朴素贝叶斯算法,把https://blog.csdn.net/qq_38688564/article/details/79521544
的第一个代码敲了一下,并在里面做了详细的注释笔记。
import numpy
#构建文本集合
def loadDataSet():
postingList = [['my', 'dog', 'has', 'flea', 'problem', 'help', 'please'],
['maybe', 'not', 'take', 'him', 'to', 'dog', 'park', 'stupid'],
['my', 'dalmation', 'is', 'so', 'cute', 'I', 'love', 'him'],
['stop', 'posting', 'ate', 'my', 'steak', 'how', 'to', 'stop', 'him'],
['mr', 'licks', 'ate', 'my', 'steak', 'how', 'to', 'stop', 'him'],
['quit', 'buying', 'worthless', 'dog', 'food', 'stupid']]
classVec = [0, 1, 0, 1, 0, 1]
return postingList,classVec
#统计词汇,创建词典
def createVocabList(dataSet):
vocabSet = set([])
for document in dataSet:
vocabSet = vocabSet | set(document)
return list(vocabSet)
#创建判断词是否出现向量,出现1,否0
# def setOfWord2vec(vocabList,inputSet):#词典,输入的文档集合
# returnVec = []
# for artical in inputSet:
# tmp = [0]*len(vocabList)
# for word in artical:
# if word in vocabList:
# tmp[vocabList.index[word]] = 1
# else:
# print("the word :%s is not in my vocabulary"%word)
# returnVec.append(tmp)
# return returnVec
#创建词模型,统计词出现次数
def bagOfWord2Vec(vocabList,inputSet):
returnVec = []
for article in inputSet:
tmp = [0]*len(vocabList)
for word in article:
if word in vocabList:
tmp[vocabList.index(word)] += 1
else:
print("the word :%s is not in my vocabulary"%word)
returnVec.append(tmp)
return returnVec
#训练朴素贝叶斯模型 p(c|w) = (p(c)*p(w|c))/p(w)
def trainNB(trainMatrix,trainCategory):#(所有训练文档构成的数组,训练标签)
#总共文档的个数
numTrainDoc = len(trainMatrix)
#单词数量
numWord = len(trainMatrix[0])#假设每个文档一样长
#侮辱性文档所占概率=侮辱性文档个数/总文档个数
pAbuse = sum(trainCategory)/numTrainDoc
p0Num = numpy.ones(numWord)#.ones()元素值都设置为1
p1Num = numpy.ones(numWord)
# 零概率问题:在计算事件的概率时,如果某个事件在观察样本库(训练集)中没有出现过,会导致该事件的概率结果是0。这是不合理的,不能因为一个事件没有观察到,就被认为该事件一定不可能发生(即该事件的概率为0)。
# 拉普拉斯平滑(Laplacian
# smoothing) 是为了解决零概率的问题。
# 理论假设:假定训练样本很大时,每个分量x的计数加1造成的估计概率变化可以忽略不计,但可以方便有效的避免零概率问题
#总结:分子加一,分母加K,K代表类别数目
p0Denom = 2.0#分母
p1Denom = 2.0
for i in range(numTrainDoc):
if trainCategory[i] == 1:
p1Num += trainMatrix[i]
p1Denom += sum(trainMatrix[i])
else:
p0Num += trainMatrix[i]
p0Denom += sum(trainMatrix[i])
#所有词条在侮辱性文档出现的概率p(wi|ci)= (wi在所有侮辱性文档的个数+1)/(侮辱性文档统计的所有单词数+分类个数k)
p1Vec = numpy.log(p1Num/p1Denom)#p(wi|c1)
# 所有词条在正常文档出现的概率
p0Vec = numpy.log(p0Num/p0Denom)#p(wi|c2)
return pAbuse,p1Vec,p0Vec
#分类函数
def classifyNB(vec2classify,p0Vec,p1Vec,pClass1):#(文档词汇出现次数,p(wi|c1),p(wi|c2),p(c1))
#p(c1|d)不等于p(c1|w1)*p(c1|w2)...不符合独立性公式
#p(c1|d)=((p(d|c1)*p(c1))/p(d) 其中p(d)为常数
#p(d|c1)=p(w1|c1)*p(w2|c1)...p(wn|c1)
#p(c1|d)=((p(w1|c1)*p(w2|c1)...p(wn|c1)*p(c1))/p(d)正比于p(w1|c1)*p(w2|c1)...p(wn|c1)*p(c1)
#正比于log(p(w1|c1)*p(w2|c1)...p(wn|c1)*p(c1))= p(w1|c1)+p(w2|c1)...p(wn|c1)+log(p(c1)) 式b
#p(w1|ci)+p(w2|ci)...p(wn|ci)+log(p(ci)) 式a
#求使p(ci|d)最大,即式a最大的类别ci
#p0Vec的p(wi|c1)与式b的p(w1|c1)不同,p0Vec的p(wi|c1)表示词典里的每个词出现概率,
# 式b的p(w1|c1)表示文档里词1出现的概率=词典里的词1出现概率*文档词1出现次数
p1 = numpy.sum(vec2classify*p0Vec)+numpy.log(pClass1)
p2 = numpy.sum(vec2classify*p1Vec)+numpy.log(1-pClass1)
if p1 > p2:
return 1
else:
return 0
#主函数,测试
if __name__ == '__main__':
test=[['mr', 'licks', 'ate', 'my', 'steak', 'how', 'food', 's']]
#test=[['maybe', 'not', 'take', 'him', 'to', 'dog', 'park', 'stupid']]
#获取文档,标签
postingList,classVec = loadDataSet()
# print(postingList)
# #获取词典
vocabList = createVocabList(postingList)
#获取每个训练文档的每个词的个数
returnVec = bagOfWord2Vec(vocabList,postingList)
#获取训练中侮辱性文档比例,侮辱文档概率,正常文档概率
pAbuse,p1Vec,p0Vec = trainNB(returnVec,classVec)
# 获取测试文档的每个词的个数
testVec = bagOfWord2Vec(vocabList,test)
pclass = classifyNB(testVec,p0Vec,p1Vec,pAbuse)
print(pclass)
'''
参考链接
系统学习朴素贝叶斯-三种模型
https://blog.csdn.net/qq_38688564/article/details/79521544
拉普拉斯平滑(Laplacian smoothing)
https://blog.csdn.net/weixin_43868020/article/details/106602799
'''