搭建word2Vec模型

word2Vec模型

Posted by hjw on November 14, 2019

搭建词向量模型

相信学会深度学习的人都经常不可避免会遇到词语向量化的问题,而解决这类问题最简单的问题是采用独热码编码。但是当数量上升到100以上,独热码的维度是100维;如果数量再上升呢?显然可知这种方法是不行,幸运的是2013年,Google开源了一款词向量计算工具——word2Vec.word2Vec算法是采用浅层神经网络来训练。有兴趣可以自行了解一下背后算法.接下来介绍怎么使用word2Vec来训练模型。

正文

1.准备工作

  • 下载语料 wiki百科的语料库,大概1.5g左右(下载路径)
  • 下载WikiExtractor 专门用来提取维基百科语料中文章的工具(下载地址)
  • 下载OpenCC 由于维基百科中语料有繁体字,故可用Opencc来化繁为简(下载地址)
  • 安装分词工具 需要安装一种分词工具来切词(下载地址) jieba库 pip install jieba 或者hanlp库 pip install pyhanlp
  • 安装word2Vec库 安装gensim库,其有word2Vec的模型 由于直接pip install gensim会出现经常出现下载失败问题 故采用豆瓣网镜像下载 pip install -i https://pypi.douban.com/simple gensim

2.提取文章

  • 下载完WikiExtractor后,解压,使用WikiExtractor.py脚本,通过一下命令来提取文章 python WikiExtractor.py -b 500M -o zhwiki zhwiki-20180720-pages-articles.xml.bz2
  • 参数介绍
    • -b 提取文章后每个文章大小
    • -o 指定输出文件保存的目录
    • zhwiki-20180720-pages-articles.xml.bz2, 下载维基百科语料的地址
  • 使用WikiExtractor提取的文章格式如下: <doc id="" revid="" url="" title="">...<\doc>

3.中文简体和繁体转换

下载解压opencc文件,其文件opencc\share\opencc下有一系列配置文件,其中t2s.json是把繁体转为简体的文件。CMD下使用命令opencc -i 需要转换文件路径 -o 转换后文件路径 -c 配置文件路径(t2s.json的路径)可以把文件繁体转为简体

4.正则表达式提取文章内容

由于提取的文章包含许多<doc></doc>,故需要使用正则表达式进行过滤。

1
2
3
4
5
6
7
8
9
  file = open(read_filePath, "r", encoding="utf-8")
  ouputfile = open(save_filePath, "a+", encoding="utf-8")
  regex_str = "[^<doc.*>$]|[^</doc>$]"
  readLine = file.readline()
  while readLine:
      content = re.match(regex_str, readLine)
      if content:
          ouputfile.write(readLine)
      readLine = file.readline()

5.分词并合并文件

使用jieba分词工具, hanlp工具对文件进行分词处理并合并文件。

  • 加载去停止词
1
2
3
4
5
    stopWordList = set()
    for filepath in filepaths:
    with open(filepath,"r",encoding="utf-8") as f:
        for item in f:
            stopWordList.add(item.strip("\n"))
  • 使用jieba分词切词并保存
1
2
3
4
5
6
7
8
9
10
11
12
13
    file = open(filepath, "r", encoding="utf-8")
    output = open(savepath, "a+", encoding="utf-8")
    datas = file.readlines()
    content_line = ""
    for data in datas:
        items = jieba.cut(data.strip("\n"), cut_all=False)
        for item in items:
            if item not in stopWordList:
                content_line += item + " "
        output.write(content_line+"\n")
        content_line = ""
    file.close()
    output.close()

6.Word2Vec模型训练 —– 调用gensim的word2Vec模型,对已经分词好文件训练。时间大概为1个小时左右,具体训练情况与电脑配置有关

1
2
3
    sentences = word2vec.LineSentence(filePath)
    model = word2vec.Word2Vec(sentences,size=250)
    model.save(savePath)

7.word2Vec模型使用 —– 调用训练好模型,测试结果。

1
2
3
4
5
6
7
8
9
10
11
12
    model = models.Word2Vec.load("wordTovec\model\wiki.model")
    word1 = u'农业'
    word2 = u'嘉伟'
    if word1 in model:
        print (u"'%s'的词向量为: " % word1)
        print (model[word1])
    else:
        print (u'单词不在字典中!')
    result = model.most_similar(word2)
    print (u"\n与'%s'最相似的词为: " % word2)
    for e in result:
        print ('%s: %f' % (e[0], e[1]))

代码传送门