代码注释:机器学习实战第4章 基于概率论的分类方法:朴素贝叶斯

写在开头的话:在学习《机器学习实战》的过程中发现书中很多代码并没有注释,这对新入门的同学是一个挑战,特此贴出我对代码做出的注释,仅供参考,欢迎指正。

1、进行文本分类

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]  #ddf
    return postingList, classVec

#功能:创建不重复词的列表
#输入:数据集
#输出:不重复词的列表
def createVocabList(dataSet):
    vocabSet = set([])#创建空集合
    for document in dataSet:
        vocabSet = vocabSet | set(document)#或操作表示创建并集
    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)#trainMatrix行数
    numWords = len(trainMatrix[0])#trainMatrix列数
    pAbusive = sum(trainCategory) / float(numTrainDocs)#任意文档属于侮辱性文档的概率
    p0Num = ones(numWords)#拉普拉斯修正
    p1Num = ones(numWords)#拉普拉斯修正
    p0Denom = 2.0#拉普拉斯修正,只有两个标签
    p1Denom = 2.0#拉普拉斯修正,只有两个标签
    for i in range(numTrainDocs):
        if trainCategory[i] == 1:#属于侮辱性文档
            p1Num += trainMatrix[1]#侮辱性文档数量
            p1Denom += sum(trainMatrix[i])
        else:#不属于侮辱性文档
            p0Num += trainMatrix[i]#非侮辱性文档数量
            p0Denom += sum(trainMatrix[i])
    p1Vect = log(p1Num / p1Denom)#防止下溢出,自然对数处理
    p0Vect = log(p0Num / p0Denom)#防止下溢出,自然对数处理
    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 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 bagOfWords2VecMN(vocabList, inputSet):
    returnVec = [0]*len(vocabList)
    for word in inputSet:
        if word in vocabList:
            returnVec[vocabList.index(word)] += 1
    return returnVec

#功能:便利函数
#输入:无
#输出:无
def testingNB():
    label = ['ham', 'spam']#将结果以文本形式呈现
    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: ', label[classifyNB(thisDoc, p0V, p1V, pAb)]
    testEntry = ['stupid', 'garbage']
    thisDoc = array(setOfWords2Vec(myVocabList, testEntry))
    print testEntry, 'classified as: ', label[classifyNB(thisDoc, p0V, p1V, pAb)]


2、过滤垃圾邮件

#功能:切分文本
#输入:需要切分文本
#输出:切分好的文本
def textParse(bigString):
    import re
    listOfTokens = re.split(r'\W*', bigString)#\W表示非单词字符,*表示匹配前一个字符0次或无限次
    #参考链接:http://www.cnblogs.com/huxi/archive/2010/07/04/1771073.html
    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())#打开spam文档,切分文本
        docList.append(wordList)#append向列表尾部添加一个新的元素,将整个wordList添加进去,即文本为基本单位
        fullText.extend(wordList)#extend向列表尾部添加wordList的所有元素,即单词为基本单位
        classList.append(1)#标签表示为spam
        wordList = textParse(open('email/ham/%d.txt' % i).read())  # 打开ham文档,切分文本
        docList.append(wordList)  # append向列表尾部添加一个新的元素,将整个wordList添加进去,即文本为基本单位
        fullText.extend(wordList)  # extend向列表尾部添加wordList的所有元素,即单词为基本单位
        classList.append(0)#标签表示为ham
    vocabList = createVocabList(docList)#创建不重复词的列表
    trainingSet = range(50)
    testSet = []
    for i in range(10):#在trainingSet中随机删除十个数,删除的作为测试集,没有删除的作为训练集
        randIndex = int(random.uniform(0, len(trainingSet)))
        testSet.append(trainingSet[randIndex])
        del(trainingSet[randIndex])
    trainMat = []
    trainClasses = []
    for docIndex in trainingSet:#得测试集和测试标签
        trainMat.append(bagOfWords2VecMN(vocabList, docList[docIndex]))
        trainClasses.append(classList[docIndex])
    p0V, p1V, pSpam = trainNB0(array(trainMat), array(trainClasses))
    errorCount = 0
    for docIndex in testSet:
        wordVector = bagOfWords2VecMN(vocabList, docList[docIndex])
        if classifyNB(array(wordVector), p0V, p1V, pSpam) != classList[docIndex]:#判断测试是否正确
            errorCount += 1
            print "classifiction error", docList[docIndex]
    print 'the error rate is: ', float(errorCount) / len(testSet)


3、RSS应用

#功能:得出现频率最高的30个词
#输入:词汇表,文本
#输出:频率最高的30个词出现的个数和词
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]#返回前30 单词出现个数和词

#功能:rss功能
#输入:
#输出:
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)
        wordList = textParse(feed0['entries'][i]['summary'])
        docList.append(wordList)
        fullText.extend(wordList)
        classList.append(0)
    vocabList = createVocabList(docList)
    top30Words = calcMostFreq(vocabList, fullText)
    for pairW in top30Words:
        if pairW[0] in vocabList:
            vocabList.remove(pairW[0])
    trainingSet = range(2 * minLen)
    testSet = []
    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:
        trainMat.append(bagOfWords2VecMN(vocabList, docList[docIndex]))
        trainClasses.append(classList[docIndex])
    p0V, p1V, pSpam = trainNB0(array(trainMat), array(trainClasses))
    errorCount = 0
    for docIndex in testSet:
        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(nf, sf):
    import operator
    vocabList, p0V, p1V = localWords(nf, 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]


你可能感兴趣的:(机器学习实战)