如何将经过预先训练的单词嵌入加载到Keras Embedding
图层中?
我从https://nlp.stanford.edu/projects/glove/下载了glove.6B.50d.txt
(glove.6B.zip文件),我不知道如何将其添加到Keras嵌入层。请参阅:https://keras.io/layers/embeddings/
答案 0 :(得分:3)
您需要将embeddingMatrix传递到Embedding
图层,如下所示:
Embedding(vocabLen, embDim, weights=[embeddingMatrix], trainable=isTrainable)
vocabLen
:词汇量中的代币数量embDim
:嵌入向量维度(在您的示例中为50)embeddingMatrix
:嵌入矩阵由gloves.6B.50d.txt isTrainable
:您是否希望嵌入可以训练或冻结图层 glove.6B.50d.txt
是以空格分隔的值列表:单词标记+(50)嵌入值。例如the 0.418 0.24968 -0.41242 ...
从Glove文件创建pretrainedEmbeddingLayer
:
# Prepare Glove File
def readGloveFile(gloveFile):
with open(gloveFile, 'r') as f:
wordToGlove = {} # map from a token (word) to a Glove embedding vector
wordToIndex = {} # map from a token to an index
indexToWord = {} # map from an index to a token
for line in f:
record = line.strip().split()
token = record[0] # take the token (word) from the text line
wordToGlove[token] = np.array(record[1:], dtype=np.float64) # associate the Glove embedding vector to a that token (word)
tokens = sorted(wordToGlove.keys())
for idx, tok in enumerate(tokens):
kerasIdx = idx + 1 # 0 is reserved for masking in Keras (see above)
wordToIndex[tok] = kerasIdx # associate an index to a token (word)
indexToWord[kerasIdx] = tok # associate a word to a token (word). Note: inverse of dictionary above
return wordToIndex, indexToWord, wordToGlove
# Create Pretrained Keras Embedding Layer
def createPretrainedEmbeddingLayer(wordToGlove, wordToIndex, isTrainable):
vocabLen = len(wordToIndex) + 1 # adding 1 to account for masking
embDim = next(iter(wordToGlove.values())).shape[0] # works with any glove dimensions (e.g. 50)
embeddingMatrix = np.zeros((vocabLen, embDim)) # initialize with zeros
for word, index in wordToIndex.items():
embeddingMatrix[index, :] = wordToGlove[word] # create embedding: word index to Glove word embedding
embeddingLayer = Embedding(vocabLen, embDim, weights=[embeddingMatrix], trainable=isTrainable)
return embeddingLayer
# usage
wordToIndex, indexToWord, wordToGlove = readGloveFile("/path/to/glove.6B.50d.txt")
pretrainedEmbeddingLayer = createPretrainedEmbeddingLayer(wordToGlove, wordToIndex, False)
model = Sequential()
model.add(pretrainedEmbeddingLayer)
...
答案 1 :(得分:1)
有一篇很棒的博客文章描述了如何使用预先训练过的单词矢量嵌入来创建嵌入层:
https://blog.keras.io/using-pre-trained-word-embeddings-in-a-keras-model.html
上述文章的代码可以在这里找到:
https://github.com/keras-team/keras/blob/master/examples/pretrained_word_embeddings.py
另一个出于同样目的的好博客:https://machinelearningmastery.com/use-word-embedding-layers-deep-learning-keras/
答案 2 :(得分:0)
几年前,我编写了一个名为 embfile 的实用程序包,用于处理“嵌入文件”(但我仅在 2020 年发布)。我想涵盖的用例是创建一个预训练的嵌入矩阵来初始化 Embedding
层。我想通过尽可能快地加载我需要的词向量来做到这一点。
支持多种格式:
该包是 extensively documented 并经过测试。还有examples that show how to use it with Keras。
import embfile
with embfile.open(EMBEDDING_FILE_PATH) as f:
emb_matrix, word2index, missing_words = embfile.build_matrix(
f,
words=vocab, # this could also be a word2index dictionary as well
start_index=1, # leave the first row to zeros
)
该函数还处理文件词汇表之外的单词的初始化。默认情况下,它在找到的向量上拟合正态分布,并使用它来生成新的随机向量(这就是 AllenNLP 所做的)。我不确定这个功能是否仍然相关:现在您可以使用 FastText 或其他工具为未知单词生成嵌入。
请记住,txt 和 bin 文件本质上是顺序文件,需要进行全面扫描(除非您在最后找到要查找的所有单词)。这就是我使用 vvm 文件的原因,它为向量提供随机访问。一个人可以通过索引顺序文件来解决这个问题,但是 embfile 没有这个功能。尽管如此,您可以将顺序文件转换为 vvm(这类似于创建索引并将所有内容打包到一个文件中)。
答案 3 :(得分:0)
我正在寻找类似的东西。我发现这篇博文回答了这个问题。它正确地解释了创建 embedding_matrix
并将其传递给 Embedding()
层的 hot。我知道这是一个旧帖子,但希望它有所帮助!