如何在Keras词嵌入层中找到相似的词

时间:2019-06-17 20:08:47

标签: keras word-embedding

从斯坦福大学的CS244N课程开始,我知道Gensim提供了一种出色的方法来处理嵌入数据:most_similar

我试图在Keras嵌入层中找到一些等效项,但是找不到。 Keras不可能开箱即用吗?还是上面有包装纸?

谢谢!

1 个答案:

答案 0 :(得分:1)

一个简单的实现是:

def most_similar(emb_layer, pos_word_idxs, neg_word_idxs=[], top_n=10):
    weights = emb_layer.weights[0]

    mean = []
    for idx in pos_word_idxs:
        mean.append(weights.value()[idx, :])

    for idx in neg_word_idxs:
        mean.append(weights.value()[idx, :] * -1)

    mean = tf.reduce_mean(mean, 0)

    dists = tf.tensordot(weights, mean, 1)
    best = tf.math.top_k(dists, top_n)

    # Mask words used as pos or neg
    mask = []
    for v in set(pos_word_idxs + neg_word_idxs):
        mask.append(tf.cast(tf.equal(best.indices, v), tf.int8))
    mask = tf.less(tf.reduce_sum(mask, 0), 1)

    return tf.boolean_mask(best.indices, mask), tf.boolean_mask(best.values, mask)

当然,您需要知道单词的索引。我假设您有一个word2idx映射,所以可以这样获得它们:[word2idx[w] for w in pos_words]

要使用它:

# Assuming the first layer is the Embedding and you are interested in word with idx 10
idxs, vals = most_similar(model.layers[0], [10])

with tf.Session() as sess:
    init = tf.global_variables_initializer()
    sess.run(init)
    idxs = sess.run(idxs)
    vals = sess.run(vals)

该功能可能有一些改进:

  • 确保它返回top_n个单词(在掩码之后返回的单词较少)
  • gensim使用归一化嵌入(L2_norm)