朴素贝叶斯方法的应用实例----基于newsgroup文档集的贝叶斯算法实现

来源:互联网 发布:美联储 8月cpi数据 编辑:程序博客网 时间:2024/05/22 05:15

转载自:http://blog.csdn.net/v_july_v/article/details/7577684

朴素贝叶斯:就是假定数据是独立的贝叶斯模型


基于newsgroup文档集的贝叶斯算法实现

2.7.1、newsgroup文档集介绍与预处理
    Newsgroups最早由Lang于1995收集并在[Lang 1995]中使用。它含有20000篇左右的Usenet文档,几乎平均分配20个不同的新闻组。除了其中4.5%的文档属于两个或两个以上的新闻组以外,其余文档仅属于一个新闻组,因此它通常被作为单标注分类问题来处理。Newsgroups已经成为文本分类聚类中常用的文档集。美国MIT大学Jason Rennie对Newsgroups作了必要的处理,使得每个文档只属于一个新闻组,形成Newsgroups-18828。 

 (:本2.7节内容主要援引自参考文献条目8的内容,有任何不妥之处,还望原作者及众读者海涵,谢谢)

    要做文本分类首先得完成文本的预处理,预处理的主要步骤如下:

  1. 英文词法分析,去除数字、连字符、标点符号、特殊 字符,所有大写字母转换成小写,可以用正则表达式:String res[] = line.split("[^a-zA-Z]");
  2. 去停用词,过滤对分类无价值的词;
  3. 词根还原stemming,基于Porter算法
  1. private static String lineProcess(String line, ArrayList<String> stopWordsArray) throws IOException {    
  2.     // TODO Auto-generated method stub    
  3.     //step1 英文词法分析,去除数字、连字符、标点符号、特殊字符,所有大写字母转换成小写,可以考虑用正则表达式    
  4.     String res[] = line.split("[^a-zA-Z]");    
  5.     //这里要小心,防止把有单词中间有数字和连字符的单词 截断了,但是截断也没事    
  6.         
  7.     String resString = new String();    
  8.     //step2去停用词    
  9.     //step3stemming,返回后一起做    
  10.     for(int i = 0; i < res.length; i++){    
  11.         if(!res[i].isEmpty() && !stopWordsArray.contains(res[i].toLowerCase())){    
  12.             resString += " " + res[i].toLowerCase() + " ";    
  13.         }    
  14.     }    
  15.     return resString;    
  16. }   
2.7.2、特征词的选取
    首先统计经过预处理后在所有文档中出现不重复的单词一共有87554个,对这些词进行统计发现:
出现次数大于等于1次的词有87554个
出现次数大于等于3次的词有36456个 
出现次数大于等于4次的词有30095个
    特征词的选取策略:
策略一:保留所有词作为特征词 共计87554个
策略二:选取出现次数大于等于4次的词作为特征词共计30095个 
    特征词的选取策略:采用策略一,后面将对两种特征词选取策略的计算时间和平均准确率做对比
2.7.3、贝叶斯算法描述及实现

    根据朴素贝叶斯公式,每个测试样例属于某个类别的概率 =  所有测试样例包含特征词类条件概率P(tk|c)之积 * 先验概率P(c)
在具体计算类条件概率和先验概率时,朴素贝叶斯分类器有两种模型:
    (1) 多项式模型( multinomial model )  –以单词为粒度
类条件概率P(tk|c)=(类c下单词tk在各个文档中出现过的次数之和+1)/(类c下单词总数+训练样本中不重复特征词总数)
先验概率P(c)=类c下的单词总数/整个训练样本的单词总数
    (2) 伯努利模型(Bernoulli model)   –以文件为粒度
类条件概率P(tk|c)=(类c下包含单词tk的文件数+1)/(类c下文件总数+2)
先验概率P(c)=类c下文件总数/整个训练样本的文件总数
本分类器选用多项式模型计算,根据斯坦福的《Introduction to Information Retrieval 》课件上所说,多项式模型计算准确率更高。
    贝叶斯算法的实现有以下注意点:
  1. 计算概率用到了BigDecimal类实现任意精度计算;
  2. 用交叉验证法做十次分类实验,对准确率取平均值;
  3. 根据正确类目文件和分类结果文计算混淆矩阵并且输出;
  4.  Map<String,Double> cateWordsProb key为“类目_单词”, value为该类目下该单词的出现次数,避免重复计算。
    贝叶斯算法实现类如下NaiveBayesianClassifier.java(author:yangliu

  1. package com.pku.yangliu;  
  2. import java.io.BufferedReader;  
  3. import java.io.File;  
  4. import java.io.FileReader;  
  5. import java.io.FileWriter;  
  6. import java.io.IOException;  
  7. import java.math.BigDecimal;  
  8. import java.util.Iterator;  
  9. import java.util.Map;  
  10. import java.util.Set;  
  11. import java.util.SortedSet;  
  12. import java.util.TreeMap;  
  13. import java.util.TreeSet;  
  14. import java.util.Vector;  
  15.   
  16. /**利用朴素贝叶斯算法对newsgroup文档集做分类,采用十组交叉测试取平均值 
  17.  * 采用多项式模型,stanford信息检索导论课件上面言多项式模型比伯努利模型准确度高 
  18.  * 类条件概率P(tk|c)=(类c 下单词tk 在各个文档中出现过的次数之和+1)/(类c下单词总数+|V|) 
  19.  */  
  20. public class NaiveBayesianClassifier {  
  21.       
  22.     /**用贝叶斯法对测试文档集分类 
  23.      * @param trainDir 训练文档集目录 
  24.      * @param testDir 测试文档集目录 
  25.      * @param classifyResultFileNew 分类结果文件路径 
  26.      * @throws Exception  
  27.      */  
  28.     private void doProcess(String trainDir, String testDir,  
  29.             String classifyResultFileNew) throws Exception {  
  30.         // TODO Auto-generated method stub  
  31.         Map<String,Double> cateWordsNum = new TreeMap<String,Double>();//保存训练集每个类别的总词数  
  32.         Map<String,Double> cateWordsProb = new TreeMap<String,Double>();//保存训练样本每个类别中每个属性词的出现词数  
  33.         cateWordsProb = getCateWordsProb(trainDir);  
  34.         cateWordsNum = getCateWordsNum(trainDir);  
  35.         double totalWordsNum = 0.0;//记录所有训练集的总词数  
  36.         Set<Map.Entry<String,Double>> cateWordsNumSet = cateWordsNum.entrySet();  
  37.         for(Iterator<Map.Entry<String,Double>> it = cateWordsNumSet.iterator(); it.hasNext();){  
  38.             Map.Entry<String, Double> me = it.next();  
  39.             totalWordsNum += me.getValue();  
  40.         }  
  41.         //下面开始读取测试样例做分类  
  42.         Vector<String> testFileWords = new Vector<String>();  
  43.         String word;  
  44.         File[] testDirFiles = new File(testDir).listFiles();  
  45.         FileWriter crWriter = new FileWriter(classifyResultFileNew);  
  46.         for(int i = 0; i < testDirFiles.length; i++){  
  47.             File[] testSample = testDirFiles[i].listFiles();  
  48.             for(int j = 0;j < testSample.length; j++){  
  49.                 testFileWords.clear();  
  50.                 FileReader spReader = new FileReader(testSample[j]);  
  51.                 BufferedReader spBR = new BufferedReader(spReader);  
  52.                 while((word = spBR.readLine()) != null){  
  53.                     testFileWords.add(word);  
  54.                 }  
  55.                 //下面分别计算该测试样例属于二十个类别的概率  
  56.                 File[] trainDirFiles = new File(trainDir).listFiles();  
  57.                 BigDecimal maxP = new BigDecimal(0);  
  58.                 String bestCate = null;  
  59.                 for(int k = 0; k < trainDirFiles.length; k++){  
  60.                     BigDecimal p = computeCateProb(trainDirFiles[k], testFileWords, cateWordsNum, totalWordsNum, cateWordsProb);  
  61.                     if(k == 0){  
  62.                         maxP = p;  
  63.                         bestCate = trainDirFiles[k].getName();  
  64.                         continue;  
  65.                     }  
  66.                     if(p.compareTo(maxP) == 1){  
  67.                         maxP = p;  
  68.                         bestCate = trainDirFiles[k].getName();  
  69.                     }  
  70.                 }  
  71.                 crWriter.append(testSample[j].getName() + " " + bestCate + "\n");  
  72.                 crWriter.flush();  
  73.             }  
  74.         }  
  75.         crWriter.close();  
  76.     }  
  77.       
  78.     /**统计某类训练样本中每个单词的出现次数 
  79.      * @param strDir 训练样本集目录 
  80.      * @return Map<String,Double> cateWordsProb 用"类目_单词"对来索引的map,保存的val就是该类目下该单词的出现次数 
  81.      * @throws IOException  
  82.      */  
  83.     public Map<String,Double> getCateWordsProb(String strDir) throws IOException{  
  84.         Map<String,Double> cateWordsProb = new TreeMap<String,Double>();  
  85.         File sampleFile = new File(strDir);  
  86.         File [] sampleDir = sampleFile.listFiles();  
  87.         String word;  
  88.         for(int i = 0;i < sampleDir.length; i++){  
  89.             File [] sample = sampleDir[i].listFiles();  
  90.             for(int j = 0; j < sample.length; j++){  
  91.                 FileReader samReader = new FileReader(sample[j]);  
  92.                 BufferedReader samBR = new BufferedReader(samReader);  
  93.                 while((word = samBR.readLine()) != null){  
  94.                     String key = sampleDir[i].getName() + "_" + word;  
  95.                     if(cateWordsProb.containsKey(key)){  
  96.                         double count = cateWordsProb.get(key) + 1.0;  
  97.                         cateWordsProb.put(key, count);  
  98.                     }  
  99.                     else {  
  100.                         cateWordsProb.put(key, 1.0);  
  101.                     }  
  102.                 }  
  103.             }  
  104.         }  
  105.         return cateWordsProb;     
  106.     }  
  107.       
  108.     /**计算某一个测试样本属于某个类别的概率 
  109.      * @param Map<String, Double> cateWordsProb 记录每个目录中出现的单词及次数  
  110.      * @param File trainFile 该类别所有的训练样本所在目录 
  111.      * @param Vector<String> testFileWords 该测试样本中的所有词构成的容器 
  112.      * @param double totalWordsNum 记录所有训练样本的单词总数 
  113.      * @param Map<String, Double> cateWordsNum 记录每个类别的单词总数 
  114.      * @return BigDecimal 返回该测试样本在该类别中的概率 
  115.      * @throws Exception  
  116.      * @throws IOException  
  117.      */  
  118.     private BigDecimal computeCateProb(File trainFile, Vector<String> testFileWords, Map<String, Double> cateWordsNum, double totalWordsNum, Map<String, Double> cateWordsProb) throws Exception {  
  119.         // TODO Auto-generated method stub  
  120.         BigDecimal probability = new BigDecimal(1);  
  121.         double wordNumInCate = cateWordsNum.get(trainFile.getName());  
  122.         BigDecimal wordNumInCateBD = new BigDecimal(wordNumInCate);  
  123.         BigDecimal totalWordsNumBD = new BigDecimal(totalWordsNum);  
  124.         for(Iterator<String> it = testFileWords.iterator(); it.hasNext();){  
  125.             String me = it.next();  
  126.             String key = trainFile.getName()+"_"+me;  
  127.             double testFileWordNumInCate;  
  128.             if(cateWordsProb.containsKey(key)){  
  129.                 testFileWordNumInCate = cateWordsProb.get(key);  
  130.             }else testFileWordNumInCate = 0.0;  
  131.             BigDecimal testFileWordNumInCateBD = new BigDecimal(testFileWordNumInCate);  
  132.             BigDecimal xcProb = (testFileWordNumInCateBD.add(new BigDecimal(0.0001))).divide(totalWordsNumBD.add(wordNumInCateBD),10, BigDecimal.ROUND_CEILING);  
  133.             probability = probability.multiply(xcProb);  
  134.         }  
  135.         BigDecimal res = probability.multiply(wordNumInCateBD.divide(totalWordsNumBD,10, BigDecimal.ROUND_CEILING));  
  136.         return res;  
  137.     }  
  138.   
  139.     /**获得每个类目下的单词总数 
  140.      * @param trainDir 训练文档集目录 
  141.      * @return Map<String, Double> <目录名,单词总数>的map 
  142.      * @throws IOException  
  143.      */  
  144.     private Map<String, Double> getCateWordsNum(String trainDir) throws IOException {  
  145.         // TODO Auto-generated method stub  
  146.         Map<String,Double> cateWordsNum = new TreeMap<String,Double>();  
  147.         File[] sampleDir = new File(trainDir).listFiles();  
  148.         for(int i = 0; i < sampleDir.length; i++){  
  149.             double count = 0;  
  150.             File[] sample = sampleDir[i].listFiles();  
  151.             for(int j = 0;j < sample.length; j++){  
  152.                 FileReader spReader = new FileReader(sample[j]);  
  153.                 BufferedReader spBR = new BufferedReader(spReader);  
  154.                 while(spBR.readLine() != null){  
  155.                     count++;  
  156.                 }         
  157.             }  
  158.             cateWordsNum.put(sampleDir[i].getName(), count);  
  159.         }  
  160.         return cateWordsNum;  
  161.     }  
  162.       
  163.     /**根据正确类目文件和分类结果文件统计出准确率 
  164.      * @param classifyResultFile 正确类目文件 
  165.      * @param classifyResultFileNew 分类结果文件 
  166.      * @return double 分类的准确率 
  167.      * @throws IOException  
  168.      */  
  169.     double computeAccuracy(String classifyResultFile,  
  170.             String classifyResultFileNew) throws IOException {  
  171.         // TODO Auto-generated method stub  
  172.         Map<String,String> rightCate = new TreeMap<String,String>();  
  173.         Map<String,String> resultCate = new TreeMap<String,String>();  
  174.         rightCate = getMapFromResultFile(classifyResultFile);  
  175.         resultCate = getMapFromResultFile(classifyResultFileNew);  
  176.         Set<Map.Entry<String, String>> resCateSet = resultCate.entrySet();  
  177.         double rightCount = 0.0;  
  178.         for(Iterator<Map.Entry<String, String>> it = resCateSet.iterator(); it.hasNext();){  
  179.             Map.Entry<String, String> me = it.next();  
  180.             if(me.getValue().equals(rightCate.get(me.getKey()))){  
  181.                 rightCount ++;  
  182.             }  
  183.         }  
  184.         computerConfusionMatrix(rightCate,resultCate);  
  185.         return rightCount / resultCate.size();    
  186.     }  
  187.       
  188.     /**根据正确类目文件和分类结果文计算混淆矩阵并且输出 
  189.      * @param rightCate 正确类目对应map 
  190.      * @param resultCate 分类结果对应map 
  191.      * @return double 分类的准确率 
  192.      * @throws IOException  
  193.      */  
  194.     private void computerConfusionMatrix(Map<String, String> rightCate,  
  195.             Map<String, String> resultCate) {  
  196.         // TODO Auto-generated method stub    
  197.         int[][] confusionMatrix = new int[20][20];  
  198.         //首先求出类目对应的数组索引  
  199.         SortedSet<String> cateNames = new TreeSet<String>();  
  200.         Set<Map.Entry<String, String>> rightCateSet = rightCate.entrySet();  
  201.         for(Iterator<Map.Entry<String, String>> it = rightCateSet.iterator(); it.hasNext();){  
  202.             Map.Entry<String, String> me = it.next();  
  203.             cateNames.add(me.getValue());  
  204.         }  
  205.         cateNames.add("rec.sport.baseball");//防止数少一个类目  
  206.         String[] cateNamesArray = cateNames.toArray(new String[0]);  
  207.         Map<String,Integer> cateNamesToIndex = new TreeMap<String,Integer>();  
  208.         for(int i = 0; i < cateNamesArray.length; i++){  
  209.             cateNamesToIndex.put(cateNamesArray[i],i);  
  210.         }  
  211.         for(Iterator<Map.Entry<String, String>> it = rightCateSet.iterator(); it.hasNext();){  
  212.             Map.Entry<String, String> me = it.next();  
  213.             confusionMatrix[cateNamesToIndex.get(me.getValue())][cateNamesToIndex.get(resultCate.get(me.getKey()))]++;  
  214.         }  
  215.         //输出混淆矩阵  
  216.         double[] hangSum = new double[20];  
  217.         System.out.print("    ");  
  218.         for(int i = 0; i < 20; i++){  
  219.             System.out.print(i + "    ");  
  220.         }  
  221.         System.out.println();  
  222.         for(int i = 0; i < 20; i++){  
  223.             System.out.print(i + "    ");  
  224.             for(int j = 0; j < 20; j++){  
  225.                 System.out.print(confusionMatrix[i][j]+"    ");  
  226.                 hangSum[i] += confusionMatrix[i][j];  
  227.             }  
  228.             System.out.println(confusionMatrix[i][i] / hangSum[i]);  
  229.         }  
  230.         System.out.println();  
  231.     }  
  232.   
  233.     /**从分类结果文件中读取map 
  234.      * @param classifyResultFileNew 类目文件 
  235.      * @return Map<String, String> 由<文件名,类目名>保存的map 
  236.      * @throws IOException  
  237.      */  
  238.     private Map<String, String> getMapFromResultFile(  
  239.             String classifyResultFileNew) throws IOException {  
  240.         // TODO Auto-generated method stub  
  241.         File crFile = new File(classifyResultFileNew);  
  242.         FileReader crReader = new FileReader(crFile);  
  243.         BufferedReader crBR = new BufferedReader(crReader);  
  244.         Map<String, String> res = new TreeMap<String, String>();  
  245.         String[] s;  
  246.         String line;  
  247.         while((line = crBR.readLine()) != null){  
  248.             s = line.split(" ");  
  249.             res.put(s[0], s[1]);      
  250.         }  
  251.         return res;  
  252.     }  
  253.   
  254.     /** 
  255.      * @param args 
  256.      * @throws Exception  
  257.      */  
  258.     public void NaiveBayesianClassifierMain(String[] args) throws Exception {  
  259.          //TODO Auto-generated method stub  
  260.         //首先创建训练集和测试集  
  261.         CreateTrainAndTestSample ctt = new CreateTrainAndTestSample();  
  262.         NaiveBayesianClassifier nbClassifier = new NaiveBayesianClassifier();  
  263.         ctt.filterSpecialWords();//根据包含非特征词的文档集生成只包含特征词的文档集到processedSampleOnlySpecial目录下  
  264.         double[] accuracyOfEveryExp = new double[10];  
  265.         double accuracyAvg,sum = 0;  
  266.         for(int i = 0; i < 10; i++){//用交叉验证法做十次分类实验,对准确率取平均值   
  267.             String TrainDir = "F:/DataMiningSample/TrainSample"+i;  
  268.             String TestDir = "F:/DataMiningSample/TestSample"+i;  
  269.             String classifyRightCate = "F:/DataMiningSample/classifyRightCate"+i+".txt";  
  270.             String classifyResultFileNew = "F:/DataMiningSample/classifyResultNew"+i+".txt";  
  271.             ctt.createTestSamples("F:/DataMiningSample/processedSampleOnlySpecial"0.9, i,classifyRightCate);  
  272.             nbClassifier.doProcess(TrainDir,TestDir,classifyResultFileNew);  
  273.             accuracyOfEveryExp[i] = nbClassifier.computeAccuracy (classifyRightCate, classifyResultFileNew);  
  274.             System.out.println("The accuracy for Naive Bayesian Classifier in "+i+"th Exp is :" + accuracyOfEveryExp[i]);  
  275.         }  
  276.         for(int i = 0; i < 10; i++){  
  277.             sum += accuracyOfEveryExp[i];  
  278.         }  
  279.         accuracyAvg = sum / 10;  
  280.         System.out.println("The average accuracy for Naive Bayesian Classifier in all Exps is :" + accuracyAvg);  
  281.           
  282.     }  
  283. }  

2.7.4、朴素贝叶斯算法对newsgroup文档集做分类的结果
    在经过一系列Newsgroup文档预处理、特征词的选取、及实现了贝叶斯算法之后,下面用朴素贝叶斯算法那对newsgroup文档集做分类,看看此贝叶斯算法的效果。
    贝叶斯算法分类结果-混淆矩阵表示,以交叉验证的第6次实验结果为例,分类准确率最高达到80.47%。

    程序运行硬件环境:Intel Core 2 Duo CPU T5750 2GHZ, 2G内存,实验结果如下:
    取所有词共87554个作为特征词:10次交叉验证实验平均准确率78.19%,用时23min,准确率范围75.65%-80.47%,第6次实验准确率超过80%,取出现次数大于等于4次的词共计30095个作为特征词: 10次交叉验证实验平均准确率77.91%,用时22min,准确率范围75.51%-80.26%,第6次实验准确率超过80%。如下图所示:

     结论:朴素贝叶斯算法不必去除出现次数很低的词,因为出现次数很低的词的IDF比较   大,去除后分类准确率下降,而计算时间并没有显著减少
2.7.5、贝叶斯算法的改进
    为了进一步提高贝叶斯算法的分类准确率,可以考虑
  1. 优化特征词的选取策略;
  2. 改进多项式模型的类条件概率的计算公式,改进为 类条件概率P(tk|c)=(类c下单词tk在各个文档中出现过的次数之和+0.001)/(类c下单词总数+训练样本中不重复特征词总数),分子当tk没有出现时,只加0.001(之前上面2.7.3节是+1),这样更加精确的描述的词的统计分布规律,
    做此改进后的混淆矩阵如下

    可以看到第6次分组实验的准确率提高到84.79%,第7词分组实验的准确率达到85.24%,平均准确率由77.91%提高到了82.23%,优化效果还是很明显的。更多内容,请参考原文:参考文献条目8。谢谢。

0 0