keras - 如何在 Keras Word Embedding 层中查找相似词
问题描述
从斯坦福的 CS244N 课程中,我知道 Gensim 提供了一种奇妙的方法来处理嵌入数据:most_similar
我试图在 Keras 嵌入层中找到一些等价物,但我做不到。Keras不可能开箱即用?还是它上面有任何包装?
解决方案
一个简单的实现是:
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)
推荐阅读
- python - 无法使用flask和pyodbc连接到mysql服务器
- sapui5 - 将 Angular 应用程序从 neo 迁移到 SAP Cloud Foundry
- python - python - 如何通过python中的id合并python中的两个api?
- intellij-idea - 用于转储整个堆栈/调用跟踪以进行比较的资源
- phpspreadsheet - PHPSpreadsheet 无法保存从模板加载的折线图(被“另一个用户”锁定)
- r - Ewma 的时间序列回报
- flutter - Flutter 与其他应用程序共享链接,并带有单独的描述
- cordova - 离子cordova插件cordova-plugin-googleplus错误10
- python - Pygame Zero 中 Actor 函数的“pos”不起作用
- c# - DDD 逻辑中的批量操作