MLA Review之三:朴素贝叶斯分类

朴素贝叶斯(Naive Bayes),贝叶斯概率论在整个统计学习上都是泰山北斗一样的存在,《Pattern Recognization and Machine Learning》这一扛鼎之作全书的思想其实就是贝叶斯概率论,简单的说就是先验代替后验。

 

我们先来给朴素贝叶斯找一点理论支持

 

贝叶斯概率公式:P(A|B)=P(A)*p(B|A)/P(B) ,而根据要求,我们需要做的是得出P(C1|X,Y)和P(C2|X,Y)的概率,其中P(C1|X,Y)的意思是根据特征值X,Y得到是C1的概率,后面是得到C2的概率,因此,我们只需要比较这两者的大小就知道结果是归为哪一类了,但是问题是这个根本不好计算,这时候贝叶斯准则就可以派上用场了:

P(C1|X,Y)=P(C1)*P(X,Y|C1)/P(X,Y)

其中P(X,Y)是可以忽略的,因此P(C1|X,Y)约等于P(C1)*P(X,Y|C1),这个时候我们可以用经验概率来计算P(C1),但是计算P(X,Y|C1)仍然有难度,为了简单起见,朴素贝叶斯假设X,Y是独立的,所谓朴素也就指的是这个独立假设,也就是P(X,Y|C1)=P(X|C1)*P(Y|C1),这样就很容易计算该值了,可以得到:

P(C1|X,Y)=P(C1)*P(X|C1)*P(Y|C1),这样就容易计算了。

 

背景粗略交代完毕,现在回到具体问题:

 

邮件分类器:邮件分类垃圾邮件个正常邮件,根据已有的邮件训练样本,训练出邮件分类模型。

数据说明25封垃圾邮件,25封正常邮件,在这50封邮件里面随机选取10篇作为测试数据,剩下40篇作为训练数据

       算法说明

  • 根据所给的训练邮件,得到所有的不重复单词数组,记为wordlist
  • 将训练数据和测试数据按照wordlist的顺序转换成词向量
  • 根据词向量使用NaiveBayes训练模型
  • 使用测试数据集测试结果

     下面是具体代码:

 

Python代码   收藏代码
  1. # -*- coding: UTF8 -*-  
  2. """ 
  3. author:luchi 
  4. date:16/2/18 
  5. desc: 
  6. 朴素贝叶斯做邮件分类 
  7. """  
  8.   
  9. """ 
  10. 获取训练与测试文本,构建训练集与测试集 
  11. """  
  12. import re  
  13. import random  
  14. from numpy import *  
  15.   
  16.   
  17. def splitWords(str):  
  18.     listTokens=re.split(r'\W*',str)  
  19.     return [token.lower() for token in listTokens  if len(token)>2 ]  
  20.   
  21. def initDataset():  
  22.   
  23.     wordList=[]  
  24.     docList=[]  
  25.     labels=[]  
  26.     for i in range(1,26):  
  27.         fr=open('email/spam/%d.txt' % i)  
  28.         frStr=fr.read()  
  29.         l=splitWords(frStr)  
  30.         docList.append(l)  
  31.         labels.append(0)  
  32.         wordList.extend(l)  
  33.         fr=open('email/ham/%d.txt' % i)  
  34.         frStr=fr.read()  
  35.         l=splitWords(frStr)  
  36.         docList.append(l)  
  37.         labels.append(1)  
  38.         wordList.extend(l)  
  39.     # print wordList  
  40.     # print docList  
  41.     #随机选出10个组作为测试  
  42.     length=len(docList)  
  43.     testList=[]  
  44.     testLabels=[]  
  45.     for i in range(10):  
  46.         randIndex=int(random.uniform(0,len(docList)))  
  47.         testList.append(docList[randIndex])  
  48.         testLabels.append(labels[randIndex])  
  49.         del(docList[randIndex])  
  50.         del(labels[randIndex])  
  51.     return wordList,docList,labels,testList,testLabels,length  
  52.   
  53. """ 
  54.  
  55. 创建训练和测试向量 
  56.  
  57. """  
  58.   
  59. def getVecDataset(wordList,trainList,testList):  
  60.     wordList=set(wordList)  
  61.     wordvec=[token for token in wordList]  
  62.     feature_num=len(wordvec)  
  63.     print len(wordvec)  
  64.     trainVec=zeros((len(trainList),feature_num))  
  65.     testVec=zeros((len(testList),feature_num))  
  66.   
  67.     for i,l in enumerate(trainList):  
  68.         for word in l:  
  69.             if word in wordvec:  
  70.                 trainVec[i][wordvec.index(word)]+=1  
  71.     for i,l in enumerate(testList):  
  72.         for word in l:  
  73.             if word in wordvec:  
  74.                 testVec[i][wordvec.index(word)]+=1  
  75.     return  trainVec,testVec  
  76.   
  77.   
  78.   
  79.   
  80. def NaiveBayes(traingList,trainLabel):  
  81.   
  82.     trainMat=array(traingList)  
  83.     labelMat=array(trainLabel)  
  84.     class0=ones(len(trainMat[0]))  
  85.     sumClass0=2.0  
  86.     class1=ones(len(trainMat[0]))  
  87.     sumClass1=2.0  
  88.     m=len(trainMat)  
  89.     pclass0=0  
  90.   
  91.     for i in range(m):  
  92.         if(trainLabel[i]==0):  
  93.             class0+=trainMat[i]  
  94.             sumClass0+=sum(trainMat[i])  
  95.             pclass0+=1  
  96.         elif trainLabel[i]==1:  
  97.             class1+=trainMat[i]  
  98.             sumClass1+=sum(trainMat[i])  
  99.     # print class0  
  100.     # print sumClass0  
  101.     class0=class0/sumClass0  
  102.     class1=class1/sumClass1  
  103.     class0=log(class0)  
  104.     class1=log(class1)  
  105.     return class0,class1,pclass0  
  106.   
  107. def testNaiveBayes(testVec,vec0,vec1,pclass0):  
  108.     p0=sum(testVec*vec0)+log(pclass0)  
  109.     p1=sum(testVec*vec1)+log(1-pclass0)  
  110.     if(p0>p1):  
  111.         return 0  
  112.     else:  
  113.         return 1  
  114.   
  115.   
  116.   
  117. def test():  
  118.     wordList,trainList,trainLabels,testList,testLabels,doc_num=initDataset()  
  119.     trainVec,testVec=getVecDataset(wordList,trainList,testList)  
  120.     class0Vec,class1Vec,pclass0=NaiveBayes(trainVec,trainLabels)  
  121.     m=len(testVec)  
  122.     err=0  
  123.     pclass0=float(pclass0)/len(trainVec)  
  124.     for i in range(m):  
  125.         vec=testVec[i]  
  126.         label=testLabels[i]  
  127.         result=testNaiveBayes(array(vec),class0Vec,class1Vec,pclass0)  
  128.         if result!=label:  
  129.             err+=1  
  130.     print ("error rate is %f" % (float(err)/m))  
  131.   
  132.   
  133. if __name__=="__main__":  
  134.     test()  

 

注意程序中使用的log方法不是math包里的log方法,而是numpy里面的log方法,所以不要引入math包即可

 

测试的结果是:



 

 

 

 

 

可以看到,在5次测试中,只有一次的错误率为10%,其他全是0

 

朴素贝叶斯在使用起来容易,操作简单,却往往在一些问题上有着惊人的高效,这也是其强大的原因,但是朴素贝叶斯并不是对所有问题都适用,其独立假设就已经表示对一些对特征值有着明显先后或者依赖关系的时候,朴素贝叶斯的独立假设是不成立的,所以使用朴素贝叶斯还是实现需要看下具体的问题

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