1 import numpy as np 2 import re 3 4 #词表到向量的转换函数 5 def loadDataSet(): 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 return postingList, classVec 14 15 #创建一个包含在所有文档中出现的不重复词的列表 16 def createVocabList(dataSet): 17 vocabSet = set([]) #创建一个空集 18 for document in dataSet: 19 vocabSet = vocabSet | set(document) #创建两个集合的并集 20 return list(vocabSet) 21 22 #词集模型:文档中的每个词在词集中只出现一次 23 def setOfWords2Vec(vocabList, inputSet): 24 returnVec = [0] * len(vocabList) #创建长度与词汇表相同,元素都为0的向量 25 for word in inputSet: 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 return returnVec 31 32 #词袋模型: 文档中的每个词在词袋中可以出现多次 33 def bagOfWords2VecMN(vocabList, inputSet): 34 returnVec = [0] * len(vocabList) 35 for word in inputSet: 36 if word in vocabList: 37 returnVec[vocabList.index(word)] += 1 38 return returnVec 39 40 #朴素贝叶斯分类器训练函数 41 def trainNB0(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 in range(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 return p0Vect, p1Vect, pAbusive 65 66 #朴素贝叶斯分类函数 67 def classifyNB(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 return 0 74 75 #便利函数,封装所有操作 76 def testingNB(): 77 listOposts, listClasses = loadDataSet() 78 myVocabList = createVocabList(listOposts) 79 trainMat = [] 80 for postinDoc in listOposts: 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 def textParse(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 def spamTest(): 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 in trainingSet: 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 = 0 119 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()
Output:
The error rate is: 0.1
背景:为什么要做平滑处理?
零概率问题,就是在计算实例的概率时,如果某个量x,在观察样本库(训练集)中没有出现过,会导致整个实例的概率结果是0。在文本分类的问题中,当一个词语没有在训练样本中出现,该词语调概率为0,使用连乘计算文本出现概率时也为0。这是不合理的,不能因为一个事件没有观察到就武断的认为该事件的概率是0。
拉普拉斯的理论支撑
为了解决零概率的问题,法国数学家拉普拉斯最早提出用加1的方法估计没有出现过的现象的概率,所以加法平滑也叫做拉普拉斯平滑。
假定训练样本很大时,每个分量x的计数加1造成的估计概率变化可以忽略不计,但可以方便有效的避免零概率问题。
根据现实情况修改分类器
除了平滑处理,另一个遇到的问题是下溢出,这是由于太多很小的数相乘造成的。当计算乘积P(w0|c1)P(w1|c1)P(w2|c1)...P(wN|c1)时, 由于大部分因子都非常小,所以程序会下溢出或者得不到正确的答案。一种解决办法是对乘积取自然对数。在代数中有ln(a*b) = ln(a) + ln(b),于是通过求对数可以避免下溢出或者浮点数舍入导致的错误。同时,采用自然对数进行处理不会有任何损失。
Reference:
《机器学习实战》
时间: 2024-11-05 19:42:15