2

我想为语料库中的单词获取单词嵌入。我决定通过gensim库在GoogleNews中使用预训练的词向量。但我的语料库包含一些不在 GoogleNews 单词中的单词。对于这些缺失的单词,我想在 GoggoleNews 单词中使用 n 个最相似单词的算术平均值。首先,我加载 GoogleNews 并检查其中是否包含“to”一词?

#Load GoogleNews pretrained word2vec model
model=word2vec.KeyedVectors.Load_word2vec_format("GoogleNews-vectors-negative33.bin",binary=True)
print(model["to"])

我收到一个错误:keyError: "word 'to' not in vocabulary" 这么大的数据集可能没有这个词吗?对于像“a”这样的其他常用词也是如此!

为了向 word2vec 模型添加缺失的单词,首先我想获取 GoogleNews 中的单词索引。对于缺少的单词,我使用了索引 0。

#obtain index of words
word_to_idx=OrderedDict({w:0 for w in corpus_words})
word_to_idx=OrderedDict({w:model.wv.vocab[w].index for w in corpus_words if w in model.wv.vocab})

然后我计算每个缺失词的最相似词的嵌入向量的平均值。

missing_embd={}
for key,value in word_to_idx.items():
    if value==0:
        similar_words=model.wv.most_similar(key)
        similar_embeddings=[model.wv[a[0]] for a in similar_words]
        missing_embd[key]=mean(similar_embeddings)

然后我通过以下方式将这些新闻嵌入添加到 word2vec 模型中:

for word,embd in missing_embd.items():
    # model.wv.build_vocab(word,update=True)
    model.wv.syn0[model.wv.vocab[word].index]=embd

有不一致的地方。当我打印missing_embed 时,它是空的。仿佛没有遗漏的字眼。但是当我通过这个检查它时:

for w in tokens_lower:
    if(w in model.wv.vocab)==False:
        print(w)
        print("***********")

我发现了很多缺失的单词。现在,我有 3 个问题: 1- 为什么missing_embed是空的,而有一些缺失的单词?2- GoogleNews 有没有可能没有像“to”这样的词?3-如何将新嵌入附加到 word2vec 模型?我使用了 build_vocabsyn0。谢谢。

4

2 回答 2

2

这是我们添加缺少的小写单词的场景。

from gensim.models import KeyedVectors
path = '../input/embeddings/GoogleNews-vectors-negative300/GoogleNews-vectors-negative300.bin'
embedding = KeyedVectors.load_word2vec_format(path, binary=True)

'Quoran' in embedding.vocab
 Output : True

'quoran' in embedding.vocab
 Output : False

此处存在 Quoran,但缺少小写的 quoran

# add quoran in lower case
embedding.add('quoran',embedding.get_vector('Quoran'),replace=False)

'quoran' in embedding.vocab
 Output : True
于 2018-12-30T05:36:09.337 回答
1

谷歌可能删除了常见的填充词,如“to”和“a”。load()如果文件看起来没有损坏,并且在显示它们存在之后检查其他词,则可以合理地假设 Google 丢弃了过于常见的词,因为它们具有如此广泛的含义以至于价值低。

你想要做什么不清楚和混乱。您分配了word_to_idx两次 - 所以只有第二行很重要。

(第一个分配,创建一个所有单词都有一个0值的字典,在第二行创建一个全新的字典之后没有挥之不去的影响,只有条目 where w in model.wv.vocab。在此步骤之后唯一可能的条目是 a0中的任何单词词向量集已经就位0——当且仅当那个词也在你的corpus_words.)

您似乎想根据相似词的平均值为未知词构建新向量。但是,most_similar()仅适用于已知单词。如果尝试完全未知的单词,它将出错。所以这种方法行不通。

更深层次的问题是gensim KeyedVectors该类不支持动态添加新的单词->向量条目。您必须深入研究其源代码,并添加一个或一批新向量,以自洽的方式修改其一系列内部属性(包括其vectors数组、vocab字典和index2entity列表)以获得新条目。

于 2018-06-01T22:43:35.340 回答