从Keras Embedding层获取词向量的方法

2024-05-17 02:54:14 发布

您现在位置:Python中文网/ 问答频道 /正文

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

有办法吗?


Tags: 词汇表函数模型元素关系可视化相似性单词
1条回答
网友
1楼 · 发布于 2024-05-17 02:54:14

通过使用嵌入层的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]

相关问题 更多 >