【问题标题】:Export gensim doc2vec embeddings into separate file to use with keras Embedding layer later将 gensim doc2vec 嵌入导出到单独的文件中,以便稍后与 keras 嵌入层一起使用
【发布时间】:2018-08-06 12:58:43
【问题描述】:

我对 gensim 有点陌生,现在我正在尝试解决涉及在 keras 中使用 doc2vec 嵌入的问题。我无法在 keras 中找到 doc2vec 的现有实现——据我所见,到目前为止,每个人都只是使用 gensim 来获取文档嵌入。

一旦我在 gensim 中训练了我的 doc2vec 模型,我需要以某种方式将嵌入权重从 genim 导出到 keras 中,但如何做到这一点还不是很清楚。我看到了

model.syn0

据说给出了 word2vec 嵌入权重(根据this)。但目前还不清楚如何对文档嵌入进行相同的导出。有什么建议吗?

我知道通常我可以直接从 gensim 模型中获取每个文档的嵌入,但我想稍后在 keras 中微调嵌入层,因为文档嵌入将用作更大任务的一部分,因此他们可能会被微调一下。

【问题讨论】:

标签: keras gensim word-embedding doc2vec


【解决方案1】:

我想通了。

假设您已经训练了 gensim 模型并使用字符串标签作为文档 ID:

#get vector of doc
model.docvecs['2017-06-24AEON']
#raw docvectors (all of them)
model.docvecs.doctag_syn0
#docvector names in model
model.docvecs.offset2doctag

假设您的 DataFrame df 包含所有文档,您可以按如下方式将此文档向量导出到 keras 嵌入层。请注意,在嵌入矩阵中,您只需要传递整数作为输入。我使用数据框中的原始数字作为输入文档的 id。另请注意,嵌入层需要不触及索引 0 - 它保留用于屏蔽,因此当我将 doc id 作为输入传递给我的网络时,我需要确保它是 >0

#creating embedding matrix
embedding_matrix = np.zeros((len(df)+1, text_encode_dim))
for i, row in df.iterrows():
    embedding = modelDoc2Vec.docvecs[row['docCode']]
    embedding_matrix[i+1] = embedding

#input with id of document
doc_input = Input(shape=(1,),dtype='int16', name='doc_input')
#embedding layer intialized with the matrix created earlier
embedded_doc_input = Embedding(output_dim=text_encode_dim, input_dim=len(df)+1,weights=[embedding_matrix], input_length=1, trainable=False)(doc_input)

更新

2017 年末之后,随着 Keras 2.0 API 的引入,最后一行应更改为:

embedded_doc_input = Embedding(output_dim=text_encode_dim, input_dim=len(df)+1,embeddings_initializer=Constant(embedding_matrix), input_length=1, trainable=False)(doc_input)

【讨论】:

  • 我的印象是 keras.layers.Embeddingweights 的格式如果你检查这个 (keras.io/layers/embeddings) 和这个 (github.com/tensorflow/tensorflow/issues/14392) 就会被弃用
  • @PoeteMaudit 你是对的,它已经改变了一点。现在最后一行而不是 weights = [embedding_matrix] 我们应该做 embeddings_initializer=Constant(embedding_matrix)。更新了答案,感谢您的注意
  • 酷(点赞)。老实说,我没有测试weights 参数当前是否有效。我刚刚看到这个人的帖子,他声称它不起作用。可能weights 参数仍然有效?
  • 我无法理解InputInput(shape=(1,),dtype='int16', name='doc_input') 行中是什么
  • @SaurabhVerma 只是文档列表中的行号。所以我在数据框中为我的网络提供了文档的整数 id - 嵌入比仅仅根据文档的整数获取所需的嵌入更晚。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-10-27
  • 2019-09-07
  • 2018-08-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-02-07
相关资源
最近更新 更多