[Word2Vec][gensim] 使用参数 min_count 处理词汇表中的缺失词

[Word2Vec][gensim] Handling missing words in vocabulary with the parameter min_count

关于这个话题已经问了一些类似的问题,但我对目前的答复不是很满意;请先原谅我。

我正在使用 python 库 gensim 中的函数 Word2Vec

我的问题是,只要我将参数 min_count 设置为大于 one[=36=,我就 无法 运行 我的语料库中的每个单词的模型].有人会说这是合乎逻辑的,因为我选择忽略只出现一次的单词。但是这个函数表现得很奇怪,因为它给出了一个 错误,说 词 'blabla' 不在词汇表 中,而这正是我想要(我希望这个词不在词汇表中)。

我可以想象这不是很清楚,然后在下面找到一个可重现的例子:

import gensim
from gensim.models import Word2Vec

# My corpus
corpus=[["paris","not","great","city"],
       ["praha","better","great","than","paris"],
       ["praha","not","country"]]

# Load a pre-trained model - The orignal one based on google news 
model_google = gensim.models.KeyedVectors.load_word2vec_format(r'GoogleNews-vectors-negative300.bin', binary=True)

# Initializing our model and upgrading it with Google's 
my_model = Word2Vec(size=300, min_count=2)#with min_count=1, everything works fine
my_model.build_vocab(corpus)
total_examples = my_model.corpus_count
my_model.build_vocab([list(model_google.vocab.keys())], update=True)
my_model.intersect_word2vec_format('GoogleNews-vectors-negative300.bin', binary=True, lockf=1.0)
my_model.train(corpus, total_examples=total_examples, epochs=my_model.iter)

# Show examples
print(my_model['paris'][0:10])#works cause 'paris' is present twice
print(my_model['country'][0:10])#does not work cause 'country' appears only once

例如,你可以找到Google的模型there,但是你可以随意使用任何模型或者不用,这不是我post的重点。

如代码注释中所述:运行模型在 'paris' 上有效,但在 'country' 上无效。当然,如果我将参数 min_count 设置为 1,一切正常。

我希望已经足够清楚了。

谢谢。

如果你要求一个不存在的词,它应该会抛出一个错误,因为你选择不学习罕见词的向量,比如你的例子中的'country'。 (而且:这样的例子很少的词通常得不到好的向量,保留它们会使剩余词的向量变差,所以 min_count 尽可能大,也许比 1, 通常是个好主意。)

修复方法是执行以下操作之一:

  1. 不要询问不存在的词。首先通过 Python 的 in 运算符进行检查。例如:
if 'country' in my_model:
    print(my_model['country'][0:10])
else: 
    pass  # do nothing, since `min_count=2` means there's no 'country' vector
  1. 捕捉错误,回退到任何你想要的缺失词发生的地方:
try:
    print(my_model['country'][0:10])
except:
    pass  # do nothing, or perhaps print an error, whatever
  1. 更改为使用总是 returns 任何单词的模型,例如 FastText – 它将尝试使用在训练期间学习的子词来合成未知单词的向量。 (这可能是垃圾,如果未知单词在字符和含义上与已知单词高度相似,那可能会很好,但对于某些用途来说,它总比没有好。)