将装有Gensim的Google的Word2Vec调整到您的词汇表,然后创建嵌入向量

时间:2018-04-15 22:59:31

标签: python word2vec gensim embedding

我想知道如何将Google的Word2Vec限制在我的词汇表中。 Google的Word2 vec链接:https://drive.google.com/file/d/0B7XkCwpI5KDYNlNUTTlSS21pQmM/edit?usp=sharing

这就是我所拥有的:

import gensim

# Load Google's pre-trained Word2Vec model.
model = gensim.models.Word2Vec.load_word2vec_format('./model/GoogleNews-vectors-negative300.bin', binary=True)

embedding_matrix = np.zeros((len(my_vocabulary), 300))

我的词汇表是我的语料库中唯一单词的列表。 我怎样才能感受到my_vocabulary中单词的嵌入矩阵? 另外,我希望能够灵活地使用Google的word2vec中不存在我的单词来填充零。

由于

2 个答案:

答案 0 :(得分:1)

您可以使用gensim.models.Word2Vec构建自定义w2v模型。

sentences = [['cats', 'can', 'not', 'fly'], ['dogs','cant' 'drive']]
model = gensim.models.Word2Vec(sentences, min_count=1)

参考:https://rare-technologies.com/word2vec-tutorial/

答案 1 :(得分:0)

您可以使用以下代码填充嵌入矩阵:

import gensim

# Load Google's pre-trained Word2Vec model.
model = gensim.models.Word2Vec.load_word2vec_format('path/to/bin', binary=True)

embedding_matrix = np.zeros((len(my_vocabulary), 300))

for index,word in enumerate(my_vocabulary):
    try:
        # update embedding matrix using Google's pretrained model
        embedding_matrix[index] = model.mv[word] 
    except:
        # when word isn't found in pretrained model, we keep the embedding matrix unchanged at that index (assigned to zero)
        pass

此外,您可以探索将词汇表单词初始化为零以外的某些值的方法。