我是靠谱客的博主 追寻海燕,最近开发中收集的这篇文章主要介绍朴素贝叶斯分类器python_朴素贝叶斯算法的python实现 -- 机器学习实战,觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

1 importnumpy as np2 importre3

4 #词表到向量的转换函数

5 defloadDataSet():6 postingList = [['my', 'dog', 'has', 'flea', 'problems', 'help', 'please'],7 ['maybe', 'not', 'take', 'him', 'to', 'dog', 'park', 'stupid'],8 ['my', 'dalmation', 'is', 'so', 'cute', 'I', 'love', 'him'],9 ['stop', 'posting', 'stupid', 'worthless', 'garbage'],10 ['mr', 'licks', 'ate', 'my', 'steak', 'how', 'to', 'stop', 'him'],11 ['quit', 'buying', 'worthless', 'dog', 'food', 'stupid']]12 classVec =[0,1,0,1,0,1] #1代表侮辱性文字,0代表正常言论

13 returnpostingList, classVec14

15 #创建一个包含在所有文档中出现的不重复词的列表

16 defcreateVocabList(dataSet):17 vocabSet = set([]) #创建一个空集

18 for document indataSet:19 vocabSet = vocabSet | set(document) #创建两个集合的并集

20 returnlist(vocabSet)21

22 #词集模型:文档中的每个词在词集中只出现一次

23 defsetOfWords2Vec(vocabList, inputSet):24 returnVec = [0] * len(vocabList) #创建长度与词汇表相同,元素都为0的向量

25 for word ininputSet:26 if word in vocabList: #将出现在文档中的词汇在词汇表中对应词汇位置置1

27 returnVec[vocabList.index(word)] = 1

28 else:29 print ("the word: %s isn't in my Vocabulary" %(word))30 returnreturnVec31

32 #词袋模型: 文档中的每个词在词袋中可以出现多次

33 defbagOfWords2VecMN(vocabList, inputSet):34 returnVec = [0] *len(vocabList)35 for word ininputSet:36 if word invocabList:37 returnVec[vocabList.index(word)] += 1

38 returnreturnVec39

40 #朴素贝叶斯分类器训练函数

41 deftrainNB0(trainMatrix, trainCategory):42 numTrainDocs =len(trainMatrix)43 numWords =len(trainMatrix[0])44 pAbusive = sum(trainCategory)/float(numTrainDocs)45 #p0Num = np.zeros(numWords)

46 #p1Num = np.zeros(numWords)

47 #p0Denom = 0.0

48 #p1Denom = 0.0

49 p0Num = np.ones(numWords) #|利用贝叶斯分类器对文档进行分类时,要计算多个概率的乘积以获得文档属于某个类别的概率,

50 p1Num = np.ones(numWords) #|如果其中一个概率值为0,那么最后的乘积也为0.

51 p0Denom = 2.0 #|为降低这种影响,可以将所有词的出现数初始化为1,并将分母初始化为2

52 p1Denom = 2.0 #|(拉普拉斯平滑)

53 for i inrange(numTrainDocs):54 if trainCategory[i] == 1:55 p1Num +=trainMatrix[i]56 p1Denom +=sum(trainMatrix[i])57 else:58 p0Num +=trainMatrix[i]59 p0Denom +=sum(trainMatrix[i])60 #p1Vect = p1Num/p1Denom

61 #p0Vect = p0Num/p0Denom

62 p1Vect = np.log(p1Num/p1Denom) #|当太多很小的数相乘时,程序会下溢出,对乘积取自然对数可以避免下溢出或浮点数舍入导致的错误

63 p0Vect = np.log(p0Num/p0Denom) #|同时,采用自然对数进行处理不会有任何损失。ln(a*b)=ln(a)+ln(b)

64 returnp0Vect, p1Vect, pAbusive65

66 #朴素贝叶斯分类函数

67 defclassifyNB(vec2Classify, p0Vec, p1Vec, pClass1):68 p1 = sum(vec2Classify * p1Vec) + np.log(pClass1) #元素相乘得到概率值

69 p0 = sum(vec2Classify * p0Vec) + np.log(1.0 -pClass1)70 if p1 >p0:71 return 1

72 else:73 return074

75 #便利函数,封装所有操作

76 deftestingNB():77 listOposts, listClasses =loadDataSet()78 myVocabList =createVocabList(listOposts)79 trainMat =[]80 for postinDoc inlistOposts:81 trainMat.append(setOfWords2Vec(myVocabList, postinDoc))82 p0V, p1V, pAb = trainNB0(np.array(trainMat), np.array(listClasses)) #获取训练文档返回的概率值

83 testEntry = ['love', 'my', 'dalmation'] #正面测试文档

84 thisDoc = np.array(setOfWords2Vec(myVocabList, testEntry)) #词汇表

85 print (testEntry, 'classified as:', classifyNB(thisDoc, p0V, p1V, pAb)) #分类结果

86 testEntry = ['stupid', 'garbage'] #侮辱性测试文档

87 thisDoc = np.array(setOfWords2Vec(myVocabList, testEntry)) #词汇表

88 print (testEntry, 'classified as:', classifyNB(thisDoc, p0V, p1V, pAb)) #分类结果

89

90 #文件解析

91 deftextParse(bigString):92 listOfTokens = re.split(r'W+', bigString) #原书中的模式为W*,匹配0个或多个

93 return [tok.lower() for tok in listOfTokens if len(tok) > 2]94

95 #完整的垃圾邮件测试函数

96 defspamTest():97 docList=[]; classList=[]; fullText=[]98 for i in range(1, 26): #导入并解析文件

99 wordList = textParse(open('email/spam/%d.txt' %i).read())100 docList.append(wordList)101 fullText.extend(wordList)102 classList.append(1)103 wordList = textParse(open('email/ham/%d.txt' %i).read())104 docList.append(wordList)105 fullText.extend(wordList)106 classList.append(0)107 vocabList =createVocabList(docList)108 trainingSet = list(range(50)); testSet=[]109 for i in range(10): #随机构建训练集与测试集

110 randIndex =int(np.random.uniform(0, len(trainingSet)))111 testSet.append(trainingSet[randIndex])112 del(trainingSet[randIndex])113 trainMat=[]; trainClasses=[]114 for docIndex intrainingSet:115 trainMat.append(setOfWords2Vec(vocabList, docList[docIndex]))116 trainClasses.append(classList[docIndex])117 p0V, p1V, pSpam =trainNB0(np.array(trainMat), np.array(trainClasses))118 errorCount =0119 for docIndex in testSet: #对测试集分类并计算错误率

120 wordVector =setOfWords2Vec(vocabList, docList[docIndex])121 if classifyNB(np.array(wordVector), p0V, p1V, pSpam) !=classList[docIndex]:122 errorCount += 1

123 print ('The error rate is:', float(errorCount/len(testSet)))124

125 #Simple unit test of func: loadDataSet(), createVocabList(), setOfWords2Vec

126 #listOPosts, listClassed = loadDataSet()

127 #myVocabList =createVocabList(listOPosts)

128 #print (myVocabList)

129 #res = setOfWords2Vec(myVocabList, listOPosts[0])

130 #print (res)

131

132 #Simple unit test of func: trainNB0()

133 #listOposts, listClasses = loadDataSet()

134 #myVocabList = createVocabList(listOposts)

135 #trainMat = []

136 #for postinDoc in listOposts:

137 #trainMat.append(setOfWords2Vec(myVocabList, postinDoc))

138 #p0V, p1V, pAb = trainNB0(trainMat, listClasses)

139 #print (p0V); print (p1V); print (pAb)

140

141 #Simple unit test of func: testingNB()

142 #testingNB()

143

144 spamTest()

最后

以上就是追寻海燕为你收集整理的朴素贝叶斯分类器python_朴素贝叶斯算法的python实现 -- 机器学习实战的全部内容,希望文章能够帮你解决朴素贝叶斯分类器python_朴素贝叶斯算法的python实现 -- 机器学习实战所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(44)

评论列表共有 0 条评论

立即
投稿
返回
顶部