朴素贝叶斯称为“朴素”,是因为整个形式化过程只做最原始、最简单的假设。
--基于贝叶斯决策理论的分类方法
![](https://img.haomeiwen.com/i13925449/8098f3b668447b58.png)
贝叶斯决策理论的核心思想是,选择具有最高概率的决策。
--条件概率
![](https://img.haomeiwen.com/i13925449/3c7a7cfed32c2643.png)
--使用条件概率来分类
--使用朴素贝叶斯进行文档分类
朴素贝叶斯是贝叶斯分类器的一个扩展,是用于文档分类的常用算法。
![](https://img.haomeiwen.com/i13925449/82a1a5d2a1f539f3.png)
要得到好的概率分布,就需要足够的数据样本,所需样本数会随着特征数目增大而迅速增长。
独立是指一个特征或者单词出现的可能性与和其他单词相邻没有关系。
朴素贝叶斯分类器中的另一个假设是,每个特征同等重要。朴素贝叶斯分类器通常有两种实现方式:一种基于贝努利模型实现,一种基于多项式模型实现。贝努利实现方式中并不考虑词在文档中出现的次数,只考虑出不出现,因此在这个意义上相当于假设词是等权重的。
--使用Python进行文本分类
文本中的特征是来自文本的词条(token),一个词条是字符的任意组合。可以把词条想象为单词,也可以使用非单词词条,然后将每一个文本片段表示为一个词条向量,其中值为1表示词条出现在文档中,0表示词条未出现。
准备数据:从文本中构建词向量
#词表到向量的转换函数
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']]
# 定义标签向量,1——abusive,0——not abusive
classVec=[0,1,0,1,0,1]
#返回邮件列表和标签向量
return postingList,classVec
# 创建词汇列表
def createVocabList(dataSet):
# 定义词汇集
vocabSet=set([])
# 遍历文档
for document in dataSet:
# 将每个document合并到vocabSet,|用来联合两个集合
vocabSet=vocabSet|set(document)
# 返回词汇集
return list(vocabSet)
# 把单词转换成向量,参数为词汇表和某个文档
def setOfWords2Vec(vocabList,inputSet):
# 定义要返回的向量
returnVec=[0]*len(vocabList)
# 遍历输出集中的单词
for word in inputSet:
# 单词在词汇集中
if word in vocabList:
# 对应的位置设为1
returnVec[vocabList.index(word)]=1
else:
print("the word:%s is not in my Vocabulary!" % word)
# 返回向量
return returnVec
#输出结果:
import bayes
listOPosts,listClasses=bayes.loadDataSet()
print(listOPosts)
myVocabList=bayes.createVocabList(listOPosts)
print(myVocabList)
print(bayes.setOfWords2Vec(myVocabList,listOPosts[0]))
print(bayes.setOfWords2Vec(myVocabList,listOPosts[3]))
输出:
[['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']]
['problems', 'posting', 'dalmation', 'so', 'steak', 'him', 'my', 'cute', 'how', 'mr', 'love', 'is', 'food', 'to', 'licks', 'dog', 'ate', 'I', 'buying', 'has', 'park', 'quit', 'please', 'take', 'worthless', 'help', 'stop', 'garbage', 'flea', 'stupid', 'maybe', 'not']
[1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 0]
[0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 1, 0, 1, 0, 0]
网友评论