如何从Keras Embedding层获取词向量

24

我目前正在使用Keras模型,其中第一层是嵌入层。为了可视化每个词之间的关系和相似度,我需要一个函数来返回词汇表中每个元素的映射及其向量(例如“love”- [0.21, 0.56,...,0.65,0.10])。

有没有什么方法可以做到这一点?

1个回答

50
您可以通过使用嵌入层的get_weights()方法来获取单词嵌入(即,嵌入层的权重实质上就是嵌入向量):
# if you have access to the embedding layer explicitly
embeddings = emebdding_layer.get_weights()[0]

# or access the embedding layer through the constructed model 
# first `0` refers to the position of embedding layer in the `model`
embeddings = model.layers[0].get_weights()[0]

# `embeddings` has a shape of (num_vocab, embedding_dim) 

# `word_to_index` is a mapping (i.e. dict) from words to their index, e.g. `love`: 69
words_embeddings = {w:embeddings[idx] for w, idx in word_to_index.items()}

# now you can use it like this for example
print(words_embeddings['love'])  # possible output: [0.21, 0.56, ..., 0.65, 0.10]

不要忘记在输入中添加填充时添加特殊字符,以应对某些用例(如LSTM)。您还可以为填充添加索引,例如 word_to_index['__padding__'] = 0 - Vaibhav
如果您正在讨论上下文化与非上下文化嵌入,那么这与您使用的Keras或DL框架完全无关。相反,它与您使用的方法或算法有关。嵌入层本身只是一个查找表:给定一个整数索引,它返回对应于该索引的向量。作为模型方法或架构的设计者,是您决定如何使用它,使模型提供上下文化或非上下文化的嵌入。 - today
谢谢,@今天整数索引部分讲得很清楚。它返回的学习密集向量更接近静态嵌入还是上下文化/动态嵌入?如果我用下游LSTM预测任务来学习它们,它们会变得上下文化吗? - A.B
@A.B 上下文嵌入不仅仅是通过嵌入层实现的;除了嵌入层之外,模型的架构也会产生上下文嵌入。嵌入层中的值是固定的(在训练后),因此对于像“银行账户”和“河岸边的银行”这样的两个句子,嵌入层为单词“银行”生成的向量对于这两个句子来说完全相同。因此,您必须添加其他层,无论是RNN还是Transformer层,以便在顶部生成上下文嵌入(作为这些层的输出,而不是嵌入层)。 - today
我该如何导入emebdding_layer?它显示未定义。我在文档中找不到它。我认为这可能是一个拼写错误。 - Guilherme Parreira
显示剩余4条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接