如何检查 word2vec 训练模型中是否存在键
How to check if a key exists in a word2vec trained model or not
我使用 Gensim 文档语料库训练了一个 word2vec 模型。一旦模型开始训练,我将编写以下代码来获取单词 "view".
的原始特征向量
myModel["view"]
但是,我收到该词的 KeyError,这可能是因为它不作为 word2vec 索引的键列表中的键存在。在尝试获取原始特征向量之前,如何检查索引中是否存在键?
在这里回答我自己的问题。
Word2Vec 提供了一个名为 contains('view') 的方法,它 returns True 或 False 基于相应的词是否已被索引。
Word2Vec还提供了一个'vocab'成员,您可以直接访问。
使用 pythonistic 方法:
if word in w2v_model.vocab:
# Do something
EDIT 自 gensim 2.0 版以来,Word2Vec 的 API 发生了变化。要访问词汇表,您现在应该使用:
if word in w2v_model.wv.vocab:
# Do something
编辑 2 属性 'wv' 已弃用,将在 gensim 4.0.0 中完成删除。现在回到 OP 的原始答案:
if word in w2v_model.vocab:
# Do something
嘿,我知道我来晚了 post,但这里有一段代码可以很好地处理这个问题。我自己在我的代码中使用它,它就像一个魅力:)
size = 300 #word vector size
word = 'food' #word token
try:
wordVector = model[word].reshape((1, size))
except KeyError:
print "not found! ", word
注意:
我正在为 word2vec 模型使用 python Gensim 库
使用
将模型转换为向量
word_vectors = model.wv
然后我们可以使用
if 'word' in word_vectors.vocab
我一般用滤镜:
for doc in labeled_corpus:
words = filter(lambda x: x in model.vocab, doc.words)
这是一种简单的方法,可以解决看不见的单词的 KeyError。
vocab 属性已从 Gensim 4.0.0 中的 KeyedVector 中删除
if 'word' in model.wv.key_to_index:
# do something
我使用 Gensim 文档语料库训练了一个 word2vec 模型。一旦模型开始训练,我将编写以下代码来获取单词 "view".
的原始特征向量myModel["view"]
但是,我收到该词的 KeyError,这可能是因为它不作为 word2vec 索引的键列表中的键存在。在尝试获取原始特征向量之前,如何检查索引中是否存在键?
在这里回答我自己的问题。
Word2Vec 提供了一个名为 contains('view') 的方法,它 returns True 或 False 基于相应的词是否已被索引。
Word2Vec还提供了一个'vocab'成员,您可以直接访问。
使用 pythonistic 方法:
if word in w2v_model.vocab:
# Do something
EDIT 自 gensim 2.0 版以来,Word2Vec 的 API 发生了变化。要访问词汇表,您现在应该使用:
if word in w2v_model.wv.vocab:
# Do something
编辑 2 属性 'wv' 已弃用,将在 gensim 4.0.0 中完成删除。现在回到 OP 的原始答案:
if word in w2v_model.vocab:
# Do something
嘿,我知道我来晚了 post,但这里有一段代码可以很好地处理这个问题。我自己在我的代码中使用它,它就像一个魅力:)
size = 300 #word vector size
word = 'food' #word token
try:
wordVector = model[word].reshape((1, size))
except KeyError:
print "not found! ", word
注意: 我正在为 word2vec 模型使用 python Gensim 库
使用
将模型转换为向量word_vectors = model.wv
然后我们可以使用
if 'word' in word_vectors.vocab
我一般用滤镜:
for doc in labeled_corpus:
words = filter(lambda x: x in model.vocab, doc.words)
这是一种简单的方法,可以解决看不见的单词的 KeyError。
vocab 属性已从 Gensim 4.0.0 中的 KeyedVector 中删除
if 'word' in model.wv.key_to_index:
# do something