用中文把玩Google开源的Deep-Learning项目word2vec

本文转载自http://www.cnblogs.com/wowarsenal/p/3293586.html

google最近新开放出word2vec项目,该项目使用deep-learning技术将term表示为向量,由此计算term之间的相似度,对term聚类等,该项目也支持phrase的自动识别,以及与term等同的计算。

word2vec项目首页:https://code.google.com/p/word2vec/,文档比较详尽,很容易上手。可能对于不同的系统和gcc版本,需要稍微改一下代码和makefile。具体到我的mac系统,源代码中所有#include <malloc.h>的地方都需要改成#include <stdlib.h>,makefile编译选项中的-Ofast要更改为-O2,-march=native -Wno-unused-result这两个编译选项都不认,使用予以删除。直接make,按照它的文档提示运行即可。

本文主要说说如何使用word2vec处理中文语料。首先我们打开demo-word.sh看看,脚本开始其实就是去下载语料并解压成text8文件,这份文件约96M大小,less看看其实就是纯文本的英文,每个单词之间有空格隔开:

 anarchism originated as a term of abuse first used against early working class radicals including the diggers of the english revolution and the sans culottes of the french revolution whilst the term is still used in a pejorative way to describe any act that used violent means to destroy the organization of society it has also been taken up as a positive label by self defined anarchists the word anarchism is derived from the greek without archons ruler chief king anarchism as a political philosophy is the belief that rulers are unnecessary and should be abolished although there... 

所以如果我们有一份分过词的中文语料,每个词(term)之间用空格隔开,就可以用word2vec来处理了。

分词我们使用开源的ansj_seg项目,该项目是用java实现中科院ictclas中的算法(下载ictclas没有源码,且linux 64bit的版本在64位mac下链接库报错,应该是不兼容,ictclas官方并未提供mac 64bit的版本)。ansj_seg的官方主页在:https://github.com/ansjsun/ansj_seg,运行:

git clone https://github.com/ansjsun/ansj_seg

下载该项目会报类似下面的错误:

error: RPC failed; result=22, HTTP code = 413 | 116 KiB/s   
fatal: The remote end hung up unexpectedly
Writing objects: 100% (2504/2504), 449.61 MiB | 4.19 MiB/s, done.
Total 2504 (delta 1309), reused 2242 (delta 1216)
fatal: The remote end hung up unexpectedly

在stackoverflow上搜了下解决办法,需要执行下面的命令,配置git的缓冲区大小:

git config --global http.postBuffer 524288000

如果仍然失败的话,可以在ansj_seg主页直接下载项目的.zip文件,解压即可。

如果用eclipse打开该项目,还需要依赖一个tree-split-word的项目,这是一个Trie树实现用来查词表的项目,ansj_seg主页目前给出的链接已经失效,在github搜索treesplitword可以找到这个项目,下载后打成jar包,加入到ansj_seg的项目中,发现仍然有错,原因是当前的tree-split-word的很多接口都与ansj_seg中使用的不兼容了。

这时发现ansj_seg是一个maven项目,直接使用mvn compile命令编译,会自动下载其所需依赖,整个编译过程没有报错,最终取得成功。从中提取出项目使用的tree_split-1.0.1.jar,加入到eclipse项目中,重新build一下,eclipse中的红叉消失。

到ansj_seg项目中的src/demo/java/下的org.ansj.demo包中跑一跑每一个demo文件,会遇到以下问题:

1. 报错找不到library.properties文件,将项目根目录下的library.properties.bak copy成library.properties,并注意添加eclipse项目中的classpath,可以解决这个问题;

2. 初始化词典时会报找不到nature/nature.map文件(词性映射文件,ansj_seg不仅有分词的功能,还能词性标注),find . -iname nature.map会发现其实这个文件是存在的,可以直接加eclipse的classpath指向ansj_seg/src/main/resources目录即可;

3. 跑demo时可能会报OutOfMemory的错误,加载词典可能超出了eclipse的默认jvm大小,可以在run as时,设定argument,-Xmx512M -Xms512M即可。

解决上述问题后,除了demo中需要读文件的没有,其他demo都能成功运行。ansj_seg的接口也非常简洁易用,很容易编程读取自己的语料文件进行分词。

最后我们需要解决的就是语料问题。搜狗实验室公布了许多有用的语料,我使用其中的全网新闻数据:http://www.sogou.com/labs/dl/ca.html,填写姓名邮箱申请得到用户名密码,可以获得一个ftp下载地址。首先下载一个迷你语料news_tensite_xml.smarty.tar.gz做做简单实验,解压文件可以看到文本的格式,很容易理解,该文件是gbk编码的,可以转成utf-8编码再进行处理。基于这个迷你语料和ansj_seg编程分词,生成word2vec的输入文件。代码如下:

复制代码
 1 package org.ansj.demo;
 2 
 3 import java.io.BufferedReader;
 4 import java.io.FileOutputStream;
 5 import java.io.IOException;
 6 import java.io.PrintWriter;
 7 import java.io.OutputStreamWriter;
 8 import java.util.HashSet;
 9 import java.util.List;
10 import java.util.Set;
11 
12 import love.cq.util.IOUtil;
13 
14 import org.ansj.domain.Term;
15 import org.ansj.splitWord.analysis.ToAnalysis;
16 
17 public class MyFileDemo {
18     
19     public static final String TAG_START_CONTENT = "<content>";
20     public static final String TAG_END_CONTENT = "</content>";
21     
22     public static void main(String[] args) {
23         String temp = null ;
24         
25         BufferedReader reader = null;
26         PrintWriter pw = null;
27         try {
28             reader = IOUtil.getReader("corpus.txt", "UTF-8") ;
29             ToAnalysis.parse("test 123 孙") ;
30             pw = new PrintWriter(new OutputStreamWriter(new FileOutputStream
31                     ("resultbig.txt"), "UTF-8"), true);
32             long start = System.currentTimeMillis()  ;
33             int allCount =0 ;
34             int termcnt = 0;
35             Set<String> set = new HashSet<String>();
36             while((temp=reader.readLine())!=null){
37                 temp = temp.trim();
38                 if (temp.startsWith(TAG_START_CONTENT)) {
39                     int end = temp.indexOf(TAG_END_CONTENT);
40                     String content = temp.substring(TAG_START_CONTENT.length(), end);
41                     //System.out.println(content);
42                     if (content.length() > 0) {
43                         allCount += content.length() ;
44                         List<Term> result = ToAnalysis.parse(content);
45                         for (Term term: result) {
46                             String item = term.getName().trim();
47                             if (item.length() > 0) {
48                                 termcnt++;
49                                 pw.print(item.trim() + " ");
50                                 set.add(item);
51                             }
52                         }
53                         pw.println();
54                     }
55                 }
56             }
57             long end = System.currentTimeMillis() ;
58             System.out.println("共" + termcnt + "个term," + set.size() + "个不同的词,共 "
59                     +allCount+" 个字符,每秒处理了:"+(allCount*1000.0/(end-start)));
60         } catch (IOException e) { 
61             e.printStackTrace();
62         } finally {
63             if (null != reader) {
64                 try {
65                     reader.close();
66                 } catch (IOException e) {
67                     e.printStackTrace();
68                 }
69             }
70             if (null != pw) {
71                 pw.close();
72             }
73         }
74     }
75 }
复制代码

生成的resultbig.txt即为分好词用空格隔开的语料,使用word2vec,运行:

./word2vec -train resultbig.txt -output vectors.bin -cbow 0 -size 200 -window 5 -negative 0 -hs 1 -sample 1e-3 -threads 12 -binary 1
./distance vectors.bin

vectors.bin是word2vec处理resultbig.txt生成的term的向量文件,./distance命令加载该文件计算term之间的距离。mini文件能够跑通,但距离没有什么意义,因为语料实在太少了(word2vec中说语料越多效果越好)。

这时可以放心的下载700+M的全网新闻语料了,最好做下预处理只取出有content的行并转码,限于本人的机器,我只取出前20W行进行分词:

cat news_tensite_xml.dat | iconv -f gbk -t utf-8 -c | grep "<content>" | head -n 200000 > corpus.txt

corpus.txt大小是200+M,分词后有4000W+的term,使用word2vec处理,最后得到的结果还有点意思:

 

 

 

200+M的语料,这个结果是不是相当凑合了?小伙伴们,快玩起来吧!剩下phrase,classify的功能各位可以自行探索:)


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值