当前位置:网站首页>朴素贝叶斯文本分类(代码实现)
朴素贝叶斯文本分类(代码实现)
2022-07-31 05:15:00 【龙虾在剥我的壳】
朴素贝叶斯算法实现案例
1.概述
要介绍朴素贝叶斯算法(Naive Bayes),那就得先介绍贝叶斯分类算法,贝叶斯分类算法是统计分类算法的一种,他是一类利用概率统计知识进行的一种分类算法。而朴素贝叶斯算法就是里面贝叶斯算法中最简单的一个算法。为什么叫做朴素贝叶斯,因为他里面的各个类条件是独立的,所以一会在后面的计算中会起到很多方便的作用。
注:朴素的意思是条件概率独立性
2.算法思想
朴素贝叶斯的思想是这样的:
如果一个事物在一些属性条件发生的情况下,事物属于A的概率>属于B的概率,则判定事物属于A
通俗的来说比如,你在街上看到一个黑人,我让你猜这人哪里来的,你很有可能猜来自非洲。为什么呢?
在你的脑海中,有这么一个判断流程:
1.这个人的皮肤是黑色 <特征>
2.黑色人种是非洲人的概率最高<条件概率:黑色条件下是非洲人的概率>
3.没有其它辅助信息的情况下,最好的判断就是非洲人
这就是朴素贝叶斯的思想基础。
3.算法步骤
1.分解各类先验样本数据中的特征
2.计算各类数据中,各特征的条件概率
(比如:特征1出现的情况下,属于A类的概率p(A|特征1),属于B类的概率p(B|特征1),属于C类的概率(C|特征1)…)
3.分解待分类数据中的特征(特征1,特征2,特征3,特征4…)
4、计算各特征的各条件概率的乘积,如下所示:
判断为A类的概率:p(A|特征1)*p(A|特征2)*p(A|特征3)*p(A|特征4)…
判断为B类的概率:p(B|特征1)*p(B|特征2)*p(B|特征3)*p(B|特征4)…
判断为C类的概率:p(C|特征1)*p(C|特征2)*p(C|特征3)*p(C|特征4)…
…
5、结果中的最大值就是该样本所属的类别
朴素贝叶斯算法的代码实现
#!/usr/bin/python
# coding=utf-8
from numpy import *
# 过滤网站的恶意留言 侮辱性: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’]]
classVec = [0,1,0,1,0,1]
return postingList, classVec
# 创建一个包含在所有文档中出现的不重复词的列表
def createVocabList(dataSet):
vocabSet = set([]) # 创建一个空集
for document in dataSet:
vocabSet = vocabSet | set(document) # 创建两个集合的并集
return list(vocabSet)
# 将文档词条转换成词向量
def setOfWords2Vec(vocabList, inputSet):
returnVec = [0]*len(vocabList) # 创建一个其中所含元素都为0的向量
for word in inputSet:
if word in vocabList:
# returnVec[vocabList.index(word)] = 1 # index函数在字符串里找到字符第一次出现的位置 词集模型
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 = zeros(numWords); p1Num = zeros(numWords)
# p0Denom = 0.0; p1Denom = 0.0
p0Num = ones(numWords); # 避免一个概率值为0,最后的乘积也为0
p1Num = ones(numWords); # 用来统计两类数据中,各词的词频
p0Denom = 2.0; # 用于统计0类中的总数
p1Denom = 2.0 # 用于统计1类中的总数
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 = p1Num / p1Denom
# p0Vect = p0Num / p0Denom
p1Vect = log(p1Num / p1Denom) # 在类1中,每个次的发生概率
p0Vect = log(p0Num / p0Denom) # 避免下溢出或者浮点数舍入导致的错误 下溢出是由太多很小的数相乘得到的
return p0Vect, p1Vect, pAbusive
# 朴素贝叶斯分类器
def classifyNB(vec2Classify, p0Vec, p1Vec, pClass1):
p1 = sum(vec2Classifyp1Vec) + log(pClass1)
p0 = sum(vec2Classifyp0Vec) + log(1.0-pClass1)
if p1 > p0:
return 1
else:
return 0
def testingNB():
listOPosts, listClasses = loadDataSet()
myVocabList = createVocabList(listOPosts)
trainMat = []
for postinDoc in listOPosts:
trainMat.append(setOfWords2Vec(myVocabList, postinDoc))
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’]
thisDoc = array(setOfWords2Vec(myVocabList, testEntry))
print (testEntry, 'classified as: ', classifyNB(thisDoc, p0V, p1V, pAb))
#调试方法
testingNB()
运行结果

边栏推荐
- sqlmap injection tutorial common commands
- 【云原生】开源数据分析 SPL 轻松应对 T+0
- Build DVWA with phpstudy
- 360 加固 file path not exists.
- Take you to understand the MySQL isolation level, what happens when two transactions operate on the same row of data at the same time?
- unicloud 云开发记录
- 一个简单的bash转powershell案例
- 安装Multisim出现 No software will be installed or removed解决方法
- 微信小程序源码获取与反编译方式
- 理解js运算符
猜你喜欢

数据库 | SQL增删改查基础语法

UiBot has an open Microsoft Edge browser and cannot perform the installation

MySQL错误-this is incompatible with sql_mode=only_full_group_by完美解决方案

What is the difference between NFT and digital collection?

js中的this指向与原型对象

Error: Cannot find module 'D:\Application\nodejs\node_modules\npm\bin\npm-cli.js'

Why does read in bash need to cooperate with while to read the contents of /dev/stdin

场效应管 | N-mos内部结构详解
![[JVM Loading]---Class Loading Mechanism](/img/b6/d1754cb6699d18602ca9a463571c0c.png)
[JVM Loading]---Class Loading Mechanism

带你搞懂MySQL隔离级别,两个事务同时操作同一行数据会怎样?
随机推荐
[Elastic-Job] Overview of Distributed Scheduling Tasks
VS connects to MYSQL through ODBC (2)
[Cloud Native] What should I do if SQL (and stored procedures) run too slowly?
Install mysqldb in mac10.14
Android software security and reverse analysis reading notes
动态规划(一)| 斐波那契数列和归递
浏览器查找js绑定或者监听的事件
360 hardening file path not exists.
Powershell中UTF-8环境中文乱码解决办法
Artifact SSMwar exploded Error deploying artifact.See server log for details
Fragmented NFT (Fractional NFT)
一文速学-玩转MySQL获取时间、格式转换各类操作方法详解
[Cloud native] Simple introduction and use of microservice Nacos
js中的this指向与原型对象
flutter arr dependencies
著名网站msdn.itellyou.cn原理分析
cocos2d-x 实现跨平台的目录遍历
"limit" query in Oracle database
cocos2d-x-3.2创建项目方法
Understanding of objects and functions in js