gensim是python下一个极易上手的主题模型程序库(topic model),网址在:http://radimrehurek.com/gensim/index.html
我本机用的python2.7,需安装setuptools或者pip,然后通过这2个工具安装numpy和scipy,因为gensim里面依赖科学/数值计算。其中scipy还需要安装BLAS和LAPACK这2个包,所以说依赖的库非常之多。在安装LAPACK的时候还要注意修改make.inc中的编译参数,增加-fPIC,否则scipy安装会报错。这其中的弯路暂且不表,重点介绍安装完之后的怎么玩gensim。
gensim支持的模型由LSI,LDA,TFIDF等模型,由于主题模型要用到语料,所以在做预研的时候可以结合NLTK的丰富语料库来getting started。
以LSI为例,整个流程包括数据读取/预处理、训练和预测,数据读取和处理使用gensim的corpus包和dictionary包进行序列化,转成TFIDF格式后,交给model下的LsiModel训练,代码如下:
主函数
'''
Created on 2013-6-13
@author: william.hw
'''
import gensim, aequerycluster, logging, nltk, sys
def notpurepunc(word):
for ch in word:
if (ch <= '9' and ch >= '0') or (ch <= 'z' and ch >= 'a'):
return True
return False
if __name__ == '__main__':
logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO)
logger = logging.getLogger('aequerycluster')
dictpath = 'aequerycluster.dict'
modelpath = 'aequerycluster.model'
logger.info("start...")
hivefile = sys.argv[1]
uniqlevel = sys.argv[2]
texts = []
count = 10
with open(hivefile) as finput:
for line in finput:
fields