编程语言
首页 > 编程语言> > 朴树贝叶斯分类算法

朴树贝叶斯分类算法

作者:互联网

对于本例中,朴素贝叶斯公式:p(A|w)=p(w|A).p(A)/p(w),其中w为待测试文本,由每一个单词wi构成,w=w0,w1,w2,...,wn,所以,要想知道测试本次是否属于侮辱性,则求

侮辱性概率:p(1|w)=p(w0,w1,w2,...,wn|1).p(1)/p(w0,w1,w2,...,wn)

非侮辱性概率:p(0|w)=p(w0,w1,w2,...,wn|0).p(0)/p(w0,w1,w2,...,wn)

因为假设w中各单词相互独立,又可以将上式写成

p(1|w)=p(w0|1)p(w1|1)...p(wn|1).p(1)/p(w0,w1,w2,...,wn),再对分子取对数p'(1|w)=∑logp(wi|1)+logp(1)

因为p(1|w)和p(0|w)分母相同,且只需要比较p(1|w)和p(0|w)大小,故求分子的值即可。

代码如下:

# -*- coding: UTF-8 -*-
import numpy as np

#创建实验样本
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 setOfWords2Vec(vocabList, inputSet):
    returnVec = [0]*len(vocabList)
    for word in inputSet:
        returnVec[vocabList.index(word)] = 1
        '''
        这个地方觉得可以优化下,如果一个词出现多次,也只给它统计一次 +=1??
        returnVec[vocabList.index(word)] += 1,createVocabList()中也得修改
        ['love', 'my', 'dalmation', 'stupid', 'stupid']
        按照此式得出是侮辱性,按照上式是非侮辱
        '''
    return  returnVec

#生成词汇集
def createVocabList(dataSet):
    vocabSet = set([])
    for document in dataSet:
        vocabSet = vocabSet|set(document)
    return list(vocabSet)

#朴素贝叶斯分类器训练函数,求条件概率
def trainNB0(trainMatrix,trainCategory):
    numTrainDocs = len(trainMatrix)
    numWords = len(trainMatrix[0])
    pAbusive = sum(trainCategory)/float(numTrainDocs)
    p0Num = np.ones(numWords)#防止词汇表中的单词没出现,概率则为0,分子变成0了,统一变成1
    p1Num = np.ones(numWords)
    p1Denom = 2.0 #分母也由0.0变成2.0
    p0Denom = 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])
    p1Vect = np.log(p1Num/p1Denom)#对每个条件概率p(wi|1)求对数
    p0Vect = np.log(p0Num/p0Denom)
    return p0Vect,p1Vect,pAbusive

'''说明:
p(1|w0,w1,w2,...,wn)=[p(w0|1).p(w1|1).p(w2|1).....p(wn|1)]*p(1)/p(w0,w1,w2,...,wn)
p(0|w0,w1,w2,...,wn)=[p(w0|0).p(w1|0).p(w2|0).....p(wn|0)]*p(0)/p(w0,w1,w2,...,wn)
因为分母p(w0,w1,w2,...,wn)相等,故只求分子做比较
w0,w1,w2,...,wn相互独立
'''
def classifyNB(vec2Classify,p0Vec,p1Vec,pClass1):
    p1 = sum(vec2Classify * p1Vec) + np.log(pClass1) #分子项,按照公式应该是相乘的,取对数后,则变为相加了
    p0 = sum(vec2Classify * p0Vec) + np.log(1 - pClass1)
    if p1 > p0:
        return 1
    else:
        return 0

def testingNB():
    listOPosts,listClasses = loadDataSet()
    myVocabList = createVocabList(listOPosts)
    trainMat = []
    for postinDoc in listOPosts:
        trainMat.append(setOfWords2Vec(myVocabList,postinDoc))
    p0V,p1V,pAb = trainNB0(np.array(trainMat),np.array(listClasses))
    testEntry = ['love','my','dalmation']
    thisDoc = np.array(setOfWords2Vec(myVocabList,testEntry))
    if classifyNB(thisDoc,p0V,p1V,pAb):
        print(testEntry,'属于侮辱类')
    else:
        print(testEntry,'属于非侮辱类')
    testEntry = ['love','stupid','garbage']
    thisDoc = np.array(setOfWords2Vec(myVocabList,testEntry))
    if classifyNB(thisDoc,p0V,p1V,pAb):
        print(testEntry,'属于侮辱类')
    else:
        print(testEntry,'属于非侮辱类')

if __name__ == '__main__':
    testingNB()

测试结果如下:

['love', 'my', 'dalmation'] 属于非侮辱类
['love', 'stupid', 'garbage'] 属于侮辱类

进程已结束,退出代码 0

参考《机器学习实战》和博客https://blog.csdn.net/c406495762/article/category/7029976

标签:...,wn,贝叶斯,算法,w2,w1,w0,np,朴树
来源: https://www.cnblogs.com/xuxiaowen1990/p/11170413.html