![](/img/trans.png)
[英]How to use own word embedding with pre-trained embedding like word2vec in Keras
[英]How do I create a Keras Embedding layer from a pre-trained word embedding dataset?
如何将预先训练好的词嵌入加载到 Keras Embedding
层中?
我下载了glove.6B.50d.txt
(来自https://nlp.stanford.edu/projects/glove/ 的glove.6B.zip 文件),但我不确定如何将它添加到 Keras 嵌入层。 请参阅: https : //keras.io/layers/embeddings/
您需要将 embeddingMatrix 传递给Embedding
层,如下所示:
Embedding(vocabLen, embDim, weights=[embeddingMatrix], trainable=isTrainable)
vocabLen
:词汇表中的记号数embDim
:嵌入向量维度(在您的示例中为 50)embeddingMatrix
: 从 glove.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)
...
有一篇很棒的博客文章描述了如何使用预训练的词向量嵌入创建嵌入层:
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/
几年前,我编写了一个名为embfile的实用程序包,用于处理“嵌入文件”(但我仅在 2020 年发布了它)。 我想涵盖的用例是创建一个预训练的嵌入矩阵来初始化一个Embedding
层。 我想通过尽可能快地加载我需要的词向量来做到这一点。
它支持多种格式:
该软件包已被广泛记录和测试。 还有一些示例展示了如何将它与 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(这类似于创建索引并将所有内容打包到单个文件中)。
我正在寻找类似的东西。 我发现这篇博文回答了这个问题。 它正确地解释了如何创建embedding_matrix
并将其传递给Embedding()
层。 我知道这是一个旧帖子,但希望它有所帮助!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.