如何在Keras中使用我自己的句子嵌入?

时间:2018-10-08 14:57:03

标签: keras nlp lstm word-embedding sentence-similarity

我是Keras的新手,我创建了自己的形状为tf_idf的句子嵌入(no_sentences,embedding_dim)。我正在尝试将此矩阵添加为LSTM层的输入。我的网络看起来像这样:

q1_tfidf = Input(name='q1_tfidf', shape=(max_sent, 300))
q2_tfidf = Input(name='q2_tfidf', shape=(max_sent, 300))

q1_tfidf = LSTM(100)(q1_tfidf)
q2_tfidf = LSTM(100)(q2_tfidf)
distance2 = Lambda(preprocessing.exponent_neg_manhattan_distance, output_shape=preprocessing.get_shape)(
        [q1_tfidf, q2_tfidf])

我正在努力应对矩阵的形状。我收到此错误:

ValueError: Error when checking input: expected q1_tfidf to have 3 dimensions, but got array with shape (384348, 300)

我已经检查了此帖子:Sentence Embedding Keras,但仍然无法弄清楚。看来我缺少明显的东西。

有什么想法吗?

1 个答案:

答案 0 :(得分:0)

据我了解,您想预测两个句子之间的差异。 重复使用LSTM层(语言模型应该相同),然后学习单个句子嵌入并使用两次,该怎么办?

q1_tfidf = Input(name='q1_tfidf', shape=(max_sent, 300))
q2_tfidf = Input(name='q2_tfidf', shape=(max_sent, 300))

lstm = LSTM(100)

lstm_out_q1= lstm (q1_tfidf)
lstm_out_q2= lstm (q2_tfidf)
predict = concatenate([lstm_out_q1, lstm_out_q2])
model = Model(inputs=[q1_tfidf ,q1_tfidf ], outputs=predict)

predict = concatenate([q1_tfidf , q2_tfidf])

您还可以在其他lambda层中引入自定义距离,但是因此需要在串联中使用其他重塑。