朴素贝叶斯分类

标签: 朴素贝叶斯

一、概念

  1. 朴素贝叶斯
    朴素:条件独立性假设,指特征之间的相互独立性假设,即一个特征出现的可能性与其他特征没有关系。比如说,假设单词bacon出现在unhealthy后面和delisious后面的概率相同。
  2. 使用条件概率进行分类:选择具有最高概率的决策
    贝叶斯准则:这里写图片描述
    这里写图片描述

二、使用朴素贝叶斯进行文档分类

  1. 准备数据:将句子转换成向量,统计所有文档中出现的单词形成列表
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]
    return postingList, classVec

#创建在所有文档中出现的不重复词的列表
def createVocabList(dataSet):
    #创建空集合
    vocabSet = set([])
    for document in dataSet:
        #两个集合的并集,加入新词
        vocabSet = vocabSet | set(document)
    return list(vocabSet)

#判断单词在文档中是否出现
def setOfWords2Vec(vocabList,inputSet):
    returnVec = [0]*len(inputSet)
    for word in inputSet:
        if word in vocabList:
            returnVec[inputSet.index(word)] = 1
        else:
            print "the word: %s is not in my vocabulary" % word
    return returnVec

listOPosts,listClasses = loadDataSet()
myVocabList = createVocabList(listOPosts)
print myVocabList
print setOfWords2Vec(myVocabList,listOPosts[0])
print setOfWords2Vec(myVocabList,listOPosts[3])

结果:
这里写图片描述

  1. 从词向量计算概率
    伪代码:
    这里写图片描述

训练函数:

def trainNB0(trainMatrix,trainCategory):
    numTrainDocs = len(trainMatrix)#训练文档的个数
    numWords = len(trainMatrix[0])#词汇表长度
    #文档为 class = 1 的概率
    pAbusive = sum(trainCategory)/float(numTrainDocs)
    p0Num = zeros(numWords)
    p1Num = zeros(numWords)
    p0Denom = 0.0
    p1Denom = 0.0
    for i in range(numTrainDocs):
        if trainCategory[i] == 1:#类别为侮辱性言论
            #该向量元素的值为词汇表中的每个词条在侮辱性言论(c=1)类别里出现的次数
            p1Num += trainMatrix[i]
            #侮辱性言论类别词条出现的总数
            p1Denom += sum(trainMatrix[i])
        else:#类别为正常言论
            p0Num += trainMatrix[i]
            p0Denom += sum(trainMatrix[i])
    p1Vect = p1Num/p1Denom
    p0Vect = p0Num/p0Denom
    return p0Vect, p1Vect, pAbusive


listOPosts,listClasses = loadDataSet()
myVocabList = createVocabList(listOPosts)
trainMat = []
for postinDoc in listOPosts:
    #将每个文档中的评论转换为文本向量
    trainMat.append(setOfWords2Vec(myVocabList,postinDoc))

p0V, plV, pAb = trainNB0(trainMat, listClasses)
print p0V
print plV
print pAb

结果:
这里写图片描述

分类函数:

#分类函数
def classfyNB(vec2Classify,p0Vec,p1Vec,pClass1):
    p1 = sum(vec2Classify * p1Vec) + log(pClass1)
    p0 = sum(vec2Classify * p0Vec) + 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(trainMat, listClasses)
    testEntry = ['love','my','dalmation']
    thisDoc = array(setOfWords2Vec(myVocabList,testEntry))
    print testEntry,'classified as:',classfyNB(thisDoc,p0V,p1V,pAb)
    testEntry = ['stupid','garbage']
    thisDoc = array(setOfWords2Vec(myVocabList,testEntry))
    print testEntry, 'classified as:', classfyNB(thisDoc, p0V, p1V, pAb)

结果:
这里写图片描述

版权声明:本文为enjoyyulinli123原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/enjoyyulinli123/article/details/79450642