1、贝叶斯定理(Bayes Theorem)
朴素贝叶斯分类(Naive Bayes Classifier)
贝叶斯分类算法,是统计学的一种分类方法,它是利用贝叶斯定理的概率统计知识,对离散型的数据进行分类的算法
2、贝叶斯算法的类型
sklearn包naive_bayes模块
GaussianNB 高斯贝叶斯
BernoulliNB 伯努利贝叶斯
MultionmialNB 多项式贝叶斯 (需要知道具体每个特征的数值大小)
一般应用于文本分类
3、实践案例
import codecs
import os.path
# 根据文件建立字典
classDict={
'C000007': '汽车',
'C000008': '财经',
'C000010': 'IT',
'C000013': '健康',
'C000014': '体育',
'C000016': '旅游',
'C000020': '教育',
'C000022': '招聘',
'C000023': '文化',
'C000024': '军事'
}
rootDir = "D:\\DATA\\pycase\\number2\\5.2\\SogouC.mini\\Sample"
# 语料库的搭建
classes=[]
filePaths=[]
fileContents=[]
for c in classDict.keys():
fileDir=os.path.join(rootDir,c)
for root,dirs,files in os.walk(fileDir):
for name in files:
filePath=os.path.join(fileDir,name)
classes.append(classDict[c])
filePaths.append(filePath)
f=codecs.open(filePath,'r','utf-8')
fileContent=f.read()
f.close()
fileContents.append(fileContent)
import pandas
# 创建数据框
corps=pandas.DataFrame({
'class':classes,
'filePath':filePaths,
'fileContent':fileContents
})
# 2 文本向量搭建,构建特征值
import re
# 匹配中文的分词
zhPattern=re.compile('[\u4e00-\u9fa5]+')
# 导入jieba分词工具
import jieba
segments=[]
filePaths=[]
# 遍历文件夹进行分词,对corps文件进行处理
for index,row in corps.iterrows():
segments=[] # 初始化,避免词汇累计导入下一个文件夹
filePath=row['filePath']
fileContent=row['fileContent']
segs=jieba.cut(fileContent)
for seg in segs:
if zhPattern.search(seg):
segments.append(seg)
filePaths.append(filePath)
row['fileContent']=" ".join(segments)
# stopword 自己根据自己的业务情况搭建词库
stopwords = pandas.read_csv(
"D:\\DATA\\pycase\\number2\\5.2\\StopwordsCN.txt",
encoding='utf8',
index_col=False,
quoting=3,
sep="\t"
)
# 导入向量方法,移除停用词
from sklearn.feature_extraction.text import CountVectorizer
countVectorizer = CountVectorizer(
stop_words=list(stopwords['stopword'].values),
min_df=0, token_pattern=r"\b\w+\b"
)
textVector = countVectorizer.fit_transform(corps['fileContent'])
# 3对文本进行分类操作,利用贝叶斯多项式分类操作
from sklearn.naive_bayes import MultinomialNB
MNBModel = MultinomialNB()
MNBModel.fit(textVector, corps['class'])
MNBModel.score(textVector, corps['class']) # 贝叶斯分类的得分
# 4 对文本进行分类预测
newTexts = ["""
据介绍,EliteBook 840 G4是一款采用14英寸1080p屏幕的商务笔记本,
硬件配置方面,入门级的EliteBook 840 G4搭载Intel Core i3-7100处理器,
配备4GB内存和500GB机械硬盘,预装Windows 10操作系统。
高端机型可选择更大容量的内存和SSD固态硬盘。
机身四周提供了USB 3.0、USB-C、DisplayPort、15针迷你D-Sub,
支持蓝牙4.2和802.11ac Wi-Fi。
整机重1.48千克。
"""]
for i in range(len(newTexts)):
newTexts[i] = " ".join(jieba.cut(newTexts[i])) # 遍历文本进行分词
newTextVector = countVectorizer.transform(newTexts) # 移除停用词
MNBModel.predict(newTextVector)
版权声明:本文为qq_36327687原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。