您好,登錄后才能下訂單哦!
機器學習實戰(zhàn)中,樸素貝葉斯那一章節(jié)只實現(xiàn)了二分類,網(wǎng)上大多數(shù)博客也只是照搬書上的源碼,沒有弄懂實現(xiàn)的根本。在此梳理了一遍樸素貝葉斯的原理,實現(xiàn)了5分類的例子,也是自己的一點心得,交流一下。
from numpy import *
'''
貝葉斯公式 p(ci|w) = p(w|ci)*p(ci) / p(w)
即比較兩類別分子大小,把結果歸為分子大的一類
p(w|ci)條件概率,即在類別1或0下,w(詞頻)出現(xiàn)的概率(詞頻/此類別總詞數(shù)即n/N)
'''
# 取得DataSet中不重復的word
def createVocabList(dataSet):
vocabSet = set([])#使用set創(chuàng)建不重復詞表庫
for document in dataSet:
vocabSet = vocabSet | set(document) #創(chuàng)建兩個集合的并集
return list(vocabSet)
'''
我們將每個詞的出現(xiàn)與否作為一個特征,這可以被描述為詞集模型(set-of-words model)。
在詞集中,每個詞只能出現(xiàn)一次。
'''
def setOfWords2Vec(vocabList, inputSet):
returnVec = [0]*len(vocabList)#創(chuàng)建一個所包含元素都為0的向量
#遍歷文檔中的所有單詞,如果出現(xiàn)了詞匯表中的單詞,則將輸出的文檔向量中的對應值設為1
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
'''
如果一個詞在文檔中出現(xiàn)不止一次,這可能意味著包含該詞是否出現(xiàn)在文檔中所不能表達的某種信息,
這種方法被稱為詞袋模型(bag-of-words model)。
在詞袋中,每個單詞可以出現(xiàn)多次。
為適應詞袋模型,需要對函數(shù)setOfWords2Vec稍加修改,修改后的函數(shù)稱為bagOfWords2VecMN
'''
def bagOfWords2Vec(vocabList, inputSet):
returnVec = [0]*len(vocabList)
for word in inputSet:
if word in vocabList:
returnVec[vocabList.index(word)] += 1
return returnVec
def countX(aList,el):
count = 0
for item in aList:
if item == el:
count += 1
return count
def trainNB0(trainMatrix,trainCategory):
'''
trainMatrix:文檔矩陣
trainCategory:每篇文檔類別標簽
'''
numTrainDocs = len(trainMatrix)
numWords = len(trainMatrix[0])
pAbusive0 = countX(trainCategory,0) / float(numTrainDocs)
pAbusive1 = countX(trainCategory,1) / float(numTrainDocs)
pAbusive2 = countX(trainCategory,2) / float(numTrainDocs)
pAbusive3 = countX(trainCategory,3) / float(numTrainDocs)
pAbusive4 = countX(trainCategory,4) / float(numTrainDocs)
#初始化所有詞出現(xiàn)數(shù)為1,并將分母初始化為2,避免某一個概率值為0
p0Num = ones(numWords); p1Num = ones(numWords)
p2Num = ones(numWords)
p3Num = ones(numWords)
p4Num = ones(numWords)
p0Denom = 2.0; p1Denom = 2.0 ;p2Denom = 2.0
p3Denom = 2.0; p4Denom = 2.0
for i in range(numTrainDocs):
# 1類的矩陣相加
if trainCategory[i] == 1:
p1Num += trainMatrix[i]
p1Denom += sum(trainMatrix[i])
if trainCategory[i] == 2:
p2Num += trainMatrix[i]
p2Denom += sum(trainMatrix[i])
if trainCategory[i] == 3:
p3Num += trainMatrix[i]
p3Denom += sum(trainMatrix[i])
if trainCategory[i] == 4:
p4Num += trainMatrix[i]
p4Denom += sum(trainMatrix[i])
if trainCategory[i] == 0:
p0Num += trainMatrix[i]
p0Denom += sum(trainMatrix[i])
#將結果取自然對數(shù),避免下溢出,即太多很小的數(shù)相乘造成的影響
p4Vect = log(p4Num/p4Denom)
p3Vect = log(p3Num/p3Denom)
p2Vect = log(p2Num/p2Denom)
p1Vect = log(p1Num/p1Denom)#change to log()
p0Vect = log(p0Num/p0Denom)#change to log()
return p0Vect,p1Vect,p2Vect,p3Vect,p4Vect,pAbusive0,pAbusive1,pAbusive2,pAbusive3,pAbusive4
def classifyNB(vec2Classify,p0Vec,p1Vec,p2Vec,p3Vec,p4Vec,pClass0,pClass1,pClass2,pClass3,pClass4):
p1 = sum(vec2Classify * p1Vec) + log(pClass1)
p2 = sum(vec2Classify * p2Vec) + log(pClass2)
p3 = sum(vec2Classify * p3Vec) + log(pClass3)
p4 = sum(vec2Classify * p4Vec) + log(pClass4)
p0 = sum(vec2Classify * p0Vec) + log(pClass0)
## print(p0,p1,p2,p3,p4)無錫人流醫(yī)院 http://www.bhnkyy39.com/
return [p0,p1,p2,p3,p4].index(max([p0,p1,p2,p3,p4]))
if __name__ == "__main__":
dataset = [['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'],
['i','love','you'],
['you','kiss','me'],
['hate','heng','no'],
['can','i','hug','you'],
['refuse','me','ache'],
['1','4','3'],
['5','2','3'],
['1','2','3']]
# 0,1,2,3,4分別表示不同類別
classVec = [0,1,0,1,0,1,2,2,4,2,4,3,3,3]
print("正在創(chuàng)建詞頻列表")
myVocabList = createVocabList(dataset)
print("正在建詞向量")
trainMat = []
for postinDoc in dataset:
trainMat.append(setOfWords2Vec(myVocabList,postinDoc))
print("開始訓練")
p0V,p1V,p2V,p3V,p4V,pAb0,pAb1,pAb2,pAb3,pAb4 = trainNB0(array(trainMat),array(classVec))
# 輸入的測試案例
tmp = ['love','you','kiss','you']
thisDoc = array(setOfWords2Vec(myVocabList,tmp))
flag = classifyNB(thisDoc,p0V,p1V,p2V,p3V,p4V,pAb0,pAb1,pAb2,pAb3,pAb4)
print('flag is',flag)
免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權內(nèi)容。