如何向gensim字典添加词元

4 投票
3 回答
5851 浏览
提问于 2025-04-18 09:31

我使用 来从一堆文档中建立字典。每个文档都是一个词语的列表。这是我的代码:

def constructModel(self, docTokens):
    """ Given document tokens, constructs the tf-idf and similarity models"""

    #construct dictionary for the BOW (vector-space) model : Dictionary = a mapping between words and their integer ids = collection of (word_index,word_string) pairs
    #print "dictionary"
    self.dictionary = corpora.Dictionary(docTokens)

    # prune dictionary: remove words that appear too infrequently or too frequently
    print "dictionary size before filter_extremes:",self.dictionary#len(self.dictionary.values())
    #self.dictionary.filter_extremes(no_below=1, no_above=0.9, keep_n=100000)
    #self.dictionary.compactify()

    print "dictionary size after filter_extremes:",self.dictionary

    #construct the corpus bow vectors; bow vector = collection of (word_id,word_frequency) pairs
    corpus_bow = [self.dictionary.doc2bow(doc) for doc in docTokens]


    #construct the tf-idf model 
    self.model = models.TfidfModel(corpus_bow,normalize=True)
    corpus_tfidf = self.model[corpus_bow]   # first transform each raw bow vector in the corpus to the tfidf model's vector space
    self.similarityModel = similarities.MatrixSimilarity(corpus_tfidf)  # construct the term-document index

我想问的是,怎么把一个新的文档(词语)添加到这个字典里并更新它。我在 gensim 的文档里找过,但没找到解决办法。

3 个回答

0

方法 1:

你可以直接使用 keyedvectors,这个是从 gensim.models.keyedvectors 里来的。它们非常简单好用。

from gensim.models.keyedvectors import WordEmbeddingsKeyedVectors

w2v = WordEmbeddingsKeyedVectors(50) # 50 = vec length
w2v.add(new_words, their_new_vecs)

方法 2:

而且 如果你已经用 gensim.models.Word2Vec 构建了一个模型,你可以这样做。假设我想添加一个标记 <UKN>,并给它一个随机的向量。

model.wv["<UNK>"] = np.random.rand(100) # 100 is the vectors length

完整的例子会是这样的:

import numpy as np
import gensim.downloader as api
from gensim.models import Word2Vec

dataset = api.load("text8")  # load dataset as iterable
model = Word2Vec(dataset)

model.wv["<UNK>"] = np.random.rand(100)
3

你可以使用 add_documents 这个方法:

from gensim import corpora
text = [["aaa", "aaa"]]
dictionary = corpora.Dictionary(text)
dictionary.add_documents([['bbb','bbb']])
print(dictionary)

运行上面的代码后,你会得到这个结果:

Dictionary(2 unique tokens: ['aaa', 'bbb'])

想了解更多细节,可以查看这个 文档

7

在gensim的网页上有关于如何做到这一点的说明,可以在这里找到

具体做法是先创建一个包含新文档的字典,然后把它们合并在一起。

from gensim import corpora

dict1 = corpora.Dictionary(firstDocs)
dict2 = corpora.Dictionary(moreDocs)
dict1.merge_with(dict2)

根据文档的说明,这样做会把“相同的词汇映射到相同的编号,而新的词汇则会分配新的编号”。

撰写回答