4

我使用从文档集合中构建字典。每个文档都是一个令牌列表。这是我的代码

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文档中搜索但没有找到解决方案

4

3 回答 3

7

此处的 gensim 网页上有有关如何执行此操作的文档

这样做的方法是使用新文档创建另一个字典,然后将它们合并。

from gensim import corpora

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

根据文档,这会将“相同的令牌映射到相同的 id,将新的令牌映射到新的 id”。

于 2014-09-23T00:29:08.260 回答
2

您可以使用以下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'])

阅读文档了解更多详情。

于 2017-07-17T10:24:07.047 回答
0

方法一:

您可以只使用来自. gensim.models.keyedvectors它们非常易于使用。

from gensim.models.keyedvectors import WordEmbeddingsKeyedVectors

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

方法二:

而且,如果您已经使用它构建了模型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)
于 2020-11-24T16:21:14.730 回答