Python3机器学习之04基于概率论的分类方法朴素贝叶斯

贝叶斯核心

选择具有最高概率的决策是贝叶斯决策理论的核心。

贝叶斯使用

通过已知3个概率来计算位置的概率

特征数量与样本关系

通常如果有t个特征,每个特征需要N个样本,那么就需要个总样本数。
如果特征之间独立,那么样本数从降到N x t

朴素贝叶斯的假设

  • 1、 特征之间相互独立
  • 2、 每个特征同等重要

代码

import numpy as np

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']]
    # 类别标签向量,1代表侮辱性词汇,0代表不是
    classVec = [0, 1, 0, 1, 0, 1]
    # 返回实验样本切分的词条、类别标签向量
    return postingList, classVec

def createVocabList(dataSet):
    # 创建一个空的不重复列表
    # set是一个无序且不重复的元素集合
    vocabSet = set([])
    for document in dataSet:
        # 取并集
        vocabSet = vocabSet | set(document)
    return list(vocabSet)


def setOfWords2Vec(vocabList, inputSet):
    # 创建一个其中所含元素都为0的向量
    returnVec = [0] * len(vocabList)
    # 遍历每个词条
    for word in inputSet:
        if word in vocabList:
            # 如果词条存在于词汇表中,则置1
            # index返回word出现在vocabList中的索引
            # 若这里改为+=则就是基于词袋的模型,遇到一个单词会增加单词向量中德对应值
            returnVec[vocabList.index(word)] = 1
        else:
            print("the word: %s is not in my Vocabulary" % word)
    # 返回文档向量
    return returnVec

listOposts,listClasses = loadDataSet()
listOposts
[['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']]
myVocabList = createVocabList(listOposts)
myVocabList
setOfWords2Vec(myVocabList,listOposts[0])
def trainNB0(trainMatrix, trainCategory):
    # 计算训练文档数目
    numTrainDocs = len(trainMatrix)
    # 计算每篇文档的词条数目
    numWords = len(trainMatrix[0])
    # 文档属于侮辱类的概率
    pAbusive = sum(trainCategory)/float(numTrainDocs)
    # 创建numpy.zeros数组,词条出现数初始化为0
    # p0Num = np.zeros(numWords)
    # p1Num = np.zeros(numWords)
    # 创建numpy.ones数组,词条出现数初始化为1,拉普拉斯平滑
    p0Num = np.ones(numWords)
    p1Num = np.ones(numWords)
    # 分母初始化为0
    # p0Denom = 0.0
    # p1Denom = 0.0
    # 分母初始化为2,拉普拉斯平滑
    p0Denom = 2.0
    p1Denom = 2.0
    for i in range(numTrainDocs):
        # 统计属于侮辱类的条件概率所需的数据,即P(w0|1),P(w1|1),P(w2|1)...
        if trainCategory[i] == 1:
            # 统计所有侮辱类文档中每个单词出现的个数
            p1Num += trainMatrix[i]
            # 统计一共出现的侮辱单词的个数
            p1Denom += sum(trainMatrix[i])
        # 统计属于非侮辱类的条件概率所需的数据,即P(w0|0),P(w1|0),P(w2|0)...
        else:
            # 统计所有非侮辱类文档中每个单词出现的个数
            p0Num += trainMatrix[i]
            # 统计一共出现的非侮辱单词的个数
            p0Denom += sum(trainMatrix[i])
    # 每个侮辱类单词分别出现的概率
    # p1Vect = p1Num / p1Denom
    # 取对数,防止下溢出
    p1Vect = np.log(p1Num / p1Denom)
    # 每个非侮辱类单词分别出现的概率
    # p0Vect = p0Num / p0Denom
    # 取对数,防止下溢出
    p0Vect = np.log(p0Num / p0Denom)
    # 返回属于侮辱类的条件概率数组、属于非侮辱类的条件概率数组、文档属于侮辱类的概率
    return p0Vect, p1Vect, pAbusive
                

trainMat = []
for postinDoc in listOposts:
    trainMat.append(setOfWords2Vec(myVocabList,postinDoc))
    
    
p0V,p1V,pAb = trainNB0(trainMat,listClasses)
pAb

0.5
p0V
array([-2.56494936, -2.56494936, -1.87180218, -3.25809654, -3.25809654,
       -2.15948425, -2.56494936, -2.56494936, -2.56494936, -3.25809654,
       -2.56494936, -3.25809654, -2.56494936, -2.56494936, -2.56494936,
       -3.25809654, -3.25809654, -2.56494936, -2.56494936, -3.25809654,
       -2.56494936, -3.25809654, -2.56494936, -2.56494936, -3.25809654,
       -2.56494936, -2.56494936, -3.25809654, -3.25809654, -2.56494936,
       -2.56494936, -2.56494936])
len(p0V)
32
len(myVocabList)
32
p1V
array([-3.04452244, -3.04452244, -3.04452244, -2.35137526, -2.35137526,
       -2.35137526, -3.04452244, -3.04452244, -3.04452244, -2.35137526,
       -3.04452244, -2.35137526, -2.35137526, -3.04452244, -3.04452244,
       -2.35137526, -1.65822808, -3.04452244, -3.04452244, -2.35137526,
       -2.35137526, -2.35137526, -3.04452244, -3.04452244, -2.35137526,
       -3.04452244, -3.04452244, -1.94591015, -2.35137526, -3.04452244,
       -1.94591015, -3.04452244])
def classifyNB(vec2Classify, p0Vec, p1Vec, pClass1):
    # 对应元素相乘
    # p1 = reduce(lambda x,y:x*y, vec2Classify * p1Vec) * pClass1
    # p0 = reduce(lambda x,y:x*y, vec2Classify * p0Vec) * (1.0 - pClass1)
    # 对应元素相乘,logA*B = logA + logB所以这里是累加
    p1 = sum(vec2Classify * p1Vec) + np.log(pClass1)
    p0 = sum(vec2Classify * p0Vec) + np.log(1.0 - pClass1)
    print(p0,p1)
    # print('p0:', p0)
    # print('p1:', p1)
    if p1 > p0:
        return 1
    else:
        return 0

def testingNB():
    # 创建实验样本
    listOPosts, listclasses = loadDataSet()
    # 创建词汇表,将输入文本中的不重复的单词进行提取组成单词向量
    myVocabList = createVocabList(listOPosts)
    trainMat = []
    for postinDoc in listOPosts:
        # 将实验样本向量化若postinDoc中的单词在myVocabList出现则将returnVec该位置的索引置1
        # 将6组数据list存储在trainMat中
        trainMat.append(setOfWords2Vec(myVocabList, postinDoc))
    # 训练朴素贝叶斯分类器
    p0V, p1V, pAb = trainNB0(np.array(trainMat), np.array(listclasses))
    # 测试样本1
    testEntry = ['love', 'my', 'dalmation']
    # 测试样本向量化返回这三个单词出现位置的索引
    thisDoc = np.array(setOfWords2Vec(myVocabList, testEntry))
    if classifyNB(thisDoc, p0V, p1V, pAb):
        # 执行分类并打印结果
        print(testEntry, '属于侮辱类')
    else:
        # 执行分类并打印结果
        print(testEntry, '属于非侮辱类')
    # 测试样本2
    testEntry = ['stupid', 'garbage']
    # 将实验样本向量化
    thisDoc = np.array(setOfWords2Vec(myVocabList, testEntry))
    if classifyNB(thisDoc, p0V, p1V, pAb):
        # 执行分类并打印结果
        print(testEntry, '属于侮辱类')
    else:
        # 执行分类并打印结果
        print(testEntry, '属于非侮辱类')
        
    testEntry = [ 'my','love','dalmation','stupid', 'garbage']
    # 将实验样本向量化
    thisDoc = np.array(setOfWords2Vec(myVocabList, testEntry))
    if classifyNB(thisDoc, p0V, p1V, pAb):
        # 执行分类并打印结果
        print(testEntry, '属于侮辱类')
    else:
        # 执行分类并打印结果
        print(testEntry, '属于非侮辱类')
    
 testingNB()
-7.694848072384611 -9.826714493730215
['love', 'my', 'dalmation'] 属于非侮辱类
-7.20934025660291 -4.702750514326955
['stupid', 'garbage'] 属于侮辱类
-14.211041148427574 -13.836317827497224
['my', 'love', 'dalmation', 'stupid', 'garbage'] 属于侮辱类
    # 创建实验样本
    listOPosts, listclasses = loadDataSet()
    # 创建词汇表,将输入文本中的不重复的单词进行提取组成单词向量
    myVocabList = createVocabList(listOPosts)
    trainMat = []
    for postinDoc in listOPosts:
        # 将实验样本向量化若postinDoc中的单词在myVocabList出现则将returnVec该位置的索引置1
        # 将6组数据list存储在trainMat中
        trainMat.append(setOfWords2Vec(myVocabList, postinDoc))
    # 训练朴素贝叶斯分类器
    p0V, p1V, pAb = trainNB0(np.array(trainMat), np.array(listclasses))
 testEntry = ['love', 'my', 'dalmation']
thisDoc = np.array(setOfWords2Vec(myVocabList, testEntry))
thisDoc
array([0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
       0, 0, 0, 0, 0, 0, 0, 1, 0, 0])
p0V
array([-2.56494936, -2.56494936, -1.87180218, -3.25809654, -3.25809654,
       -2.15948425, -2.56494936, -2.56494936, -2.56494936, -3.25809654,
       -2.56494936, -3.25809654, -2.56494936, -2.56494936, -2.56494936,
       -3.25809654, -3.25809654, -2.56494936, -2.56494936, -3.25809654,
       -2.56494936, -3.25809654, -2.56494936, -2.56494936, -3.25809654,
       -2.56494936, -2.56494936, -3.25809654, -3.25809654, -2.56494936,
       -2.56494936, -2.56494936])
vec2Classify = thisDoc
p0Vec =p0V
p1Vec =p1V
pClass1 =pAb
vec2Classify * p1Vec
array([-0.        , -0.        , -3.04452244, -0.        , -0.        ,
       -0.        , -0.        , -0.        , -0.        , -0.        ,
       -3.04452244, -0.        , -0.        , -0.        , -0.        ,
       -0.        , -0.        , -0.        , -0.        , -0.        ,
       -0.        , -0.        , -0.        , -0.        , -0.        ,
       -0.        , -0.        , -0.        , -0.        , -3.04452244,
       -0.        , -0.        ])
 testingNB()
-7.694848072384611 -9.826714493730215
['love', 'my', 'dalmation'] 属于非侮辱类
-7.20934025660291 -4.702750514326955
['stupid', 'garbage'] 属于侮辱类
-9.774289614064447 -7.747272952050379
['love', 'stupid', 'garbage'] 属于侮辱类

相关资料

英语的统计数字惊人。在世界上所有的语言(目前已达2700种)中,可以说是最丰富的词汇。简明的牛津英语词典列出了大约500,000个单词;另有50万个技术和科学术语尚未列入目录。
根据传统的估计,德语词汇量约为185,000,而法语的词汇量则少于100,000。

  • https://hypertextbook.com/facts/2001/JohnnyLing.shtml

你可能感兴趣的:(Python3机器学习之04基于概率论的分类方法朴素贝叶斯)