gpt4 book ai didi

python - 在 Tensorboard Projector 中可视化 Gensim Word2vec 嵌入

转载 作者:太空狗 更新时间:2023-10-29 20:19:33 25 4
gpt4 key购买 nike

我只看到几个问题问这个问题,但还没有一个有答案,所以我想我不妨试试。我一直在使用 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 -> Projector

要加载元数据,魔术就发生在这里:

load_meta


提醒一下,一些 word2vec 嵌入投影也可以在 http://projector.tensorflow.org/ 上找到。

关于python - 在 Tensorboard Projector 中可视化 Gensim Word2vec 嵌入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50492676/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com