【发布时间】:2017-02-25 21:15:16
【问题描述】:
我正在尝试创建一个模型,在该模型中,我想在给定特定查询的情况下预测特定文档集的顺序。我的想法基本上是为查询和文档使用共享嵌入层,然后使用每个文档和查询之间的余弦相似度(使用自定义 lambda)合并两个“分支”。然后损失函数将计算预期位置和预测相似度之间的差异。
我的问题是:有没有办法为一组文本特征创建嵌入(假设它们具有相同的长度)?
我可以通过应用 Embedding + Convolution1D + GlobalMaxPooling1D 将我的查询正确地转换为“类似 doc2vec 的嵌入”,但是我在文档集上使用相同的策略没有运气(并且重塑 + 2D 卷积并没有真正使考虑到我正在处理文本数据,这对我来说是有意义的)。
请注意,我的一个限制是我需要为我的查询和文档集使用相同的嵌入层(我正在使用 Keras 的功能 api 来执行此操作)。
[编辑,添加示例代码]
Q = Input(shape=(5, )) # each query is made of 5 words
T = Input(shape=(50, 50)) # each search result is made of 50 words and 50 docs
emb = Embedding(
max_val,
embedding_dims,
dropout=embedding_dropout
)
left = emb(Q)
left = Convolution1D(nb_filter=5,
filter_length=5,
border_mode='valid',
activation='relu',
subsample_length=1)(left)
left = GlobalMaxPooling1D()(left)
print(left)
right = emb(T) # <-- this is my problem, I don't really know what to do/apply here
def merger(vests):
x, y = vests
x = K.l2_normalize(x, axis=0) # Normalize rows
y = K.l2_normalize(y, axis=-1) # Normalize the vector
return tf.matmul(x, y) # obviously throws an error because of mismatching matrix ranks
def cos_dist_output_shape(shapes):
shape1, shape2 = shapes
return (50, 1)
merger_f = Lambda(merger)
predictions = merge([left, right], output_shape=cos_dist_output_shape, mode=merger_f)
model = Model(input=[Q, T], output=predictions)
def custom_objective(y_true, y_pred):
ordered_output = tf.cast(tf.nn.top_k(y_pred)[1], tf.float32) # returns the indices of the top values
return K.mean(K.square(ordered_output - y_true), axis=-1)
model.compile(optimizer='adam', loss=custom_objective)
[解决方案]感谢 Nassim Ben,像这样使用 TimeDistributed 将图层循环应用于图层的所有维度,如下所示:
right = TimeDistributed(emb)(T)
right = TimeDistributed(Convolution1D(nb_filter=5,
filter_length=5,
border_mode='valid',
activation='relu',
subsample_length=1)(right)
right = TimeDistributed(GlobalMaxPooling1D())(right)
【问题讨论】:
-
你有一些代码要分享吗?到目前为止,您已经尝试过什么:)
-
当然是的 :) 很抱歉没有从一开始就添加它@NassimBen
标签: python neural-network keras embedding