机器学习之旅---朴素贝叶斯分类器

简介: def loadDataSet(): postingList=[['my', 'dog', 'has', 'flea', 'problems', 'help', 'please'], ['m...



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 = 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.0
    for 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,pAbusive


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

d.     完整的测试流程

def 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 list
    import re
    listOfTokens = re.split(r'\W*', bigString)
    return [tok.lower() for tok in listOfTokens if len(tok) > 2] 



def bagOfWords2VecMN(vocabList, inputSet):
    returnVec = [0]*len(vocabList)
    for word in inputSet:
        if word in vocabList:
            returnVec[vocabList.index(word)] += 1
return returnVec

下面给出垃圾邮件预测的完整代码:

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 vocabulary
    trainingSet = range(50); testSet=[]           #create test set
    for 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) trainNB0
        trainMat.append(bagOfWords2VecMN(vocabList, docList[docIndex]))
        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

执行结果:




def calcMostFreq(vocabList,fullText):
    import operator
    freqDict = {}
    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 feedparser
    docList=[]; 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 1
        wordList = textParse(feed0['entries'][i]['summary'])
        docList.append(wordList)
        fullText.extend(wordList)
        classList.append(0)
    vocabList = createVocabList(docList)#create vocabulary
    top30Words = calcMostFreq(vocabList,fullText)   #remove top 30 words
    for pairW in top30Words:
        if pairW[0] in vocabList: vocabList.remove(pairW[0])
    trainingSet = range(2*minLen); testSet=[]           #create test set
    for 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) trainNB0
        trainMat.append(bagOfWords2VecMN(vocabList, docList[docIndex]))
        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 'the error rate is: ',float(errorCount)/len(testSet)
    return vocabList,p0V,p1V

执行结果:




def getTopWords(ny,sf):
    import operator
    vocabList,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 range(15):
        print sortedSF[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 range(15):
        print sortedNY[item][0]

执行结果:


好久不更新了,华为上班好累,都是回家抽空看的。

python初次接触,很蛋疼。不能有中文注释,运行环境掌握的也不是很好。

大家了解下算法实现原理及应用即可

目录
相关文章
|
5月前
|
机器学习/深度学习 Python
18 机器学习 - 决策树分类器案例
18 机器学习 - 决策树分类器案例
77 0
|
2月前
|
机器学习/深度学习 自然语言处理 JavaScript
GEE机器学习——最大熵分类器案例分析(JavaScript和python代码)
GEE机器学习——最大熵分类器案例分析(JavaScript和python代码)
41 0
|
4月前
|
机器学习/深度学习 算法 Python
【Python机器学习】KNN进行水果分类和分类器实战(附源码和数据集)
【Python机器学习】KNN进行水果分类和分类器实战(附源码和数据集)
281 1
|
5月前
|
机器学习/深度学习 人工智能 算法
机器学习实战:用Python和Scikit-Learn构建分类器
机器学习在当今科技领域发挥着越来越重要的作用,而构建分类器是其中的一项关键任务。本文将带你进入机器学习的世界,通过使用Python编程语言和Scikit-Learn库,实际动手构建一个分类器。我们将探讨机器学习的基本概念、数据准备、模型训练以及评估分类器性能的方法。
|
10月前
|
机器学习/深度学习 资源调度 算法
机器学习之PyTorch和Scikit-Learn第3章 使用Scikit-Learn的机器学习分类器之旅Part 2
另一种强大又广泛使用的学习算法是支持向量机(SVM),可看成是对感知机的扩展。使用感知机算法,我们最小化误分类错误。但在SVM中,我们的优化目标是最大化间隔(margin)。间隔定义为分隔的超平面(决策边界)之间的距离,距离超平面最近的训练样本称为支持向量。
264 0
机器学习之PyTorch和Scikit-Learn第3章 使用Scikit-Learn的机器学习分类器之旅Part 2
|
10月前
|
机器学习/深度学习 数据采集 存储
机器学习之PyTorch和Scikit-Learn第3章 使用Scikit-Learn的机器学习分类器之旅Part 1
本章中,我们会学习一些学术界和工业界常用的知名强大机器学习算法。在学习各种用于分类的监督学习算法的不同时,我们还会欣赏到它们各自的优势和劣势。另外,我们会开始使用scikit-learn库,它为高效、有生产力地使用这些算法提供了用户友好且一致的接口。
104 0
机器学习之PyTorch和Scikit-Learn第3章 使用Scikit-Learn的机器学习分类器之旅Part 1
|
机器学习/深度学习 人工智能 移动开发
【机器学习】线性分类——朴素贝叶斯分类器NBC(理论+图解+公式推导)
【机器学习】线性分类——朴素贝叶斯分类器NBC(理论+图解+公式推导)
112 0
【机器学习】线性分类——朴素贝叶斯分类器NBC(理论+图解+公式推导)
|
机器学习/深度学习 Python
【机器学习】贝叶斯分类器代码实现(python+sklearn)
【机器学习】贝叶斯分类器代码实现(python+sklearn)
216 0
|
机器学习/深度学习 数据采集 资源调度
【机器学习】朴素贝叶斯分类器原理(理论+图解)
【机器学习】朴素贝叶斯分类器原理(理论+图解)
114 0
|
机器学习/深度学习 算法 数据处理
机器学习:基于概率的朴素贝叶斯分类器详解--Python实现以及项目实战
机器学习:基于概率的朴素贝叶斯分类器详解--Python实现以及项目实战
309 0
机器学习:基于概率的朴素贝叶斯分类器详解--Python实现以及项目实战

热门文章

最新文章