1 / 10

# 朴素贝叶斯python代码实现.docx

。(勺)
p(q|x：)表示1love',1help1,^garbage','quit',111,1problems','is1,1park','stop
bayes.setOfWords2Vec(myVocdbLtst,l_ist0Posts[0])
[o,G,fo,o,-i,o,%o,-i,e,o,o,o,o,o,ef-i,o,o,o,o,-i,-i，%8,%0,S%-1]
aabayes*setOfWords2Vec(myVocabLtstaListOPosts[3])
[o,e,o,i,e,e,o,色，e,-i,o,e,o,o,g,o,d,-i,i,日，o,o,o,e,0,-1,0,E>,E>,B,0]

[python]
viewplaincopy

#朴素贝叶斯分类器训练函数
#trainMatrix:文档矩阵，trainCategory:由每篇文档类别标签所构成的向量
deftrainNB0(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;
foriinrange(numTrainDocs):
iftrainCategory[i]==1:
p1Num+=trainMatrix[i]
p1Denom+=sum(trainMatrix[i])
else:
p0Num+=trainMatrix[i]
p0Denom+=sum(trainMatrix[i])
p1Vect=p1Num/p1Denom
p0Vect=p0Num/p1Denom
returnp0Vect,p1Vect,pAbusive

**

fronnumpyimport*
'bayes'fronTbayes+pyb>
»>nyvocabList=bayes^createvocabLtst(ItstOPosts)trai.nMat=[]
>»forpostinQocinlistOPosts:
...trainMat,.ap