在 Tensorboard Projector 中可视化 Gensim Word2vec 嵌入

Visualize Gensim Word2vec Embeddings in Tensorboard Projector

我只看到几个问题问这个问题,其中 none 个已经有了答案,所以我想我不妨试试。我一直在使用 gensim 的 word2vec 模型来创建一些向量。我将它们导出为文本,并尝试将其导入到嵌入投影仪的 tensorflow 实时模型中。一个问题。 没用。它告诉我张量格式不正确。所以,作为初学者,我想我会向一些更有经验的人请教可能的解决方案。
相当于我的代码:

import gensim
corpus = [["words","in","sentence","one"],["words","in","sentence","two"]]
model = gensim.models.Word2Vec(iter = 5,size = 64)
model.build_vocab(corpus)
# save memory
vectors = model.wv
del model
vectors.save_word2vec_format("vect.txt",binary = False)

创建模型,保存向量,然后在制表符分隔的文件中打印出漂亮漂亮的结果,其中包含所有维度的值。我知道如何做我正在做的事情,我只是无法弄清楚我将它放入 tensorflow 的方式有什么问题,因为据我所知,与此相关的文档非常稀少。
向我提出的一个想法是实施适当的 tensorflow 代码,但我不知道如何编写代码,只需在现场演示中导入文件即可。

编辑:我现在有一个新问题。我的向量所在的对象是不可迭代的,因为 gensim 显然决定制作自己的数据结构,这些结构与我正在尝试做的不兼容。
行。也完成了!感谢您的帮助!

你说的是有可能的。你必须记住的是,Tensorboard 从保存的 tensorflow 二进制文件中读取,这些二进制文件代表你在磁盘上的变量。

More information on saving and restoring tensorflow graph and variables here

因此,主要任务是获取嵌入作为保存的 tf 变量。

Assumptions:

  • in the following code embeddings is a python dict {word:np.array (np.shape==[embedding_size])}

  • python version is 3.5+

  • used libraries are numpy as np, tensorflow as tf

  • the directory to store the tf variables is model_dir/


第 1 步:堆叠嵌入以获得单个 np.array

embeddings_vectors = np.stack(list(embeddings.values(), axis=0))
# shape [n_words, embedding_size]

第 2 步:将 tf.Variable 保存到磁盘

# Create some variables.
emb = tf.Variable(embeddings_vectors, name='word_embeddings')

# Add an op to initialize the variable.
init_op = tf.global_variables_initializer()

# Add ops to save and restore all the variables.
saver = tf.train.Saver()

# Later, launch the model, initialize the variables and save the
# variables to disk.
with tf.Session() as sess:
   sess.run(init_op)

# Save the variables to disk.
   save_path = saver.save(sess, "model_dir/model.ckpt")
   print("Model saved in path: %s" % save_path)

model_dir should contain files checkpoint, model.ckpt-1.data-00000-of-00001, model.ckpt-1.index, model.ckpt-1.meta


第 3 步:生成 metadata.tsv

要拥有漂亮的带标签的嵌入云,您可以为张量板提供制表符分隔值 (tsv) 形式的元数据 (cf. here)。

words = '\n'.join(list(embeddings.keys()))

with open(os.path.join('model_dir', 'metadata.tsv'), 'w') as f:
   f.write(words)

# .tsv file written in model_dir/metadata.tsv

第 4 步:可视化

运行 $ tensorboard --logdir model_dir -> 投影仪.

要加载元数据,神奇的地方就在这里:


提醒一下,一些 word2vec 嵌入投影也可用于 http://projector.tensorflow.org/

Gensim 实际上有官方方法可以做到这一点。

Documentation about it

以上答案对我不起作用。我发现这个脚本非常有用(将来会添加到 gensim)Source

将数据转换为元数据:

model = gensim.models.Word2Vec.load_word2vec_format(model_path, binary=True)
with open( tensorsfp, 'w+') as tensors:
    with open( metadatafp, 'w+') as metadata:
         for word in model.index2word:
           encoded=word.encode('utf-8')
           metadata.write(encoded + '\n')
           vector_row = '\t'.join(map(str, model[word]))
           tensors.write(vector_row + '\n')

或者关注这个gist

gemsim 提供了将 word2vec 转换为 tf 投影仪文件的方法

python -m gensim.scripts.word2vec2tensor -i ~w2v_model_file -o output_folder                                

添加投影仪网站,上传元数据