【Machine Learning】 朴素贝叶斯

1. 朴素贝叶斯: 条件概率在机器学习算法的应用。理解这个算法需要一点推导。不会编辑公式。。

核心就是 在已知训练集的前提条件下,算出每个特征的概率为该分类的概率, 然后套贝叶斯公式计算 预测集的所有分类概率,预测类型为概率最大的类型

from numpy import *


def loadDataSet():
    """
    Returns:
        postingList: list, 用于测试的静态数据
        classVec: list, 标签,与 postingList 对应, 1 代表侮辱性文字, 0 代表正常言论
    """
    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 代表侮辱性文字, 0 代表正常言论
    return postingList, classVec



def createVocabList(dataSet):
    """
    对数据进行去重

    Args:
        dataSet: list, 原始数据

    Returns: list 去重后的一维list

    """
    vocabSet = set([])
    for document in dataSet:
        vocabSet = vocabSet | set(document)
    return list(vocabSet)


def setOfWords2Vec(vocabList, inputSet):
    """
    对数据使用情况进行标记

    Args:
        vocabList: list 参考数据
        inputSet: 测试数据

    Returns:  list 对应 vocabList, 1 代表在 inputSet 中存在, 0 代表不存在

    """
    returnVec = [0] * len(vocabList)
    for word in inputSet:
        if word in inputSet:
            returnVec[vocabList.index(word)] = 1
        else:
            print("the word: %s is not my Vocabulary!" % word)
    return returnVec


def trainNB0(trainMatrix, trainCategory):
    """
    Args:
        trainMatrix: 测试数据
        trainCategory:  数据标签

    Returns:
        p0Vect: list[list] 在已知正常文档的概率是 0.4的前提下,
        每个单词的为正常单词的概率)
        p1Vect: list[list] (在已知侮辱性文档的概率是 0.6的前提下,
        每个单词的为侮辱性单词的概率)
        pAbusive: float  条件概率中的条件 以 createDataSet 方法中的数据为例,
        侮辱性文档的概率是 0.6, 正常文档的概率是0.4

    """
    numTrainDocs = len(trainMatrix)
    numWords = len(trainMatrix[0])
    pAbusive = sum(trainCategory) / float(numTrainDocs)
    p0Num = zeros(numWords)
    p1Num = zeros(numWords)
    p0Denom = 0.0
    p1Denom = 0.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 = p1Num / p1Denom
    p0Vect = p0Num / p0Denom
    return p0Vect, p1Vect, pAbusive


def classifyNB(vec2Classify, p0Vec, p1Vec, pClass1):
    """
    Args:
        vec2Classify: list[int] 词汇表使用标记
        p0Vec: list[list] 单个词汇为正常词汇的概率
        p1Vec: list[list] 单个词汇为侮辱性词汇的概率
        pClass1: float 文档为侮辱性文档的概率

    Returns: 1: 侮辱性文档
             2: 正常文档

    """
    p1 = sum(vec2Classify * p1Vec) + log(pClass1)    # 使用log避免 0乘以任何数为0 的尴尬
    p0 = sum(vec2Classify * p0Vec) + log(1.0 - pClass1)
    if p1 > p0:
        return 1
    else:
        return 0

def testingNB():
    listOPosts, listClasses = loadDataSet()
    myVocabList = createVocabList(listOPosts)
    trainMat = []
    for postinDoc in listOPosts:
        trainMat.append(setOfWords2Vec(myVocabList, postinDoc))
    p0V, p1V, pAb = trainNB0(trainMat, 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))


if __name__ == '__main__':
    testingNB()

 

posted @ 2018-11-27 19:21  早起的虫儿去吃鸟  阅读(207)  评论(0编辑  收藏  举报