hli*_*117 29 python nlp neural-network gensim word2vec
在使用python gensim训练word2vec模型后,你如何找到模型词汇中的单词数量?
goj*_*omo 68
词汇表在vocabWord2Vec模型的wv属性字段中,作为字典,键是每个标记(单词).所以它只是通常的Python获取字典的长度:
len(w2v_model.wv.vocab)
Run Code Online (Sandbox Code Playgroud)
(在0.13之前的较旧gensim版本中,vocab直接出现在模型上.因此,您将使用w2v_model.vocab而不是w2v_model.wv.vocab.)
获得词汇量大小的另一种方法是从嵌入矩阵本身,如下所示:
In [33]: from gensim.models import Word2Vec
# load the pretrained model
In [34]: model = Word2Vec.load(pretrained_model)
# get the shape of embedding matrix
In [35]: model.wv.vectors.shape
Out[35]: (662109, 300)
# `vocabulary_size` is just the number of rows (i.e. axis 0)
In [36]: model.wv.vectors.shape[0]
Out[36]: 662109
Run Code Online (Sandbox Code Playgroud)
Gojomo 的回答提出了AttributeErrorGensim 4.0.0+ 的问题。
对于这些版本,您可以按如下方式获取词汇表的长度:
len(w2v_model.wv.index_to_key)
(比:略快len(w2v_model.wv.key_to_index))