I. *_*lum 10 python gensim tensorflow tensorboard word-embedding
我只看到了几个问这个问题的问题,但他们都没有答案,所以我想我也可以试试.我一直在使用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)
Run Code Online (Sandbox Code Playgroud)
这将创建模型,保存向量,然后在带有所有维度值的制表符分隔文件中将结果打印出来.我理解如何做我正在做的事情,我只是无法弄清楚我把它放在tensorflow中的方式有什么问题,因为据我所知,有关这方面的文档非常缺乏.
提交给我的一个想法是实现适当的tensorflow代码,但我不知道如何编写代码,只是导入实时演示中的文件.
编辑:我现在有一个新问题.我有载体的对象是不可迭代的,因为gensim显然决定使自己的数据结构与我正在尝试的不兼容.
好.做完了!谢谢你的帮助!
syl*_*ong 11
你所描述的是可能的.您必须记住的是Tensorboard从保存的tensorflow二进制文件中读取,这些二进制文件代表磁盘上的变量.
有关在此处保存和恢复张量流图和变量的更多信息
因此,主要任务是将嵌入作为保存的tf变量.
假设:
在下面的代码中
embeddings
是一个python dict{word:np.array (np.shape==[embedding_size])}
python版本是3.5+
用过的图书馆是
numpy as np
,tensorflow as tf
存储tf变量的目录是
model_dir/
np.array
embeddings_vectors = np.stack(list(embeddings.values(), axis=0))
# shape [n_words, embedding_size]
Run Code Online (Sandbox Code Playgroud)
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)
Run Code Online (Sandbox Code Playgroud)
model_dir
应包含的文件checkpoint
,model.ckpt-1.data-00000-of-00001
,model.ckpt-1.index
,model.ckpt-1.meta
metadata.tsv
要拥有一个漂亮的标记嵌入云,您可以提供带有元数据的张量板作为制表符分隔值(tsv)(参见 此处).
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
Run Code Online (Sandbox Code Playgroud)
运行$ tensorboard --logdir model_dir
- > 投影仪.
要加载元数据,神奇的事情发生在这里:
提醒一下,http: //projector.tensorflow.org/上也提供了一些word2vec嵌入投影.
归档时间: |
|
查看次数: |
3469 次 |
最近记录: |