1. 实验要求
  2. 实验环境
  3. 实验过程
    1. 加载所有的文档
    2. 对文档分词
    3. 提取文本特征
    4. 根据朴素贝叶斯算法进行分类
    5. 画出学习曲线图
  4. 参考

根据朴素贝叶斯(Naive Bayes)算法1,对以下混在一起十个分类的文档集合进行分类。

实验要求

  1. 采用分词工具,以及停用词列表提取文本特征后,根据朴素贝叶斯算法对以下混在一起十个分类的文档集合进行分类。

  2. 采用10-fold cross validation的实验过程进行分类方法的验证,测试当训练集合分别为100,200,300,500,800个文档的时候,分类结果的准确性,画出学习曲线图(10 Fold Learning Curve)。

实验环境

操作系统:Ubuntu 14.04.3 LTS

开发环境:JDK 1.7

Java库: ansj_seg-2.0.7.jar, nlp-lang-1.0.jar

实验过程

  1. 加载所有的文档

  2. 对文档分词

  3. 提取文本特征

  4. 根据朴素贝叶斯算法进行分类

  5. 画出学习曲线图

加载所有的文档

给定10个文件夹,每个文件夹内有100个文档,共1000个文档。

对文档分词

使用ansj_seg2对文档进行分词。去掉在数词、标点符号和停用词,得到的若干个词。

提取文本特征

使用向量模型(Vector model)3提取文本特征HashMapVector,把每个文档中单词及其出现的次数保存为一个HashMap。

根据朴素贝叶斯算法进行分类

取每个文档及其对应的分类作为样本,把数据集分为\(N\)个fold,其中\(N - 1\)个fold的数据作为训练集,剩下\(1\)个fold的数据作为测试集。测试集的fold取\(N\)个fold中的一个,故能进行\(N\)次训练与测试,把所得的准确率取平均即为最后的平均准确率。

训练与测试使用朴素贝叶斯算法,具体过程如下:

训练过程:

1
2
3
4
5
6
7
8
9
Let V be the vocabulary of all words in the documents in $D$
For each category $c_i \in C$
Let $D_i$ be the subset of documents in $D$ in category $c_i$
$P(c_i) = |D_i| / |D|$
Let $T_i$ be the concatenation of all the documents in $D_i$
Let $n_i$ be the total number of word occurrences in $T_i$
For each word $w_j \in V$
Let $n_{ij}$ be the number of occurrences of $w_j$ in $T_i$
Let $P(w_j | c_i) = (n_{ij} + 1) / (n_i + |V|)$

测试过程:

1
2
3
4
5
Given a test document $X$
Let n be the number of word occurrences in $X$
Return the category:
$\text{argmax}_{c_i \in C} P (c_i) \Pi_{i = 1}^n P (a_i | c_i)$
where $a_i$ is the word occurring the $i$th position in $X$

画出学习曲线图

令训练集合分别为100, 200, 300, 500, 800个文档,使用N-Fold对分类结果的准确率进行交互验证,并把所得的准确率画成折线图。

这里为了方便,直接把训练和测试的平均准确率输出到train.data, test.data文件,使用gnuplotp4进行绘图。此外,也可使用gnuplot生成曲线图相应的latex代码。

在命令行中运行

1
2
gnuplot train.gnuplot
gnuplot test.gnuplot

即可得到train.png和test.png。

参考


  1. Naive Bayes classifier. 维基百科. 最后修订于2016年5月9日. https://en.wikipedia.org/wiki/Naive_Bayes_classifier↩︎

  2. AnsjSeg 使用手册. http://nlpchina.github.io/ansj_seg/↩︎

  3. Vector space model. 维基百科. 最后修订于2016年4月5日. https://en.wikipedia.org/wiki/Vector_space_model↩︎

  4. gnuplot homepage. Thomas Williams, Colin Kelley. 最后修订于2016年4月. http://www.gnuplot.info/↩︎