[英][Word2Vec][gensim] Handling missing words in vocabulary with the parameter min_count
已經就這個話題提出了一些類似的問題,但我對到目前為止的答復並不滿意; 請先原諒我。
我使用的功能Word2Vec
從Python庫gensim
。
我的問題是,只要我將參數min_count
設置為大於 1 ,我就無法在語料庫的每個單詞上運行我的模型。 有人會說這是邏輯,因為我選擇忽略只出現一次的單詞。 但是該函數的行為很奇怪,因為它給出了一個錯誤,說單詞“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 的模型,但您可以隨意使用任何模型,也可以不使用,這不是我的帖子的重點。
正如代碼注釋中所通知的:在“巴黎”上運行模型有效,但不能在“國家”上運行。 當然,如果我將參數min_count
設置為 1,則一切正常。
我希望它足夠清楚。
謝謝。
如果您要求一個不存在的單詞,它應該會引發錯誤,因為您選擇不學習稀有單詞的向量,例如您的示例中的'country'
。 (並且:這樣的例子很少的詞通常不會得到好的向量,保留它們會使剩余詞的向量惡化,因此min_count
盡可能大,並且可能比1
大得多,通常是個好主意。 )
解決方法是執行以下操作之一:
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
try:
print(my_model['country'][0:10])
except:
pass # do nothing, or perhaps print an error, whatever
FastText
它會嘗試使用在訓練期間學習的子詞來合成未知單詞的向量。 (這可能是垃圾,如果未知單詞在字符和含義上與已知單詞高度相似可能會很好,但對於某些用途來說,它總比沒有好。)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.