from numpy import *
def loadDataSet():#positionlist相当于多个文档,每行为一个文档,classvec相当于他的标签
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):#将所有出现在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):#vocablist是输入的单词列表,inputset是单词匹配区,如果在vocablist中存在inputset中的单词,则在列表该位置值为1
returnVec = [0]*len(vocabList)#列表*一个常数,则列表扩宽原来的常数被,内部的值重复,print([1,2,3,4,5]*3)>>[1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5]
for word in inputSet:
if word in vocabList:
returnVec[vocabList.index(word)] = 1
else: print ("the word: %s is not in my Vocabulary!" % word)#在最后的测试阶段,有可能拿到的文档信息中具有之前没有出现过的单词the word: dalmation1 is not in my Vocabulary!
return returnVec#这里返回的是inputset中的数据,可以认为是某一个文档中的数据inputset,在所有文档中文字vocablist下出现的情况
def trainNB0(trainMatrix,trainCategory):#trainmatrix为文档矩阵,经上方的returnvec得来,traincategory为每篇文档类别标签
numTrainDocs = len(trainMatrix)#矩阵的行为文档的个数
numWords = len(trainMatrix[0])#矩阵的列为每一篇文档的字数
pAbusive = sum(trainCategory)/float(numTrainDocs)#traincategory列表中的求和值,是列表中1的个数,numtraindocs是文档的个数,也是1类型文档占总文档的比例
p0Num = ones(numWords); p1Num = ones(numWords) #change to ones() ,numwords个元素的全1矩阵
p0Denom = 2.0; p1Denom = 2.0 #change to 2.0
for i in range(numTrainDocs):
if trainCategory[i] == 1:#当文档标签的类型为一时
p1Num += trainMatrix[i]#将标签为1的文档中所有文字出现的次数进行纵向统计,因为在trainmatrix中的一行记录的是dataset的一行在所有文字中出现的情况
p1Denom += sum(trainMatrix[i])#将标签为1的文档中,trainmatrix的每一行文字的字数求和,是1类型的总字数
else:
p0Num += trainMatrix[i]
p0Denom += sum(trainMatrix[i])
p1Vect = log(p1Num/p1Denom) #change to log(),计算结果是在标签是1的所有文档下,每种文字在1类型总字数下的分别比值
p0Vect = log(p0Num/p0Denom) #change to log().计算结果是在标签是0的所有文档下,每种文字在0类型总字数下的分别比值
#print(p1Num,p1Denom)
return p0Vect,p1Vect,pAbusive#返回的结果是在文档标签类型为1和0的条件下各种文字出现的概率,pabusive是1类型文档占总文档的比例
def classifyNB(vec2Classify, p0Vec, p1Vec, pClass1):
p1 = sum(vec2Classify * p1Vec) + log(pClass1) #element-wise mult,两个向量对应位置的元素乘积
p0 = sum(vec2Classify * p0Vec) + log(1.0 - pClass1)
if p1 > p0:
return 1
else:
return 0
def bagOfWords2VecMN(vocabList, inputSet):
returnVec = [0]*len(vocabList)
for word in inputSet:
if word in vocabList:
returnVec[vocabList.index(word)] += 1
return returnVec
def testingNB():
listOPosts,listClasses = loadDataSet()#listOPosts含有文字的文档矩阵,listClasses文档矩阵每一行的标签属性
myVocabList = createVocabList(listOPosts)##将所有出现在listOPosts中的数据转换为不重复的单词列表,该列表包含了所有文档中出现的单词
trainMat=[]#空的文档矩阵,用来存放文档中各个文字出现的情况
for postinDoc in listOPosts:
trainMat.append(setOfWords2Vec(myVocabList, postinDoc))#使用append最后的结果为列表中的列表,有值的话对应位置结果为1,否则结果是0
p0V,p1V,pAb = trainNB0(array(trainMat),array(listClasses))#计算结果是在标签是0和1的所有文档下,每种文字在0和1类型总字数下的分别比值
testEntry = ['love', 'my', 'dalmation1']
thisDoc = array(setOfWords2Vec(myVocabList, testEntry))#转换为和trainmat一样的形式
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 textParse(bigString): #input is big string, #output is word list
import re
listOfTokens = re.split(r'\W*', bigString)#http://blog.youkuaiyun.com/manjhok/article/details/78586818;以非字母字符进行分割,正则表达式
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('email/spam/%d.txt' % i).read())#wordlist是一个长度大于2的单词列表
docList.append(wordList)#doclist是包含了单词列表的多维矩阵
fullText.extend(wordList)#fulltext是一个包含所有单词包括重复了的单词列表
classList.append(1)#添加分类标签1
wordList = textParse(open('email/ham/%d.txt' % i).read())#读取非垃圾邮件的单词列表,一行垃圾邮件单词列表,一行正常邮件单词列表
docList.append(wordList)
fullText.extend(wordList)
classList.append(0)#添加分类标签0
vocabList = createVocabList(docList)#create vocabulary,#将所有出现在doclist中的数据转换为不重复的单词列表,该列表包含了所有文档中出现的单词,包括0类和1类
trainingSet = range(50); testSet=[] #create test set,垃圾邮件和正常邮件数目为26+26=52
for i in range(10):
randIndex = int(random.uniform(0,len(trainingSet)))
testSet.append(trainingSet[randIndex])
del(trainingSet[randIndex]) #删除之后这样的目的在于不会出现重复的结果,比如原来的6被删除,那么列表中就会只有,,4,5,7,,,
trainMat=[]; trainClasses = []
for docIndex in trainingSet:#train the classifier (get probs) trainNB0
trainMat.append(bagOfWords2VecMN(vocabList, docList[docIndex]))#vocablist是所有单词出现情况的列表
trainClasses.append(classList[docIndex])
p0V,p1V,pSpam = trainNB0(array(trainMat),array(trainClasses))
errorCount = 0
for docIndex in testSet: #classify the remaining items
wordVector = bagOfWords2VecMN(vocabList, docList[docIndex])
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
机器学习-朴素贝叶斯分类代码详解
最新推荐文章于 2023-09-14 08:32:16 发布