我正在使用 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
通常错误会在第二个文档上弹出。我想我明白它在告诉我什么(字典索引不好),我只是不知道为什么。我尝试了很多不同的东西,但似乎没有任何效果。有谁知道发生了什么?
谢谢!