二阶和三阶隐马尔柯夫过程(HMM)进行中文分词的效果对比


第一部分 引言

        关于隐马尔柯夫模型的详细内容在此就不详细介绍了,介绍HMM模型的文章很多,请读者自行去学习。二阶隐马尔柯夫模型解决问题有两个假设:其一是当前的状态仅与它前面相邻的状态有关;其二是状态转换和从某个状态发射某个观察符号的概率与时间t无关(即不动性假设)。HMM是在这两个假设的前提下解决各种各样的问题的。

       对于第二个假设,我们不去讨论它。现在来看第一个假设,二阶马尔柯夫过程假设当前状态仅与前面相邻的一个状态有关,那么对于分词来说,有些词可能会满足这样的情况,但也有可能会有些词并不这么简单的处理,他们可能和前面的数个状态有关。基于以上考虑,本文就二阶马尔柯夫过程和三阶马尔柯夫过程对中文分词做了一个实验,验证二者哪个更适合于中文的分词。


第二部分 试验结果

        语料来源:1998年1月《人民日报》

        预处理:首先将原始语料去掉段首的编号,然后将每个句子作为一行,编码转换为utf-8格式。最后按照9:1的比例将语料分为训练语料train.txt和测试语料test.txt。

        分别用二阶马尔柯夫过程和三阶马尔柯夫过程进行分词。试验结果如下图所示:


        从上图中可以看出,

        (1)三阶HMM的分词准确率和召回率均优于二阶HMM。

        (2)三阶HMM的切分词的总数要少于二阶HMM,但是切分正确的数量要大于二阶HMM。换句话说,二阶HMM倾向于将句子切的更细,而三阶HMM会比较保守,将句子切分出来的词少一些。

        (3)另外,对于交集型的歧义,三阶HMM明显要少于二阶HMM。说明马尔柯夫链增长之后,对于减少交集型歧义是很有作用的。


第三部分 源代码

        以下为本次实验过程的源代码,好多代码和之前讲述HMM分词的帖子里面的代码是一样的,只是一少部分作了修改,为了本文内容的完整性,我还是把代码全都在粘一遍把。注意之前的代码处理的是gb2312格式的文本,本文的代码文本本的格式要转换为utf-8哦,要不然,你把gb2312读进去出现了很多乱码,别说我没告诉你哦····

        (1)文件名:util.h。下面好几个文件都要用到该文件,如将测试文件中的/去掉

  1. #ifndef UTIL_H  
  2. #define UTIL_H  
  3.   
  4. #include <string>  
  5.   
  6. using namespace std;  
  7.   
  8. /* 
  9.  * 函数功能:将字符串中的所有特定子串置换为新的字符串 
  10.  * 函数输入:str     需要进行操作的字符串 
  11.  *         old_str 旧的字符串 
  12.  *         new_str 新的字符串 
  13.  * 函数输出:置换完毕的字符串 
  14.  */  
  15. string& replace_all(string &str, string old_str, string new_str){  
  16.     while(1){  
  17.         string::size_type pos(0);  
  18.         if((pos = str.find(old_str)) != string::npos){  
  19.             str.replace(pos, old_str.length(), new_str);  
  20.         }else{  
  21.             break;  
  22.         }  
  23.     }  
  24.     return str;  
  25. }  
  26.   
  27. #endif  

        (2)文件名:prehmm.cpp。对文件进行预处理工作,函数的功能请参见代码中的注释。
  1. #include <iostream>  
  2. #include <fstream>  
  3. #include <sstream>  
  4. #include <string>  
  5. #include <cstdlib>  
  6. #include <map>  
  7. #include "util.h"  
  8.   
  9. using namespace std;  
  10.   
  11.   
  12. /* 
  13.  * 函数功能:将训练语料和测试语料中出现的汉字进行编码,将他们的对应关系存入文件 
  14.  *         格式为:汉字-编码,编码从0开始 
  15.  * 函数输入:infile_1 训练语料文件名 
  16.  *         infile_2 测试语料文件名 
  17.  *         outfile  指定的输出文件名 
  18.  * 函数输出:名为outfile的文件 
  19.  */  
  20. void makeDB(string infile_1, string infile_2, string outfile){  
  21.     //读取输入文件  
  22.     ifstream fin_1(infile_1.c_str());  
  23.     ifstream fin_2(infile_2.c_str());  
  24.     if(!(fin_1 && fin_2)){  
  25.         cerr << "makeDB : Open input file fail !" << endl;  
  26.         exit(-1);  
  27.     }  
  28.     //打开输出文件  
  29.     ofstream fout(outfile.c_str());  
  30.     if(!fout){  
  31.         cerr << "makeDB : Open output file fail !" << endl;  
  32.         exit(-1);  
  33.     }  
  34.       
  35.     map<string, int> map_cchar;  
  36.     int id = -1;  
  37.     string line = "";  
  38.     string cchar = "";  
  39.     //读取输入文件内容  
  40.     while(getline(fin_1, line)){  
  41.         line = replace_all(line, "/""");  
  42.         if(line.size() >= 3){  
  43.             //逐字读取  
  44.             for(int i = 0; i < line.size() - 2; i += 3){  
  45.                 cchar = line.substr(i, 3);  
  46.                 if(map_cchar.find(cchar) == map_cchar.end()){  
  47.                     ++id;  
  48.                     map_cchar[cchar] = id;  
  49.                 }  
  50.             }  
  51.         }  
  52.     }  
  53.     while(getline(fin_2, line)){  
  54.         line = replace_all(line, "/""");  
  55.         if(line.size() >= 3){  
  56.             //逐字读取  
  57.             for(int i = 0; i < line.size() - 2; i += 3){  
  58.                 cchar = line.substr(i, 3);  
  59.                 if(map_cchar.find(cchar) == map_cchar.end()){  
  60.                     ++id;  
  61.                     map_cchar[cchar] = id;  
  62.                 }  
  63.             }  
  64.         }  
  65.     }  
  66.       
  67.     //输出到文件  
  68.     map<string, int>::iterator iter;  
  69.     for(iter = map_cchar.begin(); iter != map_cchar.end(); ++iter){  
  70.         //cout << iter -> first << " " << iter -> second << endl;  
  71.         fout << iter -> first << " " << iter -> second << endl;  
  72.     }  
  73.   
  74.     fin_1.close();  
  75.     fin_2.close();  
  76.     fout.close();  
  77. }  
  78.   
  79.   
  80. /* 
  81.  * 函数功能:将训练语料每个汉字后面加入对应的BMES状态 
  82.  * 函数输入:infile  训练语料文件名 
  83.  *         outfile 指定的输出文件名 
  84.  * 函数输出:名为outfile的文件 
  85.  */  
  86. void makeBMES(string infile, string outfile){  
  87.   
  88.     ifstream fin(infile.c_str());  
  89.     ofstream fout(outfile.c_str());  
  90.     if(!(fin && fout)){  
  91.         cerr << "makeBMES : Open file failed !" << endl;  
  92.         exit(-1);  
  93.     }  
  94.       
  95.     string word_in = "";  
  96.     string word_out = "";     
  97.     string line_in = "";  
  98.     string line_out = "";  
  99.   
  100.     while(getline(fin, line_in)){  
  101.         if(line_in.size() >= 3){  
  102.             line_out.clear();  
  103.             line_in = replace_all(line_in, "/"" ");  
  104.             istringstream strstm(line_in);  
  105.             while(strstm >> word_in){  
  106.                 word_out.clear();  
  107.                 if(word_in.size()%3 != 0){  
  108.                     cout << "单词不符合要求:" << word_in << endl;  
  109.                     continue;  
  110.                 }  
  111.                 int num = word_in.size()/3; //单词中包含多少个汉字  
  112.                 if(num == 0){  
  113.                     continue;  
  114.                 }  
  115.   
  116.                 if(num == 1){  
  117.                     word_out = word_in;  
  118.                     word_out += "/S";  
  119.                 }else{  
  120.                     //复制单词中的第一个字  
  121.                     word_out.insert(word_out.size(), word_in, 0, 3);  
  122.                     word_out += "/B";  
  123.                     //逐个复制单词中间的字  
  124.                     for(int i = 1; i < num - 1; i++){  
  125.                         word_out.insert(word_out.size(), word_in, 3*i, 3);  
  126.                         word_out += "/M";  
  127.                     }  
  128.                     //复制单词中最后的汉字  
  129.                     word_out.insert(word_out.size(), word_in, 3*num - 3, 3);  
  130.                     word_out += "/E";  
  131.                 }  
  132.   
  133.                 line_out += word_out;  
  134.             }  
  135.               
  136.             fout << line_out << endl;  
  137.         }  
  138.     }  
  139.   
  140. }  
  141.   
  142.   
  143. /* 
  144.  * 主函数 
  145.  */  
  146. int main(int argc, char *argv[]){  
  147.     if(argc < 5){  
  148.         cout << "Usage: " << argv[0] << " train_file test_file db_file bmes_file" << endl;  
  149.         exit(-1);  
  150.     }  
  151.     //构造DB文件,输入训练语料、测试语料、输出文件名  
  152.     makeDB(argv[1], argv[2], argv[3]);  
  153.   
  154.     //构造BMES文件,输入训练语料、输出文件名  
  155.     makeBMES(argv[1], argv[4]);  
  156.   
  157. }  

        (3)文件名:db.h。将汉字和编码的映射文件内存,构造为map,供其他程序使用
  1. #ifndef DB_H  
  2. #define DB_H  
  3.   
  4. #include <iostream>  
  5. #include <fstream>  
  6. #include <map>  
  7. #include <vector>  
  8. #include <cstdlib>  
  9. #include "util.h"  
  10.   
  11. using namespace std;  
  12.   
  13. /* 
  14.  * 转换类,获取编号 
  15.  */  
  16. class DB{  
  17.     private:  
  18.         map<string, int> cchar_map;   //汉字-编码映射  
  19.         map<int, string> index_map;   //编码-汉字映射  
  20.     public:  
  21.         DB();  
  22.         DB(string file);  
  23.         string getCchar(int id);        //根据编码获得汉字  
  24.         int getObservIndex(string cchar);   //根据汉字获得编码  
  25.         int getStateIndex(char state);      //根据状态获得状态编号  
  26.         vector<int> makeObservs(string line); //将输入的句子构造为发射符号序列  
  27. };  
  28.   
  29. //无参构造函数  
  30. DB::DB(){  
  31.   
  32. }  
  33.   
  34. //有参构造函数  
  35. DB::DB(string file){  
  36.     ifstream fin(file.c_str());  
  37.     if(!fin){  
  38.         cout << "Open input file fail ! Can't init Trans !" << endl;  
  39.         exit(-1);  
  40.     }  
  41.     string line = "";  
  42.     string word = "";  
  43.     string cchar = "";  
  44.     int id = 0;  
  45.     while(getline(fin, line)){  
  46.         istringstream strstm(line);  
  47.         strstm >> word;  
  48.         cchar = word;  
  49.         strstm >> word;  
  50.         id = atoi(word.c_str());  
  51.         //加入map  
  52.         cchar_map[cchar] = id;  
  53.         index_map[id] = cchar;  
  54.     }  
  55.     cout << "cchar_map大小: " << cchar_map.size() << endl;  
  56.     cout << "index_map大小: " << index_map.size() << endl;  
  57. }  
  58.   
  59. //将状态转换为数字编号  
  60. int DB::getStateIndex(char state){  
  61.     switch(state){  
  62.         case 'B' :  
  63.             return 0;  
  64.             break;  
  65.         case 'M' :  
  66.             return 1;  
  67.             break;  
  68.         case 'E' :  
  69.             return 2;  
  70.             break;  
  71.         case 'S' :  
  72.             return 3;  
  73.             break;  
  74.         default :  
  75.             return -1;  
  76.             break;  
  77.     }  
  78. }  
  79.   
  80. //将汉字转换为数字编号  
  81. int DB::getObservIndex(string cchar){  
  82.     map<string, int>::iterator iter = cchar_map.find(cchar);  
  83.     if(iter != cchar_map.end()){  
  84.         return iter -> second;  
  85.     }else{  
  86.         return -1;  
  87.     }  
  88. }  
  89.   
  90. //将数字编号转换为汉字  
  91. string DB::getCchar(int id){  
  92.     map<int, string>::iterator iter = index_map.find(id);  
  93.     if(iter != index_map.end()){  
  94.         return iter -> second;  
  95.     }else{  
  96.         return NULL;  
  97.     }  
  98. }  
  99.   
  100.   
  101. //将输入的句子构造为发射符号序列  
  102. vector<int> DB::makeObservs(string line){  
  103.     vector<int> vec_observ; //输出符号的集合  
  104.     string cchar = "";      //存放每个汉字  
  105.     string word = "";       //存放一个单词  
  106.     int num = 0;            //单词的字数  
  107.     int index = -1;         //单词对应的编号  
  108.   
  109.     line = replace_all(line, "/"" ");  
  110.     cout << line << endl;  
  111.     istringstream strstm(line);  
  112.     while(strstm >> word){  
  113.         if(word.size()%3 != 0){  
  114.             cout << "单词不符合要求:" << word << endl;  
  115.             continue;  
  116.         }  
  117.         num = word.size()/3;  
  118.         if(num == 0){  
  119.             continue;  
  120.         }else{  
  121.             for(int i = 0; i < num; i++){  
  122.                 cchar = word.substr(3*i, 3);  
  123.                 index = getObservIndex(cchar);  
  124.                 vec_observ.push_back(index);  
  125.         //cout << "cchar = " << cchar << "   index = " << index << endl;  
  126.             }  
  127.         }  
  128.     }  
  129.   
  130.     return vec_observ;  
  131. }  
  132.   
  133. #endif  

        (4)文件名:matrix.cpp。用最大似然估计的方法建立HMM的模型参数。
  1. #include <iostream>  
  2. #include <fstream>  
  3. #include <sstream>  
  4. #include <string>  
  5. #include <iomanip>  
  6. #include <cmath>  
  7. #include <list>  
  8. #include "db.h"  
  9.   
  10. using namespace std;  
  11.   
  12. const int N = 4;        //隐藏状态的数目  
  13. const int M = 4677;     //汉字的个数  
  14. const double VALUE = 1.0;   //平滑算法增加的值  
  15.   
  16.   
  17. //定义字典对象  
  18. DB db("db.txt");  
  19.   
  20.   
  21. /* 
  22.  * 模型训练,将频数转换为频率(加1平滑) 
  23.  */  
  24. void turingAdd(const int count[], double prob[], int len){  
  25.     double sum = 0.0;  
  26.     for(int i = 0; i < len; ++i){  
  27.         sum += count[i];  
  28.     }  
  29.   
  30.     sum = sum + VALUE * len;  
  31.     for(int i = 0; i < len; ++i){  
  32.         prob[i] = -log((count[i] + VALUE) / sum);//取对数  
  33.     }  
  34. }  
  35.   
  36.   
  37. /* 
  38.  * 模型训练,将发射频数转换为频率(古德-图灵平滑) 
  39.  */  
  40. void turingGood(const int count[], double prob[], int len){  
  41.     map<int, list<int> > freq_map;          //key为词频,value为该词频对应的汉字列表  
  42.     map<int, list<int> >::iterator iter;        //迭代器  
  43.     int sum = 0;                    //词频总和  
  44.   
  45.     //初始化freq_map  
  46.     for(int i = 0; i < len; i++){  
  47.         int freq = count[i];            //词频  
  48.         sum += freq;  
  49.   
  50.         iter = freq_map.find(freq);  
  51.         if(iter != freq_map.end()){  
  52.             //该词频已经存在,把当前词加入相应的list  
  53.             freq_map[freq].push_back(i);  
  54.         }else{  
  55.             //该词频不存在,建立对应的汉字list  
  56.             list<int> lst;  
  57.             lst.push_back(i);  
  58.             freq_map[freq] = lst;  
  59.         }  
  60.     }  
  61.   
  62.     //若sum=0,则结果初始化为0.0即可  
  63.     if(sum == 0){  
  64.         for(int i = 0; i < len; i++){  
  65.             prob[i] = 0.0;  
  66.         }  
  67.         return;  
  68.     }  
  69.       
  70.     //数据平滑处理  
  71.     iter = freq_map.begin();  
  72.     while(iter != freq_map.end()){  
  73.         double pr;  //频率  
  74.         int freq = iter -> first;  
  75.         int freqsize = iter -> second.size();  
  76.         if(++iter != freq_map.end()){  
  77.             int freq_2 = iter -> first;  
  78.             if(freq_2 = freq + 1){  
  79.                 int freqsize_2 = iter -> second.size();  
  80.                 pr = ((1.0 + freq) * freqsize_2) / (sum * freqsize);  
  81.             }else{  
  82.                 pr = 1.0 * freq / sum;  
  83.             }  
  84.         }else{  
  85.             pr = 1.0 * freq / sum;  
  86.         }  
  87.   
  88.         //计算结果  
  89.         list<int> lst = (--iter) -> second;  
  90.         list<int>::iterator iter_in = lst.begin();  
  91.         while(iter_in != lst.end()){  
  92.             int index = *iter_in;  
  93.             prob[index] = pr;  
  94.             ++iter_in;  
  95.         }  
  96.   
  97.         //准备下次迭代  
  98.         ++iter;  
  99.     }  
  100.   
  101.     //概率归一化  
  102.     double total = 0.0;  
  103.     for(int i = 0; i < len; i++){  
  104.         total += prob[i];  
  105.     }  
  106.     for(int i = 0; i < len; i++){  
  107.         prob[i] = -log((double)prob[i] / total);//取对数  
  108.     }  
  109. }  
  110.   
  111.   
  112. /* 
  113.  * 主函数,生成HMM模型的参数 
  114.  * 状态转移概率矩阵、初始状态概率矩阵、符号发射概率矩阵 
  115.  */  
  116. int main(int argc, char *argv[]){  
  117.     if(argc < 2){  
  118.         cout << "Usage: " << argv[0] << " bmes_file !" << endl;  
  119.         exit(-1);  
  120.     }  
  121.   
  122.     ifstream fin(argv[1]);  
  123.     if(!fin){  
  124.         cerr << "Open input file " << argv[1] << "filed !" << endl;  
  125.         exit(-1);  
  126.     }  
  127.   
  128.     int Pi[N] = {0};        //初始状态出现次数  
  129.     int A1[N][N] = {0};     //二阶状态转移次数  
  130.     int A2[N][N][N] = {0};      //三阶状态转移次数  
  131.     int B1[N][M] = {0};     //二阶符号发射次数  
  132.     int B2[N][N][M] = {0};      //三阶符号发射次数  
  133.   
  134.     //抽取文件中的状态和观察值  
  135.     string line = "";           //存放每一行的内容  
  136.     int line_num = 0;           //句子编号  
  137.     int count = 0;  
  138.     while(getline(fin, line)){  
  139.         line_num++;  
  140.         char state;         //状态  
  141.         string cchar = "";      //一个汉字  
  142.         int i, j, k, m;  
  143.         string::size_type pos = 0;  //当前处理位置  
  144.         if((pos = line.find("/", pos + 1)) != string::npos){  
  145.             //抽取句子的第一个状态  
  146.             state = line.at(pos + 1);  
  147.             i = db.getStateIndex(state);  
  148.             Pi[i]++;  
  149.             //抽取句子的第一个观察值  
  150.             cchar = line.substr(pos - 3, 3);  
  151.             m = db.getObservIndex(cchar);  
  152.             B1[i][m]++;   
  153.               
  154.             if((pos = line.find("/", pos + 1)) != string::npos){  
  155.                 //抽取句子的第二个状态  
  156.                 state = line.at(pos + 1);  
  157.                 j = db.getStateIndex(state);  
  158.                 A1[i][j]++;  
  159.                 //抽取句子的第二个观察值  
  160.                 cchar = line.substr(pos - 3, 3);  
  161.                 m = db.getObservIndex(cchar);  
  162.                 B1[j][m]++;  
  163.                 B2[i][j][m]++;  
  164.   
  165.                 while((pos = line.find("/", pos + 1)) != string::npos){  
  166.                     //抽取句子的其他状态  
  167.                     state = line.at(pos + 1);  
  168.                     k = db.getStateIndex(state);  
  169.                     A1[j][k]++;  
  170.                     A2[i][j][k]++;  
  171.                     //抽取句子的其他观察值  
  172.                     cchar = line.substr(pos - 3, 3);  
  173.                     m = db.getObservIndex(cchar);  
  174.                     B1[k][m]++;  
  175.                     B2[j][k][m]++;  
  176.   
  177.                     //准备下次迭代  
  178.                     i = j;  
  179.                     j = k;  
  180.                 }  
  181.             }  
  182.               
  183.         }  
  184.     }  
  185.     fin.close();  
  186.   
  187.     //打开输出流  
  188.     ofstream fout_1("Pi.mat");  //初始概率矩阵  
  189.     ofstream fout_2("A1.mat");  //二阶状态转移矩阵  
  190.     ofstream fout_3("A2.mat");  //三阶状态转移矩阵  
  191.     ofstream fout_4("B1.mat");  //二阶发射概率矩阵  
  192.     ofstream fout_5("B2.mat");  //三阶发射概率矩阵  
  193.     if(!(fout_1 && fout_2 && fout_3 && fout_4 && fout_5)){  
  194.         cerr << "Create Matrix file failed !" << endl;  
  195.         exit(-1);  
  196.     }  
  197.   
  198.     fout_1 << setprecision(8);  
  199.     fout_2 << setprecision(8);  
  200.     fout_3 << setprecision(8);  
  201.     fout_4 << setprecision(8);  
  202.     fout_5 << setprecision(8);  
  203.   
  204.     //初始状态矩阵写入文件  
  205.     double arr_pi[N] = {0.0};  
  206.     //turingGood(Pi, arr_pi, N);  
  207.     turingAdd(Pi, arr_pi, N);  
  208.     for(int i = 0; i < N; i++){  
  209.         fout_1 << arr_pi[i] << "\t";  
  210.     }  
  211.     fout_1 << endl;  
  212.   
  213.     //二阶状态转移矩阵写入文件  
  214.     double arr_a_1[N] = {0.0};  
  215.     for(int i = 0; i < N; i++){  
  216.         //turingGood(A1[i], arr_a_1, N);  
  217.         turingAdd(A1[i], arr_a_1, N);  
  218.         for(int j = 0; j < N; j++){  
  219.             fout_2 << arr_a_1[j] << "\t";  
  220.         }  
  221.         fout_2 << endl;  
  222.     }  
  223.   
  224.     //三阶状态转移矩阵写入文件  
  225.     double arr_a_2[N] = {0.0};  
  226.     for(int i = 0; i < N; i++){  
  227.         for(int j = 0; j < N; j++){  
  228.             //turingGood(A2[i][j], arr_a_2, N);  
  229.             turingAdd(A2[i][j], arr_a_2, N);  
  230.             for(int k = 0; k < N; k++){  
  231.                 fout_3 << arr_a_2[k] << "\t";  
  232.             }  
  233.             fout_3 << endl;  
  234.         }  
  235.     }  
  236.       
  237.     //二阶发射概率矩阵写入文件  
  238.     double arr_b_1[M] = {0.0};  
  239.     for(int i = 0; i < N; i++){  
  240.         //turingGood(B1[i], arr_b_1, M);  
  241.         turingAdd(B1[i], arr_b_1, M);  
  242.         for(int j = 0; j < M; j++){  
  243.             fout_4 << arr_b_1[j] << "\t";  
  244.         }  
  245.         fout_4 << endl;  
  246.     }  
  247.       
  248.     //三阶发射概率矩阵写入文件  
  249.     double arr_b_2[M] = {0.0};  
  250.     for(int i = 0; i < N; i++){  
  251.         for(int j = 0; j < N; j++){  
  252.             //turingGood(B2[i][j], arr_b_2, M);  
  253.             turingAdd(B2[i][j], arr_b_2, M);  
  254.             for(int k = 0; k < M; k++){  
  255.                 fout_5 << arr_b_2[k] << "\t";  
  256.             }  
  257.             fout_5 << endl;  
  258.         }  
  259.     }  
  260.   
  261.     fout_1.close();  
  262.     fout_2.close();  
  263.     fout_3.close();  
  264.     fout_4.close();  
  265.     fout_5.close();  
  266.   
  267.     return 0;  
  268. }  

        (5)文件名:hmm.h。将存储在文件中的HMM的模型参数读取到内存中,构造为一个HMM对象,供其他程序使用。
  1. #ifndef HMM_H  
  2. #define HMM_H  
  3.   
  4. #include <fstream>  
  5. #include <sstream>  
  6. #include <string>  
  7. #include <cstdlib>  
  8.   
  9. const int N = 4;  
  10. const int M = 4677;  
  11.   
  12. using namespace std;  
  13.   
  14. //定义HMM模型  
  15. class HMM{  
  16.   
  17.     public:  
  18.         int n;          //状态数目  
  19.         int m;          //可能的观察符号数目  
  20.         double Pi[N];       //初始状态概率  
  21.         double A1[N][N];    //状态转移概率矩阵  
  22.         double A2[N][N][N]; //状态转移概率矩阵  
  23.         double B1[N][M];    //符号发射概率矩阵  
  24.         double B2[N][N][M]; //符号发射概率矩阵  
  25.         HMM();  
  26.         HMM(string f_pi, string f_a1, string f_a2, string f_b1, string f_b2);  
  27. };  
  28.   
  29. //无参构造函数  
  30. HMM::HMM(){  
  31.   
  32. }  
  33.   
  34. //有参构造函数  
  35. HMM::HMM(string f_pi, string f_a1, string f_a2, string f_b1, string f_b2){  
  36.     ifstream fin_1(f_pi.c_str());  
  37.     ifstream fin_2(f_a1.c_str());  
  38.     ifstream fin_3(f_a2.c_str());  
  39.     ifstream fin_4(f_b1.c_str());  
  40.     ifstream fin_5(f_b2.c_str());  
  41.     if(!(fin_1 && fin_2 && fin_3 && fin_4 && fin_5)){  
  42.         exit(-1);  
  43.     }  
  44.   
  45.     n = N;  
  46.     m = M;  
  47.   
  48.     string line = "";  
  49.     string word = "";  
  50.   
  51.     //读取Pi  
  52.     getline(fin_1, line);  
  53.     istringstream strstm_1(line);  
  54.     for(int i = 0; i < N; i++){  
  55.         strstm_1 >> word;  
  56.         Pi[i] = atof(word.c_str());  
  57.     }  
  58.       
  59.     //读取A1  
  60.     for(int i = 0; i < N; i++){  
  61.         getline(fin_2, line);  
  62.         istringstream strstm_2(line);  
  63.         for(int j = 0; j < N; j++){  
  64.             strstm_2 >> word;  
  65.             A1[i][j] = atof(word.c_str());  
  66.         }  
  67.     }  
  68.   
  69.     //读取A2    
  70.     for(int i = 0; i < N; i++){  
  71.         for(int j = 0; j < N; j++){  
  72.             getline(fin_3, line);  
  73.             istringstream strstm_3(line);  
  74.             for(int k = 0; k < N; k++){  
  75.                 strstm_3 >> word;  
  76.                 A2[i][j][k] = atof(word.c_str());  
  77.             }  
  78.         }  
  79.     }  
  80.   
  81.     //读取B1  
  82.     for(int i = 0; i < N; i++){  
  83.         getline(fin_4, line);  
  84.         istringstream strstm_4(line);  
  85.         for(int j = 0; j < M; j++){  
  86.             strstm_4 >> word;  
  87.             B1[i][j] = atof(word.c_str());  
  88.         }  
  89.     }  
  90.       
  91.     //读取B2  
  92.     for(int i = 0; i < N; i++){  
  93.         for(int j = 0; j < N; j++){  
  94.             getline(fin_5, line);  
  95.             istringstream strstm_5(line);  
  96.             for(int k = 0; k < M; k++){  
  97.                 strstm_5 >> word;  
  98.                 B2[i][j][k] = atof(word.c_str());  
  99.             }  
  100.         }  
  101.     }  
  102.   
  103.     fin_1.close();  
  104.     fin_2.close();  
  105.     fin_3.close();  
  106.     fin_4.close();  
  107.     fin_5.close();  
  108. }  
  109.   
  110. #endif  

        (6)文件名:viterbi.cpp。维特比算法,用于分词。这是最核心的部分哦···
  1. #include <iostream>  
  2. #include <fstream>  
  3. #include <sstream>  
  4. #include <string>  
  5. #include <stack>  
  6. #include "hmm.h"  
  7. #include "db.h"  
  8.   
  9. using namespace std;  
  10.   
  11. HMM hmm("Pi.mat""A1.mat""A2.mat""B1.mat""B2.mat");  //初始化HMM模型  
  12. DB db("db.txt");            //初始化字典  
  13.   
  14.   
  15. /* 
  16.  * Viterbi算法进行分词,二阶马尔柯夫过程 
  17.  */  
  18. string viterbiTwo(string str_in){  
  19.   
  20.     //计算输入句子中的汉字个数  
  21.     int row = str_in.size() / 3;  
  22.     string str_out = "";  
  23.       
  24.     //如果输入字符串为空,则直接返回空  
  25.     if(row == 0){  
  26.         return str_out;  
  27.     }  
  28.     //如果只有一个字的话,则直接输出即可  
  29.     if(row < 2){  
  30.         str_out = str_in + "/";  
  31.         return str_out;  
  32.     }     
  33.   
  34.     //分配矩阵空间  
  35.     double **delta = new double *[row];  
  36.     int **path = new int *[row];  
  37.     for(int i = 0; i < row; i++){  
  38.         delta[i] = new double[N]();  
  39.         path[i] = new int[N]();  
  40.     }  
  41.   
  42.     //中间变量  
  43.     string cchar = "";  //存放汉字  
  44.     int min_path = -1;  
  45.     double val = 0.0;  
  46.     double min_val = 0.0;  
  47.   
  48.     //初始化矩阵,给delta和path矩阵的第一行赋初值  
  49.     cchar = str_in.substr(0, 3);  
  50.     int cchar_num = db.getObservIndex(cchar);  
  51.     for(int i = 0; i < N; i++){  
  52.         delta[0][i] = hmm.Pi[i] + hmm.B1[i][cchar_num]; //对数  
  53.         path[0][i] = -1;  
  54.     }  
  55.   
  56.     //给delta和path的后续行赋值(对数)  
  57.     for(int t = 1; t < row; t++){  
  58.         cchar = str_in.substr(3*t, 3);  
  59.         cchar_num = db.getObservIndex(cchar);  
  60.         for(int j = 0; j < N; j++){  
  61.             min_val = 100000.0;  
  62.             min_path = -1;  
  63.             for(int i = 0; i < N; i++){  
  64.                 val = delta[t-1][i] + hmm.A1[i][j];  
  65.                 if(val < min_val){  
  66.                     min_val = val;  
  67.                     min_path = i;  
  68.                 }  
  69.             }  
  70.   
  71.             delta[t][j] = min_val + hmm.B1[j][cchar_num];  
  72.             path[t][j] = min_path;  
  73.         }  
  74.     }  
  75.   
  76.     //找delta矩阵最后一行的最大值  
  77.     min_val = 100000.0;  
  78.     min_path = -1;  
  79.     for(int i = 0; i < N; i++){  
  80.         if(delta[row-1][i] < min_val){  
  81.             min_val = delta[row-1][i];  
  82.             min_path = i;  
  83.         }  
  84.     }  
  85.   
  86.     //从min_path出发,回溯得到最可能的路径  
  87.     stack<int> path_st;  
  88.     path_st.push(min_path);  
  89.     for(int i = row - 1; i > 0; i--){  
  90.         min_path = path[i][min_path];  
  91.         path_st.push(min_path);  
  92.     }  
  93.       
  94.     //释放二维数组  
  95.     for(int i = 0; i < row; i++){  
  96.         delete []delta[i];  
  97.         delete []path[i];  
  98.     }  
  99.     delete []delta;  
  100.     delete []path;  
  101.   
  102.     //根据标记好的状态序列分词  
  103.     int pos = 0;  
  104.     int index = -1;  
  105.     while(!path_st.empty()){  
  106.         index = path_st.top();  
  107.         path_st.pop();  
  108.         str_out.insert(str_out.size(), str_in, pos, 3);  
  109.         if(index == 2 || index == 3){  
  110.             //状态为E或S  
  111.             str_out.append("/");  
  112.         }  
  113.         pos += 3;  
  114.     }  
  115. }  
  116.   
  117.   
  118.   
  119.   
  120. /* 
  121.  * Viterbi算法进行分词:三阶马尔柯夫过程 
  122.  */  
  123. string viterbiThree(string str_in){  
  124.   
  125.     //计算输入句子中的汉字个数  
  126.     int row = str_in.size() / 3;  
  127.     string str_out = "";  
  128.       
  129.     //如果输入字符串为空,则直接返回空  
  130.     if(row == 0){  
  131.         return str_out;  
  132.     }  
  133.     //如果只有一个字的话,则直接输出即可  
  134.     if(row < 2){  
  135.         str_out = str_in + "/";  
  136.         return str_out;  
  137.     }  
  138.   
  139.     //分配矩阵空间  
  140.     double ***delta = new double **[row];  
  141.     int ***path = new int **[row];  
  142.     for(int i = 0; i < row; i++){  
  143.         delta[i] = new double *[N];  
  144.         path[i] = new int *[N];  
  145.         for(int j = 0; j < N; j++){  
  146.             delta[i][j] = new double[N];  
  147.             path[i][j] = new int[N];  
  148.             for(int k = 0; k < N; k++){  
  149.                 delta[i][j][k] = 0.0;  
  150.                 path[i][j][k] = 0;  
  151.             }  
  152.         }  
  153.     }  
  154.   
  155.     //初始化矩阵,给delta和path矩阵的第1个面赋初值  
  156.     //初始状态需要两个面,第0面不赋值,只给第1个面赋值  
  157.     string cchar_1 = str_in.substr(0, 3);   //第1个字  
  158.     string cchar_2 = str_in.substr(3, 3);   //第2个字  
  159.     int num_1 = db.getObservIndex(cchar_1); //第1个字的编号  
  160.     int num_2 = db.getObservIndex(cchar_2); //第2个字的编号  
  161.     for(int i = 0; i < N; i++){  
  162.         for(int j = 0; j < N; j++){  
  163.             delta[1][i][j] = hmm.Pi[i] + hmm.B1[i][num_1] +   
  164.                     hmm.A1[i][j] + hmm.B2[i][j][num_2]; //对数  
  165.             path[1][i][j] = -1;  
  166.         }  
  167.     }  
  168.   
  169.     //中间变量  
  170.     string cchar_3 = "";    //存放汉字  
  171.     int min_path = -1;  
  172.     double val = 0.0;  
  173.     double min_val = 0.0;  
  174.   
  175.     //给delta和path的后续面赋值(对数)  
  176.     //第0、1面为初始面,后续面从2开始,到row-1为止  
  177.     for(int t = 2; t < row; t++){  
  178.         cchar_3 = str_in.substr(3*t, 3);  
  179.         int num_3 = db.getObservIndex(cchar_3);  
  180.         for(int j = 0; j < N; j++){  
  181.             for(int k = 0; k < N; k++){  
  182.                 min_val = 100000.0;  
  183.                 min_path = -1;  
  184.                 for(int i = 0; i < N; i++){  
  185.                     val = delta[t-1][i][j] + hmm.A2[i][j][k];  
  186.                     if(val < min_val){  
  187.                         min_val = val;  
  188.                         min_path = i;  
  189.                     }  
  190.                 }  
  191.                 delta[t][j][k] = min_val + hmm.B2[j][k][num_3];  
  192.                 path[t][j][k] = min_path;  
  193.             }  
  194.         }  
  195.     }  
  196.   
  197.     //找delta矩阵最后一个面的最大值,最后一个面为row-1  
  198.     min_val = 100000.0;  
  199.     int min_path_i = -1;  
  200.     int min_path_j = -1;  
  201.     for(int i = 0; i < N; i++){  
  202.         for(int j = 0; j < N; j++){  
  203.             if(delta[row-1][i][j] < min_val){  
  204.                 min_val = delta[row-1][i][j];  
  205.                 min_path_i = i;  
  206.                 min_path_j = j;  
  207.             }  
  208.         }  
  209.     }  
  210.   
  211.     //从min_path_i和min_path_j出发,回溯得到最可能的路径  
  212.     //回溯从row-1开始,到2为止  
  213.     stack<int> path_st;  
  214.     path_st.push(min_path_j);  
  215.     path_st.push(min_path_i);  
  216.     for(int t = row - 1; t > 1; t--){  
  217.         int min_path_k = path[t][min_path_i][min_path_j];  
  218.         path_st.push(min_path_k);  
  219.         min_path_j = min_path_i;  
  220.         min_path_i = min_path_k;  
  221.     }  
  222.       
  223.     //释放三维数组  
  224.     for(int i = 0; i < row; i++){  
  225.         for(int j = 0; j < N; j++){  
  226.             delete []delta[i][j];  
  227.             delete []path[i][j];  
  228.         }  
  229.         delete []delta[i];  
  230.         delete []path[i];  
  231.     }  
  232.     delete []delta;  
  233.     delete []path;  
  234.   
  235.     //根据标记好的状态序列分词  
  236.     int pos = 0;  
  237.     int index = -1;  
  238.     while(!path_st.empty()){  
  239.         index = path_st.top();  
  240.         path_st.pop();  
  241.         str_out.insert(str_out.size(), str_in, pos, 3);  
  242.         if(index == 2 || index == 3){  
  243.             //状态为E或S  
  244.             str_out.append("/");  
  245.         }  
  246.         pos += 3;  
  247.     }  
  248. }  

        (7)文件名:main.cpp。主函数,调用维特比算法进行分词工作,并对分词结果进行比对,统计后输出结果。
  1. #include <cstdlib>  
  2. #include <vector>  
  3. #include <iomanip>  
  4. #include <map>  
  5. #include <algorithm>  
  6. #include <sys/time.h>  
  7. #include <sys/stat.h>  
  8. #include "util.h"  
  9. #include "viterbi.cpp"  
  10.   
  11.   
  12. const long MaxCount = 50000;    //需要切分的最大句子数量,若该值大于文件中  
  13.                 //实际的句子数量,以实际句子数量为准。  
  14.   
  15. //获取当前时间(ms)  
  16. long getCurrentTime(){  
  17.     struct timeval tv;  
  18.     gettimeofday(&tv, NULL);  
  19.     return tv.tv_sec*1000 + tv.tv_usec/1000;  
  20. }  
  21.   
  22. //获取文件大小  
  23. unsigned long getFileSize(string file_path){  
  24.     unsigned long filesize = -1;  
  25.     struct stat statbuff;  
  26.     if(stat(file_path.c_str(), &statbuff) < 0){  
  27.         return filesize;  
  28.     }else{  
  29.         filesize = statbuff.st_size;  
  30.     }  
  31.         return filesize;  
  32. }  
  33.   
  34.   
  35. /* 
  36.  * 函数功能:计算切分标记的位置 
  37.  * 函数输入:1.strline_in未进行切分的汉字字符串 
  38.            2.strline_right进行切分后的汉字字符串 
  39.  * 函数输出:vecetor,其中存放了strline_in中哪些位置放置了分词标记 
  40.  *         注意:vector中不包含最后标记的位置,但是包含位置0。 
  41.  */  
  42. vector<int> getPos(string strline_right, string strline_in){  
  43.     int pos_1 = 0;  
  44.     int pos_2 = -1;  
  45.     int pos_3 = 0;  
  46.     string word = "";  
  47.     vector<int> vec;  
  48.   
  49.     int length = strline_right.length();  
  50.     while(pos_2 < length){  
  51.         //前面的分词标记  
  52.         pos_1 = pos_2;  
  53.           
  54.         //后面的分词标记  
  55.         pos_2 = strline_right.find('/', pos_1 + 1);  
  56.   
  57.         if(pos_2 > pos_1){  
  58.             //将两个分词标记之间的单词取出  
  59.             word  = strline_right.substr(pos_1 + 1, pos_2 - pos_1 - 1);  
  60.             //根据单词去输入序列中查出出现的位置  
  61.             pos_3 = strline_in.find(word, pos_3);  
  62.             //将位置存入数组  
  63.             vec.push_back(pos_3);  
  64.             pos_3 = pos_3 + word.size();  
  65.         }else{  
  66.             break;  
  67.         }  
  68.     }  
  69.       
  70.     return vec;  
  71. }  
  72.   
  73.   
  74. /* 
  75.  * 获取标准切分和程序切分的结果 
  76.  */  
  77. string getString(string word, int pos, vector<int> vec_right){  
  78.     char ss[1000];  
  79.     int i = 0;  
  80.     int k = 0;  
  81.     if(vec_right.size() == 0){  
  82.         return word;  
  83.     }  
  84.     while(vec_right[i] < pos){  
  85.         i++;  
  86.     }  
  87.     for(int j = 0; j < word.size(); j++){  
  88.         if(j == vec_right[i] - pos){  
  89.             if(j != 0){  
  90.                 ss[k] = '/';  
  91.                 ++k;  
  92.             }  
  93.             ++i;  
  94.         }  
  95.         ss[k] = word[j];  
  96.         ++k;  
  97.     }  
  98.     ss[k] = '\0';  
  99.     string word_str = ss;  
  100.   
  101.     return word_str;  
  102. }  
  103.   
  104. /* 
  105.  * 函数功能:获取单个句子切分的结果统计 
  106.  * 函数输入:1.vec_right 正确的分词标记位置集合 
  107.  *           2.vec_out   函数切分得到的分词标记位置集合 
  108.  * 函数输出:返回一个veceor,含有4个元素,分别为: 
  109.  *          切分正确、组合型歧义、未登录词、交集型歧义的数量 
  110.  * 
  111.  */  
  112. vector<int> getCount_2(string strline, vector<int> vec_right, vector<int> vec_out, vector<string> &vec_err){  
  113.     vector<int> vec(4, 0);    //存放计算结果  
  114.     //建立map  
  115.     map<intint> map_result;  
  116.     for(int i = 0; i < vec_right.size(); i++){  
  117.         map_result[vec_right[i]] += 1;  
  118.     }  
  119.     for(int i = 0; i < vec_out.size(); i++){  
  120.         map_result[vec_out[i]] += 2;  
  121.     }  
  122.   
  123.     //统计map中的信息  
  124.     //若value=1,只在vec_right中  
  125.     //若value=2,只在vec_out中  
  126.     //若value=3,在vec_right和vec_out中都有  
  127.     map<intint>::iterator p_pre, p_cur;  
  128.     int count_value_1 = 0;  
  129.     int count_value_2 = 0;  
  130.     int count_value_3 = 0;  
  131.     p_pre = map_result.begin();  
  132.     p_cur = map_result.begin();  
  133.     while(p_cur != map_result.end()){  
  134.         while(p_cur != map_result.end() && p_cur -> second == 3){  
  135.             p_pre = p_cur;  
  136.             ++count_value_3;    //切分正确的数目  
  137.             ++p_cur;        //迭代器后移  
  138.         }  
  139.           
  140.         while(p_cur != map_result.end() && p_cur -> second != 3){  
  141.             if(p_cur -> second == 1){  
  142.                 ++count_value_1;  
  143.             }else if(p_cur -> second == 2){  
  144.                 ++count_value_2;  
  145.             }  
  146.             ++p_cur;  
  147.         }  
  148.           
  149.         //确定切分错误的字符串  
  150.         if(p_cur == map_result.end() && p_cur == (++p_pre)){  
  151.             continue;  
  152.         }  
  153.         int pos_1 = p_pre -> first;  
  154.         int pos_2 = p_cur -> first;   
  155.         string word = strline.substr(pos_1, pos_2 - pos_1); //切分错误的单词  
  156.         string word_right = getString(word, pos_1, vec_right);  //正确的切分方式  
  157.         string word_out = getString(word, pos_1, vec_out);  //得到的切分方式  
  158.    
  159.         string str_err = "";  
  160.         //不同的错误类型         
  161.         if(count_value_1 > 0 && count_value_2 == 0){  
  162.             str_err = "  组合型歧义: " + word + "    正确切分: " + word_right + "    错误切分: " + word_out;  
  163.             vec_err.push_back(str_err);  
  164.             cout << str_err << endl;  
  165.             vec[1] += count_value_1;          
  166.         }else if(count_value_1 == 0 && count_value_2 > 0){  
  167.             str_err = "  未登录词语: " + word + "    正确切分: " + word_right + "    错误切分: " + word_out;  
  168.             vec_err.push_back(str_err);  
  169.             cout << str_err << endl;  
  170.             vec[2] += count_value_2;  
  171.         }else if(count_value_1 > 0 && count_value_2 > 0){  
  172.             str_err = "  交集型歧义: " + word + "    正确切分: " + word_right + "    错误切分: " + word_out;  
  173.             vec_err.push_back(str_err);  
  174.             cout << str_err << endl;  
  175.             vec[3] += count_value_2;      
  176.         }  
  177.   
  178.         //计数器复位  
  179.         count_value_1 = 0;  
  180.         count_value_2 = 0;  
  181.     }  
  182.   
  183.     vec[0] += count_value_3;      
  184.   
  185.     return vec;  
  186. }  
  187.   
  188.   
  189. /* 
  190.  * 主函数:进行分词并统计分词结果 
  191.  * 
  192.  */  
  193. int main(int argc, char *argv[]){  
  194.     if(argc < 3){  
  195.         cout << "Usage: " << argv[0] << " test_file result_file" << endl;  
  196.         exit(-1);  
  197.     }  
  198.   
  199.     long time_1 = getCurrentTime();  
  200.       
  201.     string strline_right;   //输入语料:用作标准分词结果  
  202.     string strline_in;  //去掉分词标记的语料(用作分词的输入)  
  203.     string strline_out_1;   //隐马尔科夫模型(二阶)分词完毕的语料  
  204.     string strline_out_2;   //隐马尔科夫模型(三阶)分词完毕的语料  
  205.       
  206.     ifstream fin(argv[1]);  //打开输入文件  
  207.     if(!fin){  
  208.         cout << "Unable to open input file !" << argv[1] << endl;  
  209.         exit(-1);  
  210.     }  
  211.   
  212.     ofstream fout(argv[2]); //确定输出文件  
  213.     if(!fout){  
  214.         cout << "Unable to open output file !" << endl;  
  215.         exit(-1);  
  216.     }  
  217.       
  218.     long count = 0;         //句子编号  
  219.     long count_1 = 0;       //隐马尔科夫模型(二阶)切分完全正确的句子总数  
  220.     long count_2 = 0;       //隐马尔科夫模型(三阶)切分完全正确的句子总数  
  221.     long count_right_all = 0;   //准确的切分总数  
  222.     //二阶  
  223.     long count_out_1_all = 0;   //隐马尔科夫模型切分总数  
  224.     long count_out_1_right_all = 0; //隐马尔科夫模型切分正确总数  
  225.     long count_out_1_fail_1_all = 0;//隐马尔科夫模型(组合型歧义)  
  226.     long count_out_1_fail_2_all = 0;//隐马尔科夫模型(未登录词语)  
  227.     long count_out_1_fail_3_all = 0;//隐马尔科夫模型(交集型歧义)  
  228.     //三阶  
  229.     long count_out_2_all = 0;   //隐马尔科夫模型切分总数  
  230.     long count_out_2_right_all = 0; //隐马尔科夫模型切分正确总数  
  231.     long count_out_2_fail_1_all = 0;//隐马尔科夫模型(组合型歧义)  
  232.     long count_out_2_fail_2_all = 0;//隐马尔科夫模型(未登录词语)  
  233.     long count_out_2_fail_3_all = 0;//隐马尔科夫模型(交集型歧义)  
  234.   
  235.   
  236.     vector<string> vec_err_1; //隐马尔科夫模型(二阶)切分错误的词  
  237.     vector<string> vec_err_2; //隐马尔科夫模型(三阶)切分错误的词  
  238.   
  239.     while(getline(fin, strline_right, '\n') && count < MaxCount){  
  240.         if(strline_right.length() > 1){  
  241.               
  242.             //去掉分词标记  
  243.             strline_in = strline_right;  
  244.             strline_in = replace_all(strline_in, "/""");  
  245.   
  246.             //隐马尔科夫模型分词  
  247.             strline_out_1 = strline_right;  
  248.             istringstream strstm(strline_in);  
  249.             string sentence;  
  250.             string result_1;  
  251.             string result_2;  
  252.             string line_out_1;  
  253.             string line_out_2;  
  254.             while(strstm >> sentence){  
  255.                 //二阶切分  
  256.                 result_1 = viterbiTwo(sentence);  
  257.                 line_out_1 += result_1;  
  258.                 //三阶切分  
  259.                 result_2 = viterbiThree(sentence);  
  260.                 line_out_2 += result_2;  
  261.             }  
  262.             strline_out_1 = line_out_1;  
  263.             strline_out_2 = line_out_2;  
  264.   
  265.             //输出分词结果  
  266.             count++;  
  267.             cout << "----------------------------------------------" << endl;  
  268.             cout << "句子编号:" << count << endl;  
  269.             cout << endl;  
  270.             cout << "待分词的句子长度: " << strline_in.length() << "  句子:" << endl;  
  271.             cout << strline_in << endl;  
  272.             cout << endl;  
  273.             cout << "标准比对结果长度: " << strline_right.length() << "  句子:" << endl;  
  274.             cout << strline_right << endl;  
  275.             cout << endl;  
  276.             cout << "隐马尔科夫模型(二阶)分词长度: " << strline_out_1.length() << "  句子:" << endl;  
  277.             cout << strline_out_1 << endl;  
  278.             cout << endl;  
  279.             cout << "隐马尔科夫模型(三阶)分词长度: " << strline_out_2.length() << "  句子:" << endl;  
  280.             cout << strline_out_2 << endl;  
  281.             cout << endl;  
  282.               
  283.   
  284.             //输出分词结果的数字序列表示  
  285.             vector<int> vec_right = getPos(strline_right, strline_in);  
  286.             vector<int> vec_out_1 = getPos(strline_out_1, strline_in);  
  287.             vector<int> vec_out_2 = getPos(strline_out_2, strline_in);  
  288.               
  289.             cout << "标准结果:" << endl;  
  290.             for(int i = 0; i < vec_right.size(); i++){  
  291.                 cout << setw(4) << vec_right[i];  
  292.             }  
  293.             cout << endl;  
  294.   
  295.             cout << "隐马尔科夫模型(二阶)分词结果:" << endl;  
  296.             for(int i = 0; i < vec_out_1.size(); i++){  
  297.                 cout << setw(4) << vec_out_1[i];  
  298.             }  
  299.             cout << endl;  
  300.   
  301.             cout << "隐马尔科夫模型(三阶)分词结果:" << endl;  
  302.             for(int i = 0; i < vec_out_2.size(); i++){  
  303.                 cout << setw(4) << vec_out_2[i];  
  304.             }  
  305.             cout << endl;  
  306.               
  307.   
  308.             //输出匹配的错误列表  
  309.             cout << endl;  
  310.             if(vec_right == vec_out_1){  
  311.                 cout << "隐马尔科夫模型(二阶)分词完全正确!" << endl;  
  312.                 count_1++;  
  313.             }else{  
  314.                 cout << "隐马尔科夫模型(二阶)分词错误列表:" << endl;  
  315.             }  
  316.             vector<int> vec_count_1 = getCount_2(strline_in, vec_right, vec_out_1, vec_err_1);  
  317.   
  318.             cout << endl;  
  319.             if(vec_right == vec_out_2){  
  320.                 cout << "隐马尔科夫模型(三阶)分词完全正确!" << endl;  
  321.                 count_2++;  
  322.             }else{  
  323.                 cout << "隐马尔科夫模型(三阶)分词错误列表:" << endl;  
  324.             }  
  325.             vector<int> vec_count_2 = getCount_2(strline_in, vec_right, vec_out_2, vec_err_2);  
  326.                           
  327.             //准确的切分数量  
  328.             int count_right = vec_right.size();  
  329.             //切分得到的数量  
  330.             int count_out_1 = vec_out_1.size();           
  331.             int count_out_2 = vec_out_2.size();           
  332.             //切分正确的数量  
  333.             int count_out_1_right = vec_count_1[0];  
  334.             cout << "切分得到:" << count_out_1 << endl;  
  335.             cout << "切分正确:" << count_out_1_right << endl;           
  336.   
  337.             cout << "隐马尔科夫模型(二阶):" << endl;   
  338.             cout << "  组合型歧义:" << vec_count_1[1] << endl;  
  339.             cout << "  未登录词语:" << vec_count_1[2] << endl;  
  340.             cout << "  交集型歧义:" << vec_count_1[3] << endl;  
  341.               
  342.             int count_out_2_right = vec_count_2[0];  
  343.             cout << "切分得到:" << count_out_2 << endl;  
  344.             cout << "切分正确:" << count_out_2_right << endl;           
  345.   
  346.             cout << "隐马尔科夫模型(三阶):" << endl;   
  347.             cout << "  组合型歧义:" << vec_count_2[1] << endl;  
  348.             cout << "  未登录词语:" << vec_count_2[2] << endl;  
  349.             cout << "  交集型歧义:" << vec_count_2[3] << endl;  
  350.               
  351.             count_right_all += count_right;  
  352.   
  353.             count_out_1_all += count_out_1;  
  354.             count_out_1_right_all += count_out_1_right;  
  355.             count_out_1_fail_1_all += vec_count_1[1];  
  356.             count_out_1_fail_2_all += vec_count_1[2];  
  357.             count_out_1_fail_3_all += vec_count_1[3];  
  358.               
  359.             count_out_2_all += count_out_2;  
  360.             count_out_2_right_all += count_out_2_right;  
  361.             count_out_2_fail_1_all += vec_count_2[1];  
  362.             count_out_2_fail_2_all += vec_count_2[2];  
  363.             count_out_2_fail_3_all += vec_count_2[3];  
  364.               
  365.         }  
  366.     }  
  367.       
  368.     long time_2 = getCurrentTime();  
  369.     unsigned long file_size = getFileSize("test.txt");  
  370.   
  371.   
  372.     //打印错误的切分内容   
  373.     cout << endl;  
  374.     cout << "---------------------------------" << endl;  
  375.     cout << "错误样例(已排序):" << endl;  
  376.   
  377.   
  378.     //对错误切分内容进行排序并掉重复的  
  379.     sort(vec_err_1.begin(), vec_err_1.end());  
  380.     sort(vec_err_2.begin(), vec_err_2.end());  
  381.       
  382.     vector<string>::iterator end_unique_1 = unique(vec_err_1.begin(), vec_err_1.end());  
  383.     vector<string>::iterator end_unique_2 = unique(vec_err_2.begin(), vec_err_2.end());  
  384.       
  385.   
  386.     int num_1 = end_unique_1 - vec_err_1.begin();  
  387.     int num_2 = end_unique_2 - vec_err_2.begin();  
  388.       
  389.   
  390.     cout << "----------------------------------" << endl;  
  391.     cout << "隐马尔科夫模型(二阶)切分错误数量:" << num_1 << endl;  
  392.     for(int i = 0; i < num_1; i++){  
  393.         cout << vec_err_1[i] << endl;  
  394.     }  
  395.     cout << endl;  
  396.   
  397.     cout << "----------------------------------" << endl;  
  398.     cout << "隐马尔科夫模型(三阶)切分错误数量:" << num_2 << endl;  
  399.     for(int i = 0; i < num_2; i++){  
  400.         cout << vec_err_2[i] << endl;  
  401.     }  
  402.     cout << endl;  
  403.       
  404.   
  405.     //计算准确率和召回率  
  406.     double kk_1 = (double)count_out_1_right_all / count_out_1_all;  //隐马尔科夫模型(二阶)准确率  
  407.     double kk_2 = (double)count_out_1_right_all / count_right_all;  //隐马尔科夫模型(二阶)召回率  
  408.     double kk_3 = (double)count_out_2_right_all / count_out_2_all;  //隐马尔科夫模型(三阶)准确率  
  409.     double kk_4 = (double)count_out_2_right_all / count_right_all;  //隐马尔科夫模型(三阶)召回率  
  410.       
  411.   
  412.     //集中输出结果  
  413.     cout << endl;  
  414.     cout << "---------------------------------" << endl;  
  415.     cout << "分词消耗时间:" << time_2 - time_1 << "ms" << endl;  
  416.     cout << "测试文件大小:" << file_size/1024 << " KB" << endl;  
  417.     cout << "分词速度为:  " << (double)file_size*1000/((time_2 - time_1)*1024) << " KB/s" << endl;  
  418.   
  419.       
  420.   
  421.     cout << endl;  
  422.     cout << "句子总数:" << count << endl;  
  423.       
  424.     cout << "隐马尔科夫模型(二阶)切分完全正确的句子数目: " << count_1 << "\t ( " << (double)count_1*100/count << " % )" << endl;  
  425.     cout << "隐马尔科夫模型(三阶)切分完全正确的句子数目: " << count_2 << "\t ( " << (double)count_2*100/count << " % )" << endl;  
  426.       
  427.     cout << endl;  
  428.   
  429.     cout << "准确的切分总数:" << count_right_all << endl;        //准确的切分总数  
  430.     cout << "隐马尔科夫模型(二阶)切分总数:" << count_out_1_all << endl;        //隐马尔科夫模型切分总数     
  431.     cout << "隐马尔科夫模型(三阶)切分总数:" << count_out_2_all << endl;        //隐马尔科夫模型切分总数     
  432.     cout << "隐马尔科夫模型(二阶)切分正确总数:" << count_out_1_right_all << endl;    //隐马尔科夫模型切分正确总数  
  433.     cout << "隐马尔科夫模型(三阶)切分正确总数:" << count_out_2_right_all << endl;    //隐马尔科夫模型切分正确总数  
  434.       
  435.   
  436.     cout << endl;  
  437.     cout << "隐马尔科夫模型(二阶):" << endl;  
  438.     long count_out_1_fail_all = count_out_1_fail_1_all + count_out_1_fail_2_all + count_out_1_fail_3_all;     
  439.     cout << "  组合型歧义:" << count_out_1_fail_1_all << "\t ( " << (double)count_out_1_fail_1_all*100/count_out_1_fail_all << " % )" << endl;  
  440.     cout << "  未登录词语:" << count_out_1_fail_2_all << "\t ( " << (double)count_out_1_fail_2_all*100/count_out_1_fail_all << " % )" << endl;  
  441.     cout << "  交集型歧义:" << count_out_1_fail_3_all << "\t ( " << (double)count_out_1_fail_3_all*100/count_out_1_fail_all << " % )" << endl;  
  442.     cout << endl;  
  443.     cout << "隐马尔科夫模型(三阶):" << endl;  
  444.     long count_out_2_fail_all = count_out_2_fail_1_all + count_out_2_fail_2_all + count_out_2_fail_3_all;     
  445.     cout << "  组合型歧义:" << count_out_2_fail_1_all << "\t ( " << (double)count_out_2_fail_1_all*100/count_out_2_fail_all << " % )" << endl;  
  446.     cout << "  未登录词语:" << count_out_2_fail_2_all << "\t ( " << (double)count_out_2_fail_2_all*100/count_out_2_fail_all << " % )" << endl;  
  447.     cout << "  交集型歧义:" << count_out_2_fail_3_all << "\t ( " << (double)count_out_2_fail_3_all*100/count_out_2_fail_all << " % )" << endl;  
  448.       
  449.     cout << endl;       
  450.     cout << "统计结果:" << endl;  
  451.     cout << "隐马尔科夫模型(二阶)    准确率:" << kk_1*100 << "%  \t召回率:" << kk_2*100 << "%" << endl;  
  452.     cout << "隐马尔科夫模型(三阶)    准确率:" << kk_3*100 << "%  \t召回率:" << kk_4*100 << "%" << endl;  
  453.       
  454.   
  455.     return 0;  

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
雨流计数法(Rainflow Counting Method)是应用于疲劳寿命评估的一种方法,用于对振动载荷信号进行统计分析。在MATLAB中使用雨流计数法可以通过以下步骤进行: 1. 准备载荷信号数据:将需要分析的振动载荷信号以向量形式导入MATLAB中,确保信号数据按时间序列排列。 2. 定义载荷振幅与载荷均值的阈值:根据具体情况,定义振荡载荷的阈值,即超过该阈值的载荷被认为是振荡载荷,低于该阈值的载荷被认为是静载荷。 3. 实现雨流计数程序:使用MATLAB的编程功能,编写计算雨流计数的程序。程序的主要目的是将载荷信号转化为一系列载荷振幅和裂纹母线均值的载荷循环,并对每个循环进行计数。 4. 雨流计数结果的统计分析:根据雨流计数的结果,可以进行一系列统计分析,如载荷循环的频次统计、载荷循环的振幅与幅值统计、载荷循环的持续时间统计等,以获得载荷信号的疲劳特性。 5. 结果的可视化与评估:通过MATLAB中的数据可视化工具,对雨流计数结果进行可视化展示,如绘制载荷循环的振幅与幅值分布直方图、载荷循环的马尔柯夫链图等。同时,结合疲劳材料的疲劳性能指标,对载荷寿命进行评估。 总之,使用MATLAB进行雨流计数法的分析需要准备信号数据、设定阈值、编写计数程序、进行统计分析以及结果的可视化与评估等步骤。通过这些步骤,可以对载荷信号进行疲劳寿命评估,为结构的疲劳安全性提供参考。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值