word2vec - 获取最近的单词

word2vec - get nearest words

读取tensorflow word2vec模型输出如何输出与特定词相关的词?

阅读src : https://github.com/tensorflow/tensorflow/blob/r0.11/tensorflow/examples/tutorials/word2vec/word2vec_basic.py可以查看图像是如何绘制的。

但是是否有一种数据结构(例如字典)作为训练模型的一部分而创建,允许访问最接近给定词的最近的 n 个词? 例如,如果 word2vec 生成图像:

图片来源:https://www.tensorflow.org/versions/r0.11/tutorials/word2vec/index.html

在这张图片中,单词 'to , he , it' 包含在同一个簇中,是否有一个函数将 'to' 作为输入并输出 'he , it'(在本例中为 n=2)?

这种方法一般适用于word2vec。如果您可以将 word2vec 保存在 text/binary 文件中,例如 google/GloVe word vector. Then what you need is just the gensim.

要安装:

Via github

Python代码:

from gensim.models import Word2Vec

gmodel=Word2Vec.load_word2vec_format(fname)
ms=gmodel.most_similar('good',10)
for x in ms:
    print x[0],x[1]

然而,这将搜索所有单词以提供结果,有近似最近邻 (ANN) 可以更快地为您提供结果,但会牺牲准确性。

在最新的gensim中,annoy is used to perform the ANN, see this notebooks了解更多信息。

Flann is another library for Approximate Nearest Neighbors.

gensim.models.Word2Vec 模型上获取 gensim and use similar_by_word 方法。

similar_by_word需要3个参数,

  1. 输入的单词
  2. n - 前 n 个相似词(可选,默认=10)
  3. restrict_vocab(可选,默认=None)

例子

import gensim, nltk

class FileToSent(object):
   """A class to load a text file efficiently """   
    def __init__(self, filename):
        self.filename = filename
        # To remove stop words (optional)
        self.stop = set(nltk.corpus.stopwords.words('english'))

    def __iter__(self):
        for line in open(self.filename, 'r'):
            ll = [i for i in unicode(line, 'utf-8').lower().split() if i not in self.stop]
            yield ll

然后根据你输入的句子(sentence_file.txt),

sentences = FileToSent('sentence_file.txt')
model = gensim.models.Word2Vec(sentences=sentences, min_count=2, hs=1)
print model.similar_by_word('hack', 2) # Get two most similar words to 'hack'
# [(u'debug', 0.967338502407074), (u'patch', 0.952264130115509)] (Output specific to my dataset)

我假设您不想使用 gensim,而更愿意坚持使用 tensorflow。那样的话,我会提供两种选择

选项 1 - Tensorboard:

如果您只是从探索的角度尝试这样做,我建议您使用 Tensorboard 的嵌入可视化工具来搜索最接近的嵌入。它提供了一个很酷的界面,您可以将余弦和欧几里得距离与一定数量的邻居一起使用。

Link to Tensorflow documentation

选项 2 - 直接计算

在 word2vec_basic.py 文件中,有一个例子说明了他们如何计算最接近的词,如果你稍微弄乱了这个函数,你可以继续使用它。在图表本身中发现以下内容:

# Compute the cosine similarity between minibatch examples and all embeddings.
norm = tf.sqrt(tf.reduce_sum(tf.square(embeddings), 1, keep_dims=True))
normalized_embeddings = embeddings / norm
valid_embeddings = tf.nn.embedding_lookup(
  normalized_embeddings, valid_dataset)
similarity = tf.matmul(
  valid_embeddings, normalized_embeddings, transpose_b=True)

然后,在训练期间(每 10000 步)他们 运行 下一段代码(在会话处于活动状态时)。当他们调用 similarity.eval() 时,它正在获取图中相似张量的文字 numpy 数组评估。

# Note that this is expensive (~20% slowdown if computed every 500 steps)
if step % 10000 == 0:
  sim = similarity.eval()
  for i in xrange(valid_size):
    valid_word = reverse_dictionary[valid_examples[i]]
    top_k = 8 # number of nearest neighbors
    nearest = (-sim[i, :]).argsort()[1:top_k+1]
    log_str = "Nearest to %s:" % valid_word
    for k in xrange(top_k):
      close_word = reverse_dictionary[nearest[k]]
      log_str = "%s %s," % (log_str, close_word)
    print(log_str)

如果你想为自己调整这个,你将不得不做一些技巧,将 reverse_dictionary[valid_examples[i]] 更改为你想要获得 k-closest 单词的 word/words idx .