今天学习NB(nave Bayes)算法.看看此算法是不是真NB。
朴素贝叶斯法基于两点:
已知输入:
含有 N 个样本的训练集, T={(x⃗ (1),y(1)),(x⃗ (2),y(2)).....,(x⃗ (N),y(N))} ,其中特征向量 x⃗ (i)=(x(i)1,x(i)2,....,x(i)n)T , x(i)j 表示第 i 个样本的第 j 维特征, xj∈{aj1,aj2...,ajSj} ,其中, ajl 为第 j 维特征中第 l 个可能取值, Sj 为第 j 维特征可能取值的个数, j=1,2,3...,n,l=1,2,...,Sj,y(i)∈c1,c2,...cK ;实例 x⃗ ;
输出: x⃗ 的类别 y
以上条件概率和先验概率估计通过最大似然估计得出,其中会出现概率为0的情况,此时会影响到后验概率的计算结果。解决此问题的方法可采用贝叶斯估计。
条件概率的贝叶斯估计为:
《机器学习实战》中,文本分类,主要流程为:
from numpy import *
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 is abusive, 0 not
return postingList,classVec
#根据训练样本提取特征向量
def createVocabList(dataSet):
vocabSet = set([]) #create empty set
for document in dataSet:
vocabSet = vocabSet | set(document) #union of the two sets
return list(vocabSet)
#将文本集转换为标准特征向量
def setOfWords2Vec(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
#分类训练,计算先验概率和条件概率
def trainNB0(trainMatrix,trainCategory):
numTrainDocs = len(trainMatrix)
numWords = len(trainMatrix[0])
pAbusive = sum(trainCategory)/float(numTrainDocs)
p0Num = ones(numWords); p1Num = ones(numWords) #change to ones()
p0Denom = 2.0; p1Denom = 2.0 #change to 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 = log(p1Num/p1Denom) #change to log()
p0Vect = log(p0Num/p0Denom) #change to log()
return p0Vect,p1Vect,pAbusive
#预测
def classifyNB(vec2Classify, p0Vec, p1Vec, pClass1):
p1 = sum(vec2Classify * p1Vec) + log(pClass1) #element-wise mult
p0 = sum(vec2Classify * p0Vec) + log(1.0 - pClass1)
if p1 > p0:
return 1
else:
return 0