我正在使用 Python 的 gensim 库来进行潜在语义索引。我按照网站上的教程进行操作,效果很好。现在我想稍微修改一下;我想在每次添加文档时运行 lsi 模型。
这是我的代码:
stoplist = set('for a of the and to in'.split())
num_factors=3
corpus = []
for i in range(len(urls)):
print "Importing", urls[i]
doc = getwords(urls[i])
cleandoc = [word for word in doc.lower().split() if word not in stoplist]
if i == 0:
dictionary = corpora.Dictionary([cleandoc])
else:
dictionary.addDocuments([cleandoc])
newVec = dictionary.doc2bow(cleandoc)
corpus.append(newVec)
tfidf = models.TfidfModel(corpus)
corpus_tfidf = tfidf[corpus]
lsi = models.LsiModel(corpus_tfidf, numTopics=num_factors, id2word=dictionary)
corpus_lsi = lsi[corpus_tfidf]
geturls 是我编写的函数,它以字符串形式返回网站的内容。同样,如果我等到我处理完所有文档后再执行 tfidf 和 lsi,它会起作用,但这不是我想要的。我想在每次迭代中都这样做。不幸的是,我得到了这个错误:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "streamlsa.py", line 51, in <module>
lsi = models.LsiModel(corpus_tfidf, numTopics=num_factors, id2word=dictionary)
File "/Library/Python/2.6/site-packages/gensim-0.7.8-py2.6.egg/gensim/models/lsimodel.py", line 303, in __init__
self.addDocuments(corpus)
File "/Library/Python/2.6/site-packages/gensim-0.7.8-py2.6.egg/gensim/models/lsimodel.py", line 365, in addDocuments
self.printTopics(5) # TODO see if printDebug works and remove one of these..
File "/Library/Python/2.6/site-packages/gensim-0.7.8-py2.6.egg/gensim/models/lsimodel.py", line 441, in printTopics
self.printTopic(i, topN = numWords)))
File "/Library/Python/2.6/site-packages/gensim-0.7.8-py2.6.egg/gensim/models/lsimodel.py", line 433, in printTopic
return ' + '.join(['%.3f*"%s"' % (1.0 * c[val] / norm, self.id2word[val]) for val in most])
File "/Library/Python/2.6/site-packages/gensim-0.7.8-py2.6.egg/gensim/corpora/dictionary.py", line 52, in __getitem__
return self.id2token[tokenid] # will throw for non-existent ids
KeyError: 1248
通常错误会在第二个文档上弹出。我想我明白它在告诉我什么(字典索引不好),我只是想不通为什么。我尝试了很多不同的东西,但似乎没有任何效果。有谁知道这是怎么回事吗?
谢谢!
最佳答案
这是 gensim 中的一个错误,反向 id->word 映射被缓存,但是缓存在 addDocuments()
之后没有得到更新。
它在 2011 年的这次提交中得到修复:https://github.com/piskvorky/gensim/commit/b88225cfda8570557d3c72b0820fefb48064a049 .
关于python - LSI 在 python 中使用 gensim,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6287411/