ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

【机器学习实战】朴素贝叶斯

2021-11-28 17:02:01  阅读:161  来源: 互联网

标签:实战 0.04166667 概率 贝叶斯 文档 trainMatrix 朴素 mathrm


在这里插入图片描述

文章目录

基于贝叶斯决策理论的分类方法

朴素贝叶斯

  • 优点: 在数据较少的情况下仍然有效, 可以处理多类别问题。
  • 缺点: 对于输入数据的准备方式较为敏感。

适用数据类型: 标称型数据。

使用条件概率来分类

条件概率

如果对条件概率不理解,可以查看我的知乎文章

条件概率

贝叶斯决策理论要求计算两个概率 p 1 ( x , y ) \mathrm{p} 1(\mathrm{x}, \mathrm{y}) p1(x,y) 和 p 2 ( x , y ) \mathrm{p} 2(\mathrm{x}, \mathrm{y}) p2(x,y) :

  • 如果 p 1 ( x , y ) > p 2 ( x , y ) p 1(x, y)>p 2(x, y) p1(x,y)>p2(x,y), 那么属于类别 1 ;
  • 如果 p 2 ( x , y ) > p 1 ( x , y ) \mathrm{p} 2(\mathrm{x}, \mathrm{y})>\mathrm{p} 1(\mathrm{x}, \mathrm{y}) p2(x,y)>p1(x,y), 那么属于类别 2 。

但这两个准则并不是贝叶斯决策理论的所有内容。使用p1()和p2()只是为了尽可能简化 描述, 而真正需要计算和比较的是 p ( c 1 ∣ x , y ) p\left(c_{1} \mid x , y\right) p(c1​∣x,y) 和 p ( c 2 ∣ x , y ) p\left(c_{2} \mid x , y\right) p(c2​∣x,y) 。这些符号所代表的具体意义是:
给定某个由 x 、 y \mathrm{x} 、 \mathrm{y} x、y 表示的数据点, 那么该数据点来自类别 C 2 \mathrm{C}_{2} C2​ 的概率是多少? 数据点来自类别 C 2 \mathrm{C}_{2} C2​ 的概 率又是多少? 注意这些概率与刚才给出的概率 p ( x , y ∣ c 2 ) p\left(x, y \mid c_{2}\right) p(x,y∣c2​) 并不一样(这个的含义为,给定条件为 c 1 c_1 c1​,在参数为 c 1 c_1 c1​的条件下,实验结果为x,y的概率), 不过可以使用贝叶斯准则 来交换概率中条件与结果。具体地, 应用贝叶斯准则得到:
p ( c i ∣ x , y ) = p ( x , y ∣ c i ) p ( c i ) p ( x , y ) p\left(c_{i} \mid x, y\right)=\frac{p\left(x, y \mid c_{i}\right) p\left(c_{i}\right)}{p(x, y)} p(ci​∣x,y)=p(x,y)p(x,y∣ci​)p(ci​)​

使用这些定义, 可以定义贝叶斯分类准则为:

  • 如果 P ( C 1 ∣ x , y ) > P ( C 2 ∣ x , y ) P\left(C_{1} \mid x, y\right)>P\left(C_{2} \mid x, y\right) P(C1​∣x,y)>P(C2​∣x,y), 那么属于类别 C 1 C_{1} C1​ 。
  • 如果 P ( C 1 ∣ x , y ) < P ( C 2 ∣ x , y ) P\left(C_{1} \mid x, y\right)<P\left(C_{2} \mid x, y\right) P(C1​∣x,y)<P(C2​∣x,y), 那么属于类别 C 2 C_{2} C2​ 。

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

朴素贝叶斯的一般过程

  1. 收集数据: 可以使用任何方法。本章使用RSS源。
  2. 准备数据: 需要数值型或者布尔型数据。
  3. 分析数据: 有大量特征时, 绘制特征作用不大, 此时使用直方图效果更好。
  4. 训练算法: 计算不同的独立特征的条件概率。
  5. 测试算法: 计算错误率。
  6. 使用算法: 一个常见的朴素贝叶斯应用是文档分类。可以在任意的分类场景中使用朴 素贝叶斯分类器, 不一定非要是文本。

使用 Python 进行文本分类

#词表到向量的转换函数
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([])
    for document in dataSet:
        vocabSet = vocabSet | set(document) #创建两个集合的并集
    return list(vocabSet)
def setOfWord2Vec(vocabList, inputSet):
    returnVec = [0]*len(vocabList)
    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
listOposts,listClasses = loadDataSet()
myVocabList = createVocabList(listOposts)
myVocabList
['dog',
 'to',
 'ate',
 'love',
 'not',
 'him',
 'my',
 'posting',
 'steak',
 'food',
 'mr',
 'so',
 'how',
 'buying',
 'has',
 'is',
 'park',
 'dalmation',
 'cute',
 'problems',
 'stop',
 'flea',
 'stupid',
 'I',
 'quit',
 'worthless',
 'please',
 'licks',
 'maybe',
 'garbage',
 'help',
 'take']
setOfWord2Vec(myVocabList,listOposts[0])
[1,
 0,
 0,
 0,
 0,
 0,
 1,
 0,
 0,
 0,
 0,
 0,
 0,
 0,
 1,
 0,
 0,
 0,
 0,
 1,
 0,
 1,
 0,
 0,
 0,
 0,
 1,
 0,
 0,
 0,
 1,
 0]
setOfWord2Vec(myVocabList,listOposts[3])
[0,
 0,
 0,
 0,
 0,
 0,
 0,
 1,
 0,
 0,
 0,
 0,
 0,
 0,
 0,
 0,
 0,
 0,
 0,
 0,
 1,
 0,
 1,
 0,
 0,
 1,
 0,
 0,
 0,
 1,
 0,
 0]
from numpy import *
#朴素贝叶斯分类器训练函数
def trainNB0(trainMatrix,trainCategory):
    numTrainDocs = len(trainMatrix)  #计算训练的文档数目
    numWords = len(trainMatrix[0]) #计算每篇文档的词条数
    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:               #统计属于侮辱类的条件概率所需的数据,即P(w0|1),P(w1|1),P(w2|1)···
            p1Num += trainMatrix[i]
            p1Denom += sum(trainMatrix[i])
        else:                                   #统计属于非侮辱类的条件概率所需的数据,即P(w0|0),P(w1|0),P(w2|0)···
            p0Num += trainMatrix[i]
            p0Denom += sum(trainMatrix[i])
    p1Vect = p1Num/p1Denom
    p0Vect = p0Num/p0Denom
    return p0Vect,p1Vect,pAbusive#返回属于侮辱类的条件概率数组,属于非侮辱类的条件概率数组,文档属于侮辱类的概率
trainMat = []
for positinDoc in listOposts:
    trainMat.append(setOfWord2Vec(myVocabList,positinDoc))
p0V,p1V,pAb = trainNB0(trainMat,listClasses)
pAb
0.5
p0V
array([0.04166667, 0.04166667, 0.04166667, 0.04166667, 0.        ,
       0.08333333, 0.125     , 0.        , 0.04166667, 0.        ,
       0.04166667, 0.04166667, 0.04166667, 0.        , 0.04166667,
       0.04166667, 0.        , 0.04166667, 0.04166667, 0.04166667,
       0.04166667, 0.04166667, 0.        , 0.04166667, 0.        ,
       0.        , 0.04166667, 0.04166667, 0.        , 0.        ,
       0.04166667, 0.        ])
p1V
array([0.10526316, 0.05263158, 0.        , 0.        , 0.05263158,
       0.05263158, 0.        , 0.05263158, 0.        , 0.05263158,
       0.        , 0.        , 0.        , 0.05263158, 0.        ,
       0.        , 0.05263158, 0.        , 0.        , 0.        ,
       0.05263158, 0.        , 0.15789474, 0.        , 0.05263158,
       0.10526316, 0.        , 0.        , 0.05263158, 0.05263158,
       0.        , 0.05263158])
#修改更稳定版
#朴素贝叶斯分类器训练函数
def trainNB0(trainMatrix,trainCategory):
    numTrainDocs = len(trainMatrix)  #计算训练的文档数目
    numWords = len(trainMatrix[0]) #计算每篇文档的词条数
    pAbusive = sum(trainCategory)/float(numTrainDocs)#文档属于侮辱类的概率
    p0Num = ones(numWords); p1Num = ones(numWords)
    p0Denom = 2.0; p1Denom = 2.0
    for i in range(numTrainDocs):
        if trainCategory[i] == 1:               #统计属于侮辱类的条件概率所需的数据,即P(w0|1),P(w1|1),P(w2|1)···
            #统计所有类别为1的词条向量中各个词条出现的次数
            p1Num += trainMatrix[i]
            #统计类别为1的词条向量中出现的所有词条的总数
            #即统计类1所有文档中出现单词的数目
            p1Denom += sum(trainMatrix[i])
        else:                                   #统计属于非侮辱类的条件概率所需的数据,即P(w0|0),P(w1|0),P(w2|0)···
            p0Num += trainMatrix[i]
            p0Denom += sum(trainMatrix[i])
    p1Vect = log(p1Num/p1Denom)
    p0Vect = log(p0Num/p0Denom) #类别0所有文档中各个词条出现的频数p(wi|c0)
    return p0Vect,p1Vect,pAbusive#返回属于侮辱类的条件概率数组,属于非侮辱类的条件概率数组,文档属于侮辱类的概率
def classifyNB(vec2Classify,p0Vec,p1Vec,pClass1):
    p1 = sum(vec2Classify * p1Vec) + log(pClass1)
    p0 = sum(vec2Classify * p0Vec) + log(1.0 - pClass1)
    if p1 > p0:
        return 1
    else:
        return 0
def testingNB():
    listOposts,listClasses = loadDataSet()
    myVocabList = createVocabList(listOposts)
    trainMat = []
    for positinDoc in listOposts:
        trainMat.append(setOfWord2Vec(myVocabList,positinDoc))
    p0V,p1V,pAb = trainNB0(array(trainMat),array(listClasses))
    testEntry = ['love','my','dalmation']
    thisDoc = array(setOfWord2Vec(myVocabList,testEntry))
    print(testEntry,"classified as :",classifyNB(thisDoc,p0V,p1V,pAb))
    testEntry = ['stupid','garbage']
    thisDoc = array(setOfWord2Vec(myVocabList,testEntry))
    print(testEntry,"classified as :",classifyNB(thisDoc,p0V,p1V,pAb))
testingNB()
['love', 'my', 'dalmation'] classified as : 0
['stupid', 'garbage'] classified as : 1
#朴素贝叶斯词袋模型
def bagOfWords2VecMN(vocabList,inputSet):
    returnVec = [0]*len(vocabList)
    for word in inputSet:
        if word in vocabList:
            returnVec[vocabList.index(word)] += 1
    return returnVec   

示例:垃圾邮件过滤

数据集下载

蓝奏云地址

示例: 使用朴素贝叶斯对电子邮件进行分类

  1. 收集数据: 提供文本文件。
  2. 准备数据: 将文本文件解析成词条向量。
  3. 分析数据: 检查词条确保解析的正确性。
  4. 训练算法: 使用我们之前建立的trainNB0() 函数。
  5. 测试算法: 使用classifynB(), 并且构建一个新的测试函数来计算文档集的错误率。
  6. 使用算法: 构建一个完整的程序对一组文档进行分类, 将错分的文档输出到屏幕上。
#文件解析及垃圾邮件测试函数
def textParse(bigString):
    import re
    listOfTokens = re.split(r'\W*',bigString)
    return [tok.lower() for tok in listOfTokens if len(tok) > 2]

def spamTest():
    docList = []; classList = []; fullText = []
    for i in range(1,26):
        wordList = textParse(open('email/spam/%d.txt' % i,'rb').read().decode('utf8','ignore'))
        docList.append(wordList)
        fullText.extend(wordList)
        classList.append(1)
        wordList = textParse(open('email/ham/%d.txt' % i,'rb').read().decode('utf8','ignore'))
        docList.append(wordList)
        fullText.extend(wordList)
        classList.append(0)
    #将所有邮件中出现的字符串构建成字符串列表
    vocabList = createVocabList(docList)
    #构建一个大小为50的整数列表和一个空列表
    #留存交叉验证
    trainingSet = list(range(50)); testSet = []
    for i in range(10):
        randIndex = int(random.uniform(0,len(trainingSet)))
        testSet.append(trainingSet[randIndex])
        del(trainingSet[randIndex])
    trainMat = [] ;trainClasses = []
    for docIndex in trainingSet:
        trainMat.append(setOfWord2Vec(vocabList,docList[docIndex]))
        trainClasses.append(classList[docIndex])
    p0V,p1V,pSpam = trainNB0(array(trainMat),array(trainClasses))
    errorCount = 0
    for docIndex in testSet:
        wordVector = setOfWord2Vec(vocabList,docList[docIndex])
        if classifyNB(array(wordVector),p0V,p1V,pSpam) != classList[docIndex]:
            errorCount += 1
    print('the error rate is: ',float(errorCount)/len(testSet))
spamTest()
the error rate is:  0.6

标签:实战,0.04166667,概率,贝叶斯,文档,trainMatrix,朴素,mathrm
来源: https://blog.csdn.net/wl1780852311/article/details/121593954

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有