200字范文,内容丰富有趣,生活中的好帮手!
200字范文 > 机器学习实战笔记——贝叶斯估计

机器学习实战笔记——贝叶斯估计

时间:2022-03-31 00:36:46

相关推荐

机器学习实战笔记——贝叶斯估计

贝叶斯估计的基本思想

(1)定义:从概率论的角度,提出的分类方法。通过统计特征在数据集上取某个特定值得次数,然后除以数据集的实例总数,或者特征取该值得概率。在分类中选择高概率对应的类别。

(2)优点:在数据少的情况下,仍然有效,可以处理多类别问题

(3)缺点:对于输入数据的准备方式敏感,使用的数据类型为标称型数据

条件概率

(1)依赖关系:若A依赖B,则在B已知的情况下,求A发生的概率P(A|B)=P(AB)/P(B)

(2)贝叶斯准则:P(B|A)=P(A|B)P(B)/P(A)

贝叶斯估计的实现文档分类的流程

(1)假设:一个特征或者单词出现的可能性与它和其他单词相邻没有关系(特征之间相互独立)

(2)从文本中构建词向量,将每一篇文档进行词汇表向量转换。

(3)从词向量计算每个类别下的不同词条的不同概率值

(4)测试修改初始化参数

贝叶斯估计的程序编写

'''Created on Oct 19, @author: Peter'''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 notreturn postingList,classVecdef createVocabList(dataSet):vocabSet = set([]) #create empty setfor document in dataSet:vocabSet = vocabSet | set(document) #union of the two setsreturn list(vocabSet)def setOfWords2Vec(vocabList, inputSet):returnVec = [0]*len(vocabList)for word in inputSet:if word in vocabList:returnVec[vocabList.index(word)] = 1else: print ("the word: %s is not in my Vocabulary!" % word)return returnVecdef trainNB0(trainMatrix,trainCategory):numTrainDocs = len(trainMatrix)numWords = len(trainMatrix[0])pAbusive = sum(trainCategory)/float(numTrainDocs)p0Num = ones(numWords); p1Num = ones(numWords)#change to ones() p0Denom = 2.0; p1Denom = 2.0 #change to 2.0for i in range(numTrainDocs):if trainCategory[i] == 1:p1Num += trainMatrix[i]p1Denom += sum(trainMatrix[i])else:p0Num += trainMatrix[i]p0Denom += sum(trainMatrix[i])p1Vect = log(p1Num/p1Denom)#change to log()p0Vect = log(p0Num/p0Denom)#change to log()return p0Vect,p1Vect,pAbusivedef classifyNB(vec2Classify, p0Vec, p1Vec, pClass1):p1 = sum(vec2Classify * p1Vec) + log(pClass1) #element-wise multp0 = sum(vec2Classify * p0Vec) + log(1.0 - pClass1)if p1 > p0:return 1else: return 0def bagOfWords2VecMN(vocabList, inputSet):returnVec = [0]*len(vocabList)for word in inputSet:if word in vocabList:returnVec[vocabList.index(word)] += 1return returnVecdef testingNB():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)def textParse(bigString): #input is big string, #output is word listimport relistOfTokens = re.split(r'\W*', bigString)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())docList.append(wordList)fullText.extend(wordList)classList.append(1)wordList = textParse(open('email/ham/%d.txt' % i).read())docList.append(wordList)fullText.extend(wordList)classList.append(0)vocabList = createVocabList(docList)#create vocabularytrainingSet = range(50); testSet=[] #create test setfor i in range(10):randIndex = int(random.uniform(0,len(trainingSet)))testSet.append(trainingSet[randIndex])del(trainingSet[randIndex]) trainMat=[]; trainClasses = []for docIndex in trainingSet:#train the classifier (get probs) trainNB0trainMat.append(bagOfWords2VecMN(vocabList, docList[docIndex]))trainClasses.append(classList[docIndex])p0V,p1V,pSpam = trainNB0(array(trainMat),array(trainClasses))errorCount = 0for docIndex in testSet: #classify the remaining itemswordVector = bagOfWords2VecMN(vocabList, docList[docIndex])if classifyNB(array(wordVector),p0V,p1V,pSpam) != classList[docIndex]:errorCount += 1print "classification error",docList[docIndex]print 'the error rate is: ',float(errorCount)/len(testSet)#return vocabList,fullTextdef calcMostFreq(vocabList,fullText):import operatorfreqDict = {}for token in vocabList:freqDict[token]=fullText.count(token)sortedFreq = sorted(freqDict.iteritems(), key=operator.itemgetter(1), reverse=True) return sortedFreq[:30] def localWords(feed1,feed0):import feedparserdocList=[]; classList = []; fullText =[]minLen = min(len(feed1['entries']),len(feed0['entries']))for i in range(minLen):wordList = textParse(feed1['entries'][i]['summary'])docList.append(wordList)fullText.extend(wordList)classList.append(1) #NY is class 1wordList = textParse(feed0['entries'][i]['summary'])docList.append(wordList)fullText.extend(wordList)classList.append(0)vocabList = createVocabList(docList)#create vocabularytop30Words = calcMostFreq(vocabList,fullText) #remove top 30 wordsfor pairW in top30Words:if pairW[0] in vocabList: vocabList.remove(pairW[0])trainingSet = range(2*minLen); testSet=[] #create test setfor i in range(20):randIndex = int(random.uniform(0,len(trainingSet)))testSet.append(trainingSet[randIndex])del(trainingSet[randIndex]) trainMat=[]; trainClasses = []for docIndex in trainingSet:#train the classifier (get probs) trainNB0trainMat.append(bagOfWords2VecMN(vocabList, docList[docIndex]))trainClasses.append(classList[docIndex])p0V,p1V,pSpam = trainNB0(array(trainMat),array(trainClasses))errorCount = 0for docIndex in testSet: #classify the remaining itemswordVector = bagOfWords2VecMN(vocabList, docList[docIndex])if classifyNB(array(wordVector),p0V,p1V,pSpam) != classList[docIndex]:errorCount += 1print ('the error rate is: ',float(errorCount)/len(testSet))return vocabList,p0V,p1Vdef getTopWords(ny,sf):import operatorvocabList,p0V,p1V=localWords(ny,sf)topNY=[]; topSF=[]for i in range(len(p0V)):if p0V[i] > -6.0 : topSF.append((vocabList[i],p0V[i]))if p1V[i] > -6.0 : topNY.append((vocabList[i],p1V[i]))sortedSF = sorted(topSF, key=lambda pair: pair[1], reverse=True)print ("SF**SF**SF**SF**SF**SF**SF**SF**SF**SF**SF**SF**SF**SF**SF**SF**")for item in sortedSF:print item[0]sortedNY = sorted(topNY, key=lambda pair: pair[1], reverse=True)print ("NY**NY**NY**NY**NY**NY**NY**NY**NY**NY**NY**NY**NY**NY**NY**NY**")for item in sortedNY:print item[0]

贝叶斯估计的应用

1.使用朴素贝叶斯进行电子邮件过滤

2.使用朴素贝叶斯分类器从个人广告中获取区域倾向

比较

与kNN和决策树相比,贝叶斯估计能够通过较少的数据进行分类,同时可以有效处理多分类的问题

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。