1. 安装 gensim
source activate python362
conda install -n python362 gensim
2. 实操
2.1 基本数据(语料)
语料文件可以一行一行 ,也可以使用分词后的空格分割的文本
(python362) zjf@zhangjifeideMBP ~/Downloads cat ./tags
迷宫
养成
割草
卡通
3D
恶搞
古风
塔防迷宫
收集
教育
次世代
中国象棋
像素
精美
俄罗斯方块
剪影
坦克
反乌托邦
魔幻
街机
2.2 实例代码
# -*- coding: UTF-8 -*-
from gensim.models import word2vec
import logging
logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO)
sentences = word2vec.Text8Corpus("/Users/zjf/Downloads/tags")
model = word2vec.Word2Vec(sentences, min_count=0, size=10, window=5)
"""计算某个语料的词向量"""
say_vector = model[u'aa']
print say_vector
"""计算2个语料的相似度"""
say_similarity_a = model.similarity(u"3D", u"3D")
print say_similarity_a
"""遍历语料集合并写入文件"""
target_file = open('/Users/zjf/Downloads/tags_vector', 'w')
for key in sentences:
for single_key in key:
# print single_key
say_vector = model[single_key]
# print say_vector
target_line = ('%s' + ',' + '%s') % (single_key, say_vector)
print target_line
# print('%s' + '\t' + '%s') % (single_key, say_vector)
target_file.write(target_line.encode('utf-8'))
target_file.write('\n')
"""计算最相似"""
most_similari = model.most_similar(u"斗地主")
print most_similari
for a in most_similari:
for b in a:
print b
3. 常见报错
3.1 ImportError: cannot import name ‘show_config’ [duplicate]
issue:https://stackoverflow.com/questions/38699494/importerror-cannot-import-name-show-config
适用于所有报错的工程
原因:工程中有自己编写的名为 :numpy.py的文件,word2vec需要 numpy包下的文件,导致重名
解决 :修改自己 的文件名
3.2 raise RuntimeError(“you must first build vocabulary before training the model”) RuntimeError: you must first build vocabulary before training the model
min_count=x 是必加参数
4. 方法参数
· sentences:可以是一个·ist,对于大语料集,建议使用BrownCorpus,Text8Corpus或·ineSentence构建。
· sg: 用于设置训练算法,默认为0,对应CBOW算法;sg=1则采用skip-gram算法。
· size:是指特征向量的维度,默认为100。大的size需要更多的训练数据,但是效果会更好. 推荐值为几十到几百。
· window:表示当前词与预测词在一个句子中的最大距离是多少
· alpha: 是学习速率
· seed:用于随机数发生器。与初始化词向量有关。
· min_count: 可以对字典做截断. 词频少于min_count次数的单词会被丢弃掉, 默认值为5
· max_vocab_size: 设置词向量构建期间的RAM限制。如果所有独立单词个数超过这个,则就消除掉其中最不频繁的一个。每一千万个单词需要大约1GB的RAM。设置成None则没有限制。
· sample: 高频词汇的随机降采样的配置阈值,默认为1e-3,范围是(0,1e-5)
· workers参数控制训练的并行数。
· hs: 如果为1则会采用hierarchica·softmax技巧。如果设置为0(defau·t),则negative sampling会被使用。
· negative: 如果>0,则会采用negativesamp·ing,用于设置多少个noise words
· cbow_mean: 如果为0,则采用上下文词向量的和,如果为1(defau·t)则采用均值。只有使用CBOW的时候才起作用。
· hashfxn: hash函数来初始化权重。默认使用python的hash函数
· iter: 迭代次数,默认为5
· trim_rule: 用于设置词汇表的整理规则,指定那些单词要留下,哪些要被删除。可以设置为None(min_count会被使用)或者一个接受()并返回RU·E_DISCARD,uti·s.RU·E_KEEP或者uti·s.RU·E_DEFAU·T的函数。
· sorted_vocab: 如果为1(defau·t),则在分配word index 的时候会先对单词基于频率降序排序。
· batch_words:每一批的传递给线程的单词的数量,默认为10000
参考
https://github.com/tensorflow/tensorflow/blob/r1.10/tensorflow/examples/tutorials/word2vec/word2vec_basic.py https://github.com/tensorflow/models/tree/master/tutorials/embedding/word2vec.py