4.5 使用Python进行文本分类
4.5.1 准备数据:从文本中构建词向量
#coding:utf-8 from numpy import * #准备数据:从文本中构建词向量 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]# 1代表侮辱性文字,0代表正常言论 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) for word in inputSet: if word in vocabList: returnVec[vocabList.index(word)] = 1 else: print "the word: %s is not in my Vocabulary!" % word return returnVec
4.5.2 训练算法:从词向量计算概率
#训练算法:计算每个词在每种类别下出现的概率 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 #分母:浮点数 for i in range(numTrainDocs): if trainCategory[i] == 1:#类别为1 p1Num += trainMatrix[i]#分子 p1Denom += sum(trainMatrix[i])#分母 else: p0Num += trainMatrix[i] p0Denom += sum(trainMatrix[i]) p1Vect = p1Num / p1Denom#条件概率 p0Vect = p0Num / p1Denom#条件概率 return p0Vect, p1Vect, pAbusive
4.5.3 测试算法:根据显示情况修改分类器
拉普拉斯平滑
条件概率p(w0|1)p(w1|1)p(w2|1),如果一个为0,最后乘机也为0.为降低这种影响,可以将所有词出现数初始化为1,分母初始化为2.
打开bayes.py,将trainNB0()的第4行和第5行修改为:
p0Num = ones(numWords); p1Num = ones(numWords) p0Denom = 2.0; p2Denom = 2.0
另一个问题是下溢出,由于太多很小数相乘造成。一种解决方法是对乘积取自然对数,采用自然对数处理不会有任何损失。
将trainNB0()的return前两行代码修改为:
p1Vect = log(p1Num / p1Denom) p2Vect = log(p0Num / p0Denom)
将下面代码添加到bayes.py中:
#测试算法:根据现实情况修改分类器 #朴素贝叶斯分类算法 def classifyNB(vec2Classify, p0Vec, p1Vec, pClass1):#输入第一个元素:要分类的向量 p1 = sum(vec2Classify * p1Vec) + log(pClass1)#元素相乘 p0 = sum(vec2Classify * p0Vec) + log(1.0 - pClass1) if p1 > p0: return 1 else: return 0 def testingNB():#便利函数convenience function:封装所有操作 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‘, ‘garbage‘] thisDoc = array(setOfWords2Vec(myVocabList, testEntry)) print testEntry, ‘classified as:‘, classifyNB(thisDoc, p0V, p1V, pAb)
4.5.4 准备数据:根据显示情况修改分类器
目前为止,我们将每个词的出现与否作为一个特征,这被描述为词集模型(set-of-words model).
如果每个单词可以出现多次作为特征,这被描述为词袋模型(bag-of-words model).
为适应词袋模型,需对setOfWords2Vec()稍加修改,唯一不同是遇到每个单词时,会增加词向量中的对应值,而不只是将对应的数值设为1.
#将一组单词转化一组数字,即将词汇表转换为一组向量:词集模型 def bagOfWords2Vec(vocabList, inputSet):#输入:词汇表,某个文档 returnVec = [0] * len(vocabList) for word in inputSet: if word in vocabList: returnVec[vocabList.index(word)] += 1 return returnVec
现在分类器已构建好,下面将利用该分类器来过滤垃圾邮件。
时间: 2024-10-24 16:51:32