关于 TWE-1 的使用
由于在做项目的时候需要与主题模型进行对比,被 TWE 这个坑困惑了好几天😫,在这里就做一下记录~
一、topical_word_embeddings 开源项目
- 链接:项目地址
- 注意:不需要再下载 gensim
- 关于使用以 TWE-1 为例子
- Get the gibbslda++, run it and get the tassign file and the wordmap.txt
- Use the command: python train.py wordmap_filename tassign_filename topic_number to run the TWE-1
- Output file are under the directory output: word_vector.txt and topic_vector.txt
二、gibbslda++ 的使用
- 链接:下载地址
- GibbsLDA 有很多的软件版本,比如 C++ 版,Java 版,Python 版,MatLab 版。各种版本对输入数据的要求可能还不一样,综合来看,C++ 版本最稳定,运算速度也最快。但是,C++ 版本一般在 Linux 上运行,如果在 Windows 下运行,需要安装 Visual Studio。因此本人采用了虚拟机。虚拟机安装教程
1 下载文件
- 把下载的文件放到 Linux 的一个目录下,如 /home/user/LDA/,然后执行如下命令
cd /home/user/LDA/
gunzip GibbsLDA++-0.2.tar.gz
tar -xf GibbsLDA++-0.2.tar
cd \GibbsLDA++-0.2
2 安装
因为缺少头文件,需要我们手动进行添加
- utils.cpp 找不到 'atof' 函数,补上
#include <cstdlib>
- lda.cpp 找不到 'printf' 函数,补上
#include <cstdio>
然后执行如下命令
make clean
make
3 语料准备
- 文件格式是 dat
- 文件内容
- 第 1 行是总共的文章篇数
- 第 2 行到第 M 行就是所有文章,每篇文章占一行。对于英文来说,每个词之间已经用空格分开了,但是中文不行,所以需要要先对文章进行分词和去停用词。
- 文章编码是 ANSI
- 文章中不能有空行
4 运行
lda -est [-alpha <double>] [-beta <double>] [-ntopics <int>] [-niters <int>] [-savestep <int>] [-twords <int>] -dfile <string>
例如
- 参数 alpha 是 0.5
- 参数 beta 是 0.1(这个也可以先不管)
- 产生 100 个 topic
- 运算迭代 1000 次
- 每迭代 100 次之后的结果都保存出来
- 每个 topic 包含出现概率最大的前 20 个词
- 要运算的文件是 /home/seven/LDA/test.dat
src/lda -est -alpha 0.5 -beta 0.1 -ntopics 100 -niters 1000 -savestep 100 -twords 20 -dfile /home/seven/LDA/test.dat
5 结果
结果文件存在测试文件所在的目录,对于本文就是 /home/seven/LDA/
- model-final.others 设置的参数
- model-final.phi 每个主题下的词概率分布
- model-final.tassign 每篇文章的各个词被指定的主题编号
- model-final.theta 每篇文章的主题概率分布
- model-final.twords 每个主题下的前 20 个主题词
- wordmap.txt 词典
三、TWE-1 的使用
- 为避免命名引起的错误,可以先把项目名称的‘-’给去掉
1 使用方法
- 在 Terminal 输入下列代码即可
python train.py wordmap.txt model-final.tassign 14
2 报错问题
(1)NameError: global name 'train_sentence_topic' is not defined
- word2vec_inner.pyx 文件是 c 写的,需要先编译!
- 先是装 cython 这个库,python2 的话就装 cython0.20.2 版本,python3 版本装最新的就行。
- 可以直接解析 pyx 文件(参考文档),本人这里通过新建文件夹里实现的!
① 在项目下新建文件夹 foo,并在该文件夹下新建 init.py
② 把 word2vec_inner.pyx 文件复制到该文件夹下
③ 在该文件夹下新建 setup.py 文件
from distutils.core import setup
from distutils.extension import Extension
from Cython.Build import cythonize
import numpy
extensions = [
Extension("word2vec_inner", ["word2vec_inner.pyx"],
include_dirs=[numpy.get_include()])
]
setup(
name="word2vec_inner",
ext_modules=cythonize(extensions),
)
④ 在 Terminal 终端下进入 foo 文件夹,并执行如下命令
python setup.py build_ext --inplace
这个时候会出现这样的错误:
fatal error C1083: Cannot open include file: 'voidptr.h': No such file or directory
解决方法:
- 把 gensim\models 文件夹下的 voidptr.h 文件复制到你所用的 VS 的 VC\include 文件夹下(如:C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\include文件夹下)。
- 之后编译成功,生成了 .c 与 .pyd 文件,我们主要调用的是 pyd 文件。
(2)ImportError: cannot import name fblas
这是版本原因引起的,我们需要把 pyx 文件中的第 20 行代码
from scipy.linalg.blas import fblas
修改成
import scipy.linalg.blas as fblas
即可
大功告成!!