本文实例讲述了Python实现的朴素贝叶斯算法。分享给大家供大家参考,具体如下:
代码主要参考机器学习实战那本书,发现最近老外的书确实比中国人写的好,由浅入深,代码通俗易懂,不多说上代码:
#encoding:utf-8'''''Created on 2015年9月6日@author: ZHOUMEIXU204朴素贝叶斯实现过程'''#在该算法中类标签为1和0,如果是多标签稍微改动代码既可import numpy as nppath=u"D://Users//zhoumeixu204/Desktop//python语言机器学习//机器学习实战代码 python//机器学习实战代码//machinelearninginaction//Ch04//"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,classVecdef createVocabList(dataset): vocabSet=set([]) for document in dataset: vocabSet=vocabSet|set(document) return list(vocabSet)def setOfWordseVec(vocabList,inputSet): returnVec=[0]*len(vocabList) for word in inputSet: if word in vocabList: returnVec[vocabList.index(word)]=1 #vocabList.index() 函数获取vocabList列表某个元素的位置,这段代码得到一个只包含0和1的列表 else: print("the word :%s is not in my Vocabulary!"%word) return returnVeclistOPosts,listClasses=loadDataSet()myVocabList=createVocabList(listOPosts)print(len(myVocabList))print(myVocabList)print(setOfWordseVec(myVocabList, listOPosts[0]))print(setOfWordseVec(myVocabList, listOPosts[3]))#上述代码是将文本转化为向量的形式,如果出现则在向量中为1,若不出现 ,则为0def trainNB0(trainMatrix,trainCategory): #创建朴素贝叶斯分类器函数 numTrainDocs=len(trainMatrix) numWords=len(trainMatrix[0]) pAbusive=sum(trainCategory)/float(numTrainDocs) p0Num=np.ones(numWords);p1Num=np.ones(numWords) p0Deom=2.0;p1Deom=2.0 for i in range(numTrainDocs): if trainCategory[i]==1: p1Num+=trainMatrix[i] p1Deom+=sum(trainMatrix[i]) else: p0Num+=trainMatrix[i] p0Deom+=sum(trainMatrix[i]) p1vect=np.log(p1Num/p1Deom) #change to log p0vect=np.log(p0Num/p0Deom) #change to log return p0vect,p1vect,pAbusivelistOPosts,listClasses=loadDataSet()myVocabList=createVocabList(listOPosts)trainMat=[]for postinDoc in listOPosts: trainMat.append(setOfWordseVec(myVocabList, postinDoc))p0V,p1V,pAb=trainNB0(trainMat, listClasses)if __name__!='__main__': print("p0的概况") print (p0V) print("p1的概率") print (p1V) print("pAb的概率") print (pAb)
运行结果:
32
['him', 'garbage', 'problems', 'take', 'steak', 'quit', 'so', 'is', 'cute', 'posting', 'dog', 'to', 'love', 'licks', 'dalmation', 'flea', 'I', 'please', 'maybe', 'buying', 'my', 'stupid', 'park', 'food', 'stop', 'has', 'ate', 'help', 'how', 'mr', 'worthless', 'not']
新闻热点
疑难解答