樸素貝葉斯簡介和實現(xiàn)

1.什么是樸素貝葉斯?
樸素貝葉斯,即先驗概率(條件),判斷事件A,在事件B已經(jīng)發(fā)生的條件下,發(fā)生的概率!


條件概率舉例.png

2.利用樸素貝葉斯進行分類的依據(jù)?
p(c1|x,y)>p(c2|x,y),那么類別就屬于c1;
p(c2|x,y)>p(c1|x,y),那么類別就屬于c2;
3.樸素貝葉斯算法的一般過程

  1. 收集數(shù)據(jù):可以使用任何方法。本章使用RSS源。
  2. 準備數(shù)據(jù):需要數(shù)值型或者布爾型數(shù)據(jù)
  3. 分析數(shù)據(jù):有大量特征時,繪制特征作用不大,此時使用直方圖效果更好。
  4. 訓練算法:計算不同的獨立特征的條件概率。
  5. 測試算法:計算錯誤率。
  6. 使用算法:一個常見的樸素貝葉斯應用是文檔分類。可以在任意的分類場景中使用樸素貝葉斯分類器,不一定非要是文本。

4.算法實現(xiàn)的偽代碼如下:
計算每個類別中的文檔數(shù)目
對每篇訓練文檔:
對每個類別:
如果詞條出現(xiàn)在文檔中→ 增加該詞條的計數(shù)值
增加所有詞條的計數(shù)值
對每個類別:
對每個詞條:
將該詞條的數(shù)目除以總詞條數(shù)目得到條件概率
返回每個類別的條件概率

代碼示例

from numpy import zeros,ones,array
from math  import log
#定義讀取數(shù)據(jù)的函數(shù)
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):
    #創(chuàng)建一個空集
    vocabSet = set([])
    for document in dataSet:
        #創(chuàng)建兩個集合的并集  
        vocabSet = vocabSet | set(document)
    return list(vocabSet)
x,y=loadDataSet() #讀入訓練集合和結(jié)果
wordlist=createVocabList(x)
print("單詞集合如下:\n",createVocabList(x))
#將原始數(shù)據(jù)轉(zhuǎn)換為向量數(shù)據(jù),詞集模型
def setOfWords2Vec(vocabList, inputSet):
    #創(chuàng)建一個其中所含元素都為0的向量 
    returnVec = [0]*len(vocabList) #由文檔中所有單詞構(gòu)建的list
    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
data_x=setOfWords2Vec(wordlist,x[0])
print(data_x)
#詞袋模型
def bagOfWords2VecMN(vocabList, inputSet):
    returnVec = [0]*len(vocabList)
    for word in inputSet:
        if word in vocabList:
            returnVec[vocabList.index(word)] += 1
    return returnVec
    #查看生成的向量

#定義概率函數(shù)
def trainNB0(trainMatrix,trainCategory):#輸入x和y
    numTrainDocs=len(trainMatrix) #返回記錄的行數(shù)
    numWords = len(trainMatrix[0])#返回矩陣的列數(shù)
    pAbusive = sum(trainCategory)/float(numTrainDocs) #返回y=1發(fā)生的概率
    #(以下兩行)初始化概率為0
    p0Num = ones(numWords); p1Num = ones(numWords) 
    p0Denom = 2.0; p1Denom = 2.0
    for i in range(numTrainDocs): #對每一行記錄進行處理
        if trainCategory[i] == 1:#對于y=1的記錄
            #(以下兩行)向量相加 
            p1Num += trainMatrix[i]   #構(gòu)建y=1的單詞集合
            p1Denom += sum(trainMatrix[i]) #統(tǒng)計y=1中單詞的數(shù)目
        else:
            p0Num += trainMatrix[i]
            p0Denom += sum(trainMatrix[i])
   p1Vect =[log(x) for x in p1Num/p1Denom]  #change to log()
    #對每個元素做除法
    p0Vect = [log(x) for x in p0Num/p0Denom]   #change to log()
    return p0Vect,p1Vect,pAbusive
#構(gòu)建訓練樣本
data_x=[]
for postinDoc in x:
    data_x.append(setOfWords2Vec(wordlist, postinDoc))  
#訓練樣本概率
p0V,p1V,pAb=trainNB0(data_x,y)  

#定義測試函數(shù)
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

#定義主要函數(shù)
def testingNB():
    #讀入數(shù)據(jù)
    listOPosts,listClasses = loadDataSet()
    #生成wordlist
    myVocabList = createVocabList(listOPosts)
    #構(gòu)建特征向量
    trainMat=[]
    for postinDoc in listOPosts:
        trainMat.append(setOfWords2Vec(myVocabList, postinDoc))
    #計算條件概率,單詞a在正常郵件出現(xiàn)的概率,在垃圾郵件出現(xiàn)的概率,垃圾郵件出現(xiàn)的概率
    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)) 
``` 
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容