我想通了。
假设您已经训练了 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)