中文wikipead数据的LDA预处理

环境:Ubuntu 14.04, Gensim,  jieba

先中文分词:

python -m jieba wiki.zh.text.jian.utf-8 > cut_result.txt

抽取3万个文档:

head -n 30000 cut_result.txt > cut_small.txt

处理脚本如下:

from gensim import corpora

train_data = []
corpus1 = []
corpus2 = []

with open(‘cut_small.txt’, ‘r’) as f:
for i in f.readlines():
train_data.append(list(i.decode(‘utf8’).split(‘/’)))

dic = corpora.Dictionary(train)

corpus1 = [dic.doc2bow(text) for text in train_data]

with open(‘cut_small.txt’, ‘r’) as f:
for i in f.readlines():
corpus2.append([dic.token2id[j] for j in i.decode(‘utf8’).split(‘/’)])

 

数据预处理中英文wikipedia

环境:Ubuntu 14.04, Gensim,

处理脚本process_wiki.py:

 

 

 

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import logging
import os.path
import sys

from gensim.corpora import WikiCorpus

if __name__ == '__main__':
    program = os.path.basename(sys.argv[0])
    logger = logging.getLogger(program)

    logging.basicConfig(format='%(asctime)s: %(levelname)s: %(message)s')
    logging.root.setLevel(level=logging.INFO)
    logger.info("running %s" % ' '.join(sys.argv))

    # check and process input arguments
    if len(sys.argv) < 3:
        print globals()['__doc__'] % locals()
        sys.exit(1)
    inp, outp = sys.argv[1:3]
    space = " "
    i = 0

    output = open(outp, 'w')
    wiki = WikiCorpus(inp, lemmatize=False, dictionary={})
    for text in wiki.get_texts():
        output.write(space.join(text) + "\\n")
        i = i + 1
        if (i % 10000 == 0):
            logger.info("Saved " + str(i) + " articles")

    output.close()
    logger.info("Finished Saved " + str(i) + " articles")

下载中文和英文的wikipedia
wget https://dumps.wikimedia.org/enwiki/latest/enwiki-latest-pages-articles.xml.bz2
wget https://dumps.wikimedia.org/zhwiki/latest/zhwiki-latest-pages-articles.xml.bz2

方法一:

python process_wiki.py zhwiki-latest-pages-articles.xml.bz2 wiki.zh.text

方法二:

Wikipedia Extractor 是用 Python 写的一个维基百科抽取器,使用非常方便。

wget http://medialab.di.unipi.it/Project/SemaWiki/Tools/WikiExtractor.py
python WikiExtractor.py -cb1000M -o extracted  zhwiki-latest-pages-articles.xml.bz2
参数 -b1000M 表示以 1000M 为单位切分文件,默认是 500K。

 

 

将wiki.zh.text中的繁体字转化位简体字:

sudo apt-get install opencc

opencc -i wiki.zh.text -o wiki.zh.text.jian -c zht2zhs.ini

 

处理非utf-8字符

iconv -c -t UTF-8 < wiki.zh.text.jian > wiki.zh.text.jian.utf-8

 

 

 

基于搜索词做的推荐

环境:Oracle database 11g,  Gensim, jieba, spark 1.0

思路: 首先从数据仓库中抽取出每个人对应的搜索词集合, 然后对搜索词集合做分词处理,统计每个词的频率。 然后输出用户与分词处理后的词语的矩阵,其中搜索次数为矩阵中的数值。

步骤:
1. 在oracle数据库查出每个的搜索词集合
select employee_id, to_char(yd_concat(q_content)) from agg_kw_daily group by employee_id;

2. 分词处理,输出用户与分词处理后的词语的矩阵

from gensim import corpora
import jieba

train_set = []

q_content = [i.split(‘ ‘) for i in open(‘/u01/jerry/emp_query_conten.txt’).readlines()]
[train_set.append(list(jieba.cut(i[1]))) for i in q_content]

train_set2 = []
for i in train_set:
train_set2.append([j for j in i if j not in set([u’,’, u’_’, u’-‘, u’ ‘, u’.’, u”, u’不’, u’的’])])

dic = corpora.Dictionary(train_set2)
corpus = [dic.doc2bow(text) for text in train_set2]

corpus2 = []
for i in corpus:
corpus2.append([j for j in i if j[1] > 1])

import sys
reload(sys)
sys.setdefaultencoding(‘utf-8’)
output = open(‘/u01/jerry/qw_dic’, ‘w’)
for key, value in dic.iteritems():
output.write(str(key) + ‘ ‘ + value + ‘\n’)

for i in range(0, len(corpus2)):
for j in corpus2[i]:
print q_content[i][0], j[0], j[1]

output = open(‘/u01/jerry/emp_q_cnt’, ‘w’)
for i in range(0, len(corpus2)):
for j in corpus2[i]:
output.write(str(q_content[i][0]) + ‘ ‘ +  str(j[0]) + ‘ ‘ + str(j[1]) + ‘\n’)

3. 将输出的文件emp_q_cnt在spark mllib中计算,得出预测模型

import org.apache.spark.mllib.recommendation.ALS
import org.apache.spark.mllib.recommendation.Rating

val data = sc.textFile(“/home/cloudera/emp_q_cnt”)
val ratings = data.map(_.split(‘\t’) match { case Array(user,item,rate) => Rating(user.toInt, item.toInt, rate.toDouble)})

val rank = 10
val numIterations = 1000
val model = ALS.train(ratings, rank, numIterations, 0.01)

4. 查看某个用户对某一分词的预测值(用户10008, 分词2)

model.predict(sc.parallelize(Array((10008, 2)))).map{case Rating(user, item, rate) => ((user, item), rate)}.take(1)

Kaldi的rnnlm训练

环境: Ubuntu 12.04, Kaldi

深度学习在NLP上的应用(具体可参考这篇文章 http://licstar.net/archives/328) 中提到一个概念:词向量 (英文为distributed representation, word representation, word embeding中任一个)。在Mikolov 的 RNNLM中有涉及到到词向量的训练,其中Kaldi中有实现示例。

1. 切换到Kaldi目录/u01/kaldi/tools,未找到rnnlm目录。 可能是版本有些旧了, 直接从网上下载这个目录

svn co https://svn.code.sf.net/p/kaldi/code/trunk/tools/rnnlm-hs-0.1b

2.
cd rnnlm-hs-01.b
make
生成rnnlm执行文件

jerry@hq:/u01/kaldi/tools/rnnlm-hs-0.1b$ ./rnnlm
RNNLM based on WORD VECTOR estimation toolkit v 0.1b

Options:
Parameters for training:
-train <file>
Use text data from <file> to train the model
-valid <file>
Use text data from <file> to perform validation and control learning rate
-test <file>
Use text data from <file> to compute logprobs with an existing model
-rnnlm <file>
Use <file> to save the resulting language model
-hidden <int>
Set size of hidden layer; default is 100
-bptt <int>
Set length of BPTT unfolding; default is 3; set to 0 to disable truncation
-bptt-block <int>
Set period of BPTT unfolding; default is 10; BPTT is performed each bptt+bptt_block steps
-gen <int>
Sampling mode; number of sentences to sample, default is 0 (off); enter negative number for interactive mode
-threads <int>
Use <int> threads (default 1)
-min-count <int>
This will discard words that appear less than <int> times; default is 0
-alpha <float>
Set the starting learning rate; default is 0.1
-maxent-alpha <float>
Set the starting learning rate for maxent; default is 0.1
-reject-threshold <float>
Reject nnet and reload nnet from previous epoch if the relative entropy improvement on the validation set is below this threshold (default 0.997)
-stop <float>
Stop training when the relative entropy improvement on the validation set is below this threshold (default 1.003); see also -retry
-retry <int>
Stop training iff N retries with halving learning rate have failed (default 2)
-debug <int>
Set the debug mode (default = 2 = more info during training)
-direct-size <int>
Set the size of hash for maxent parameters, in millions (default 0 = maxent off)
-direct-order <int>
Set the order of n-gram features to be used in maxent (default 3)
-beta1 <float>
L2 regularisation parameter for RNNLM weights (default 1e-6)
-beta2 <float>
L2 regularisation parameter for maxent weights (default 1e-6)
-recompute-counts <int>
Recompute train words counts, useful for fine-tuning (default = 0 = use counts stored in the vocab file)

Examples:
./rnnlm -train data.txt -valid valid.txt -rnnlm result.rnnlm -debug 2 -hidden 200

3.  使用kaldi中的wsj示例
下载一个包含wsj的 git clone https://github.com/foundintranslation/Kaldi.git
将其中的cp wsj/s1 /u01/kaldi/egs/wsj/ -Rf
发现其中的wsj数据源是要用dvd光盘上的,没法获得,这条路走不通。

4. 到网站http://www.fit.vutbr.cz/~imikolov/rnnlm/下载

rnnlm-0.3e

Basic examples

这两个文件,其中有程序和示例, 解压Basic_examples,里面有数据文件data

jerry@hq:/u01/kaldi/tools/rnnlm-hs-0.1b$ ls /u01/jerry/simple-examples/data
ptb.char.test.txt  ptb.char.train.txt  ptb.char.valid.txt  ptb.test.txt  ptb.train.txt  ptb.valid.txt  README

开始训练词向量
jerry@hq:/u01/kaldi/tools/rnnlm-hs-0.1b$ ./rnnlm -train /u01/jerry/simple-examples/data/ptb.train.txt -valid /u01/jerry/simple-examples/data/ptb.valid.txt -rnnlm result.rnnlm -debug2 -hidden 100

Vocab size: 10000
Words in train file: 929589
Starting training using file /u01/jerry/simple-examples/data/ptb.train.txt
Iteration 0     Valid Entropy 9.457519
Alpha: 0.100000  ME-alpha: 0.100000  Progress: 99.11%  Words/thread/sec: 28.40k Iteration 1     Valid Entropy 8.416857
Alpha: 0.100000  ME-alpha: 0.100000  Progress: 99.11%  Words/thread/sec: 28.18k Iteration 2     Valid Entropy 8.203366
Alpha: 0.100000  ME-alpha: 0.100000  Progress: 99.11%  Words/thread/sec: 27.98k Iteration 3     Valid Entropy 8.090350
Alpha: 0.100000  ME-alpha: 0.100000  Progress: 99.11%  Words/thread/sec: 27.25k Iteration 4     Valid Entropy 8.026399
Alpha: 0.100000  ME-alpha: 0.100000  Progress: 99.11%  Words/thread/sec: 27.35k Iteration 5     Valid Entropy 7.979509
Alpha: 0.100000  ME-alpha: 0.100000  Progress: 99.11%  Words/thread/sec: 27.43k Iteration 6     Valid Entropy 7.949336
Alpha: 0.100000  ME-alpha: 0.100000  Progress: 99.11%  Words/thread/sec: 27.35k Iteration 7     Valid Entropy 7.931067  Decay started
Alpha: 0.050000  ME-alpha: 0.050000  Progress: 99.11%  Words/thread/sec: 28.55k Iteration 8     Valid Entropy 7.827513
Alpha: 0.025000  ME-alpha: 0.025000  Progress: 99.11%  Words/thread/sec: 28.37k Iteration 9     Valid Entropy 7.759574
Alpha: 0.012500  ME-alpha: 0.012500  Progress: 99.11%  Words/thread/sec: 28.45k Iteration 10    Valid Entropy 7.714383
Alpha: 0.006250  ME-alpha: 0.006250  Progress: 99.11%  Words/thread/sec: 28.51k Iteration 11    Valid Entropy 7.684731
Alpha: 0.003125  ME-alpha: 0.003125  Progress: 99.11%  Words/thread/sec: 28.64k Iteration 12    Valid Entropy 7.668839  Retry 1/2
Alpha: 0.001563  ME-alpha: 0.001563  Progress: 99.11%  Words/thread/sec: 28.25k Iteration 13    Valid Entropy 7.668437  Retry 2/2

 

jerry@hq:/u01/kaldi/tools/rnnlm-hs-0.1b$ ls -l
total 8184
-rw-rw-r– 1 jerry jerry   11358 Aug 25 15:08 LICENSE
-rw-rw-r– 1 jerry jerry     407 Aug 25 15:08 Makefile
-rw-rw-r– 1 jerry jerry    8325 Aug 25 15:08 README.txt
-rw-rw-r– 1 jerry jerry  109943 Aug 25 18:05 result.rnnlm
-rw-rw-r– 1 jerry jerry 8040020 Aug 25 18:05 result.rnnlm.nnet
-rwxrwxr-x 1 jerry jerry  142501 Aug 25 15:08 rnnlm
-rw-rw-r– 1 jerry jerry   33936 Aug 25 15:08 rnnlm.c
jerry@hq:/u01/kaldi/tools/rnnlm-hs-0.1b$

vi  result.rnnlm

</s> 42068
the 50770
<unk> 45020
N 32481
of 24400
to 23638
a 21196
in 18000
and 17474
‘s 9784

 

Gensim做中文主题模型(LDA)

环境: Ubuntu 12.04, gensim, jieba

中文语料来自http://www.sogou.com/labs/dl/c.html 的精简版(tar.gz格式) 24M
jerry@hq:/u01/jerry/Reduced$ ls
C000008  C000010  C000013  C000014  C000016  C000020  C000022  C000023  C000024

各个文件夹的分类:
C000007 汽车
C000008 财经
C000010 IT
C000013 健康
C000014 体育
C000016 旅游
C000020 教育
C000022 招聘
C000023 文化
C000024 军事

步骤如下:

import jieba, os
from gensim import corpora, models, similarities

train_set = []

walk = os.walk(‘/u01/jerry/Reduced’)
for root, dirs, files in walk:
for name in files:
f = open(os.path.join(root, name), ‘r’)
raw = f.read()
word_list = list(jieba.cut(raw, cut_all = False))
train_set.append(word_list)

dic = corpora.Dictionary(train_set)
corpus = [dic.doc2bow(text) for text in train_set]
tfidf = models.TfidfModel(corpus)
corpus_tfidf = tfidf[corpus]
lda = models.LdaModel(corpus_tfidf, id2word = dic, num_topics = 10)
corpus_lda = lda[corpus_tfidf]

>>> for i in range(0, 10):
…      print lda.print_topic(i)

0.000*康宁 + 0.000*sohu2 + 0.000*wmv + 0.000*bbn7 + 0.000*mmst + 0.000*cid + 0.000*icp + 0.000*沙尘 + 0.000*性骚扰 + 0.000*乌里韦
0.000*media + 0.000*mid + 0.000*stream + 0.000*bbn7 + 0.000*mmst + 0.000*sohu2 + 0.000*cid + 0.000*icp + 0.000*wmv + 0.000*that
0.012* + 0.000*米兰 + 0.000*老板 + 0.000*男人 + 0.000*女人 + 0.000*她 + 0.000*小说 + 0.000*病人 + 0.000*我 + 0.000*女性
0.002*& + 0.002*nbsp + 0.001*0 + 0.001*; + 0.001*西安 + 0.001*报名 + 0.001*1 + 0.001*∶ + 0.001*00 + 0.001*5
0.002*手机 + 0.002*孩子 + 0.001*球 + 0.001*国家队 + 0.001*胜 + 0.001*教练 + 0.001*; + 0.001*名单 + 0.001*阅读 + 0.001*高校
0.001*’ + 0.000* + 0.000*= + 0.000*var + 0.000*height + 0.000*width + 0.000*NewWin + 0.000*} + 0.000*{ + 0.000*+
0.003*  + 0.002*比赛 + 0.002*我 + 0.002*  + 0.001*; + 0.001*- + 0.001*, + 0.001*他 + 0.001*& + 0.001*―
0.000*航班 + 0.000*劳动合同 + 0.000*最低工资 + 0.000*农民工 + 0.000*养老保险 + 0.000*劳动者 + 0.000*用人单位 + 0.000*养老 + 0.000*上调 + 0.000*锦江
0.000*面板 + 0.000*碘 + 0.000*食物 + 0.000*维生素 + 0.000*营养 + 0.000*皮肤 + 0.000*蛋白质 + 0.000*药物 + 0.000*症状 + 0.000*体内
0.000* + 0.000*EMC + 0.000*包机 + 0.000*基金 + 0.000*陆纯初 + 0.000*南越 + 0.000*Kashya + 0.000*西沙群岛 + 0.000*Clariion + 0.000*西沙

感觉最终的主题模型不太理想, 可以需要多增加参数num_topics的数量。