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 is abusive, 0 not
return postingList,classVec
def createVocabList(dataSet):
vocabSet = set([]) #create empty set
for document in dataSet:
vocabSet = vocabSet | set(document) #union of the two sets
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
def trainNB0(trainMatrix,trainCategory):
#numTrainDocs训练集总条数
numTrainDocs = len(trainMatrix)
#每条训练数据总单词数
numWords = len(trainMatrix[0])
#侮辱类的概率(侮辱类占总训练数据的比例)
pAbusive = sum(trainCategory)/float(numTrainDocs)
#拉普拉斯平滑,所有单词一开始全部置为1,防止概率为0
#正常类向量置为1
p0Num = ones(numWords);
#侮辱类向量置为1
p1Num = ones(numWords)
#分母置为2
p0Denom = 2.0;
p1Denom = 2.0
#遍历训练集数据
for i in range(numTrainDocs):
#该条训练数据为侮辱类
if trainCategory[i] == 1:
#侮辱类所含单词,次数加1
p1Num += trainMatrix[i]
#p1Denom侮辱类总词数
p1Denom += sum(trainMatrix[i])
#该条训练数据为正常类
else:
#正常类所含单词,次数增加
p0Num += trainMatrix[i]
#p0Denom正常类总词数
p0Denom += sum(trainMatrix[i])
#数据取log,即单个单词的p(x1|c1)取log,防止下溢出
p1Vect = log(p1Num/p1Denom)
p0Vect = log(p0Num/p0Denom)
#返回正常类、侮辱类的类条件概率向量,p0Vect,p1Vect
#每一项为拉普拉斯平滑处理后词的类条件概率取log以2底
#返回侮辱类的概率pAbusive
return p0Vect,p1Vect,pAbusive
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():
#获得训练数据,类别标签
listOPosts,listClasses = loadDataSet()
#创建词典
myVocabList = createVocabList(listOPosts)
#构建矩阵,存放训练数据
trainMat=[]
#遍历原始数据,转换为词向量,构成数据训练矩阵
for postinDoc in listOPosts:
#数据转换后存入数据训练矩阵trainMat中
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)
#文档词袋模型,词向量 值为该词在本篇文章中出现的次数
def bagOfWords2VecMN(vocabList, inputSet):
returnVec = [0]*len(vocabList)
for word in inputSet:
if word in vocabList:
returnVec[vocabList.index(word)] += 1
return returnVec
#准备数据,按空格切分出词
#单词长度小于或等于2的全部丢弃
def textParse(bigString):
import re
listOfTokens = re.split(r'\W*', bigString)
#tok.lower() 将整个词转换为小写
return [tok.lower() for tok in listOfTokens if len(tok) > 2]
def spamTest():
#文章按篇存放
docList=[];
#存放文章类别
classList = [];
#存放所有文章内容
fullText =[]
for i in range(1,26):
#读取垃圾邮件
wordList = textParse(open('D:/email/spam/%d.txt' % i).read())
#docList按篇存放文章
docList.append(wordList)
#fullText邮件内容存放到一起
fullText.extend(wordList)
#垃圾邮件类别标记为1
classList.append(1)
#读取正常邮件
wordList = textParse(open('D:/email/ham/%d.txt' % i).read())
docList.append(wordList)
fullText.extend(wordList)
#正常邮件类别标记为0
classList.append(0)
#创建词典
vocabList = createVocabList(docList)
#训练集共50篇文章
trainingSet = range(50);
#创建测试集
testSet=[]
#随机选取10篇文章为测试集,测试集中文章从训练集中删除
for i in range(10):
#0-50间产生一个随机数
randIndex = int(random.uniform(0,len(trainingSet)))
#从训练集中找到对应文章,加入测试集中
testSet.append(trainingSet[randIndex])
#删除对应文章
del(trainingSet[randIndex])
#准备数据,用于训练分类器
trainMat=[]; #训练数据
trainClasses = [] #类别标签
#遍历训练集中文章数据
for docIndex in trainingSet:
#每篇文章转为词袋向量模型,存入trainMat数据矩阵中
trainMat.append(bagOfWords2VecMN(vocabList, docList[docIndex]))
#trainClasses存放每篇文章的类别
trainClasses.append(classList[docIndex])
#训练分类器
p0V,p1V,pSpam = trainNB0(array(trainMat),array(trainClasses))
#errorCount记录测试数据出错次数
errorCount = 0
#遍历测试数据集,每条数据相当于一条文本
for docIndex in testSet:
#文本转换为词向量模型
wordVector = bagOfWords2VecMN(vocabList, docList[docIndex])
#模型给出的分类结果与本身类别不一致时,说明模型出错,errorCount数加1
if classifyNB(array(wordVector),p0V,p1V,pSpam) != classList[docIndex]:
errorCount += 1
#输出出错的文章
print "classification error",docList[docIndex]
#输出错误率,即出错次数/总测试次数
print 'the error rate is: ',float(errorCount)/len(testSet)
#return vocabList,fullText
if __name__ == "__main__":
#获取数据
listOPosts,listClasses = loadDataSet()
#构建词典
myVocabList = createVocabList(listOPosts)
trainMat = []
for postinDoc in listOPosts:
#构建训练矩阵
trainMat.append(setOfWords2Vec(myVocabList, postinDoc))
p0V,p1V,pAb = trainNB0(trainMat, listClasses)
#网站论坛内容分类
testingNB()
#垃圾邮件分类
spamTest()
Python Bayes
最新推荐文章于 2021-02-04 03:01:07 发布