---
title: "CRF++使用"
author: "vergilwang"
date: "2012-12-28T11:01:00Z"
tags: []
categories: ["开源软件"]
slug: "crf"
draft: false
lastmod: "2014-02-15T15:45:39Z"
id: 2011289
url: "https://vergilwang.iteye.com/blog/2011289"
---

前段时间写了[中文分词的一些记录](http://blog.csdn.net/marising/archive/2009/04/16/4083650.aspx)里面提到了CRF的分词方法，近段时间又研究了一下，特把方法写下来，以备忘，另外，李沫南同学优化过CRF++，见：[http://www.coreseek.cn/opensource/CRF/](http://www.coreseek.cn/opensource/CRF/)。我觉得CRF++还有更大的优化空间，以后有时间再搞。

 

 

**1 下载和安装**

CRF的概念，请google，我就不浪费资源啦。官方地址如下：http://crfpp.sourceforge.net/

我用的是Ubutnu，所以，下载的是源码：http://sourceforge.net/projects/crfpp/files/ 下载[CRF++-0.54.tar.gz](http://sourceforge.net/projects/crfpp/files/crfpp/0.54/CRF%2B%2B-0.54.tar.gz/download "/crfpp/0.54/CRF++-0.54.tar.gz:  released on 2010-05-15")

没有gcc/g++/make请安装  
% ./configure  
% make\[如果path.h报错 加上#inlcude&lt;iostream&gt;头文件]  
% sudo make install

**2 测试和体验**  
在源码包中有example，可以执行./exec.sh体验一下  
exec.sh #训练和测试脚本  
template #模板文件  
test.data #测试文件  
train.data #训练文件  
可以打开看看

**3 语料整理和模板编写**

我采用的是6Tag和6Template的方式  
S，单个词；B，词首；E，词尾；M1/M2/M，词中

1个字的词：  
和 S  
2个字的词(注意是实际上是一个字一行，我为了排版，改为横排的了)：  
中 B 国 E  
3个字的词：  
进 B 一 M 步 E  
5个字的词：  
发 B 展 M1 中 M2 国 M 家 E  
跟多字的词  
中 B 华 M1 人 M2 民 M 共 M 和 M国 E  
标点符号作为单词（S表示）

从[bamboo](http://code.google.com/p/nlpbamboo/)项目中下载：people-daily.txt.gz  
pepoledata.py文件

**\[python]**[view plain](http://blog.csdn.net/marising/article/details/5769653 "view plain")[copy](http://blog.csdn.net/marising/article/details/5769653 "copy")

 

001. #!/usr/bin/python
002. #-\*-coding:utf-8-\*-
003. importsys
004. #home\_dir="D:/source/NLP/people\_daily//"
005. home\_dir="/home/lhb/workspace/CRF\_data/"
006. defsplitWord(words):
007. uni=words.decode('utf-8')
008. li=list()
009. foruinuni:
010. li.append(u.encode('utf-8'))
011. returnli
012. #4tag
013. #S/B/E/M
014. defget4Tag(li):
015. length=len(li)
016. #printlength
017. iflength==1:
018. return\['S']
019. eliflength==2:
020. return\['B','E']
021. eliflength&gt;2:
022. li=list()
023. li.append('B')
024. foriinrange(0,length-2):
025. li.append('M')
026. li.append('E')
027. returnli
028. #6tag
029. #S/B/E/M/M1/M2
030. defget6Tag(li):
031. length=len(li)
032. #printlength
033. iflength==1:
034. return\['S']
035. eliflength==2:
036. return\['B','E']
037. eliflength==3:
038. return\['B','M','E']
039. eliflength==4:
040. return\['B','M1','M','E']
041. eliflength==5:
042. return\['B','M1','M2','M','E']
043. eliflength&gt;5:
044. li=list()
045. li.append('B')
046. li.append('M1')
047. li.append('M2')
048. foriinrange(0,length-4):
049. li.append('M')
050. li.append('E')
051. returnli
052. defsaveDataFile(trainobj,testobj,isTest,word,handle,tag):
053. ifisTest:
054. saveTrainFile(testobj,word,handle,tag)
055. else:
056. saveTrainFile(trainobj,word,handle,tag)
057. defsaveTrainFile(fiobj,word,handle,tag):
058. iflen(word)&gt;0:
059. wordli=splitWord(word)
060. iftag=='4':
061. tagli=get4Tag(wordli)
062. iftag=='6':
063. tagli=get6Tag(wordli)
064. foriinrange(0,len(wordli)):
065. w=wordli\[i]
066. h=handle
067. t=tagli\[i]
068. fiobj.write(w+'/t'+h+'/t'+t+'/n')
069. else:
070. #print'Newline'
071. fiobj.write('/n')
072. #B,M,M1,M2,M3,E,S
073. defconvertTag(tag):
074. fiobj=open(home\_dir+'people-daily.txt','r')
075. trainobj=open(home\_dir+tag+'.train.data','w')
076. testobj=open(home\_dir+tag+'.test.data','w')
077. arr=fiobj.readlines()
078. i=0
079. forainarr:
080. i+=1
081. a=a.strip('/r/n/t')
082. words=a.split('')
083. test=False
084. ifi%10==0:
085. test=True
086. forwordinwords:
087. word=word.strip('/t')
088. iflen(word)&gt;0:
089. i1=word.find('[')
090. ifi1&gt;=0:
091. word=word\[i1+1:]
092. i2=word.find(']')
093. ifi2&gt;0:
094. word=word\[:i2]
095. word\_hand=word.split('/')
096. w,h=word\_hand
097. #printw,h
098. ifh=='nr':#renmin
099. #print'NR',w
100. ifw.find('·')&gt;=0:
101. tmpArr=w.split('·')
102. fortmpintmpArr:
103. saveDataFile(trainobj,testobj,test,tmp,h,tag)
104. continue
105. ifh!='m':
106. saveDataFile(trainobj,testobj,test,w,h,tag)
107. ifh=='w':
108. saveDataFile(trainobj,testobj,test,"","",tag)#split
109. trainobj.flush()
110. testobj.flush()
111. if\_\_name\_\_=='\_\_main\_\_':
112. iflen(sys.argv)&lt;2:
113. print'tag\[6,4]convertrawdatatotrain.dataandtag.test.data'
114. else:
115. tag=sys.argv\[1]
116. convertTag(tag)

下载下来并解压，然后用脚本整理数据，注意home\_dir改为语料的目录：  
python ./peopledata.py 6

90%数据作为训练数据，10%的数据作为测试数据，生成的文件如：  
6.test.data  
6.train.data

模板文件的写法如下  
template：

**\[python]**[view plain](http://blog.csdn.net/marising/article/details/5769653 "view plain")[copy](http://blog.csdn.net/marising/article/details/5769653 "copy")

 

1. #Unigram
2. U00:%x\[-1,0]
3. U01:%x\[0,0]
4. U02:%x\[1,0]
5. U03:%x\[-1,0]/%x\[0,0]
6. U04:%x\[0,0]/%x\[1,0]
7. U05:%x\[-1,0]/%x\[1,0]
8. #Bigram
9. B

%x\[row,column]代表的是行和列，\[-1,0]表示前1个字的第1列，［0，0］当前字的第1列，［1，0］后1个字的第1列

**4 执行和结果查看**  
6exec.sh文件

**\[python]**[view plain](http://blog.csdn.net/marising/article/details/5769653 "view plain")[copy](http://blog.csdn.net/marising/article/details/5769653 "copy")

 

1. #!/bin/sh
2. ./crf\_learn-f3-c4.0template6.train.data6.model&gt;6.train.rst
3. ./crf\_test-m6.model6.test.data&gt;6.test.rst
4. ./crfeval.py6.test.rst
5. #./crf\_learn-aMIRA-f3templatetrain.datamodel
6. #./crf\_test-mmodeltest.data
7. #rm-fmodel

WordCount from test result: 109805  
WordCount from golden data: 109948  
WordCount of correct segs : 106145  
P = 0.966668, R = 0.965411, F-score = 0.966039

**5 调整Tag和模板**  
4 Tag S/B/M/E 比 6Tag 去掉了M1和M2  
python ./peopledata.py 4  
4exec.sh文件为

**\[python]**[view plain](http://blog.csdn.net/marising/article/details/5769653 "view plain")[copy](http://blog.csdn.net/marising/article/details/5769653 "copy")

 

1. #!/bin/sh
2. ./crf\_learn-f3-c4.0template4.train.data4.model&gt;4.train.rst
3. ./crf\_test-m4.model4.test.data&gt;4.test.rst
4. ./crfeval.py4.test.rst

4Tag的效果为  
[lhb@localhost:~/workspace/CRF\_data$](mailto:lhb@localhost:~/workspace/CRF_data%24)./crfeval.py 4.test.rst  
ordCount from test result: 109844  
WordCount from golden data: 109948  
WordCount of correct segs : 105985  
P = 0.964868, R = 0.963956, F-score = 0.964412

 

6Tag的效果比4Tag有细微的差距，当然是6Tag好。

6Tag 训练时间为  
10062.00s  
4tag的训练时间为  
4208.71s

6Tag的标注方法差异

1)把M放在E之前：  
发 B 展 M1 中 M2 国 M 家 E  
2)把M放在B后  
发 B 展 M 中 M1 国 M2 家 E  
3)把M放在M1和M2之间：  
发 B 展 M1 中 M 国 M2 家 E  
第1种方式效果最好，有细微的差距。  
template的编写

我尝试过12行模板的编写，把词性作为一个计算因素，但是速度实在是很慢，没跑完，我就关机了。效果应该比6 template要好，可以尝试以下。

**\[python]**[view plain](http://blog.csdn.net/marising/article/details/5769653 "view plain")[copy](http://blog.csdn.net/marising/article/details/5769653 "copy")

 

01. #Unigram
02. U00:%x\[-1,1]
03. U01:%x\[0,1]
04. U02:%x\[1,1]
05. U03:%x\[-1,1]/%x\[0,1]
06. U04:%x\[0,1]/%x\[1,1]
07. U05:%x\[-1,1]/%x\[1,1]
08. U06:%x\[-1,0]
09. U07:%x\[0,0]
10. U08:%x\[1,0]
11. U09:%x\[-1,0]/%x\[0,0]
12. U010:%x\[0,0]/%x\[1,0]
13. U011:%x\[-1,0]/%x\[1,0]
14. #Bigram
15. B

 

 

有某位同学问我要crfeval.py文件，特放出如下：

 

 

**\[python]**[view plain](http://blog.csdn.net/marising/article/details/5769653 "view plain")[copy](http://blog.csdn.net/marising/article/details/5769653 "copy")

 

01. #!/usr/bin/python
02. #-\*-coding:utf-8-\*-
03. importsys
04. if\_\_name\_\_=="\_\_main\_\_":
05. try:
06. file=open(sys.argv\[1],"r")
07. except:
08. print"resultfileisnotspecified,oropenfailed!"
09. sys.exit()
10. wc\_of\_test=0
11. wc\_of\_gold=0
12. wc\_of\_correct=0
13. flag=True
14. forlinfile:
15. ifl=='/n':continue
16. \_,\_,g,r=l.strip().split()
17. ifr!=g:
18. flag=False
19. ifrin('E','S'):
20. wc\_of\_test+=1
21. ifflag:
22. wc\_of\_correct+=1
23. flag=True
24. ifgin('E','S'):
25. wc\_of\_gold+=1
26. print"WordCountfromtestresult:",wc\_of\_test
27. print"WordCountfromgoldendata:",wc\_of\_gold
28. print"WordCountofcorrectsegs:",wc\_of\_correct
29. #查全率
30. P=wc\_of\_correct/float(wc\_of\_test)
31. #查准率，召回率
32. R=wc\_of\_correct/float(wc\_of\_gold)
33. print"P=%f,R=%f,F-score=%f"%(P,R,(2\*P\*R)/(P+R))