python - 我应该使用哪个 gensim 语料库类来加载 LDA 转换后的语料库? - Python

标签 python nlp corpus lda gensim

我如何从 python 的 gensim 加载经过 LDA 转换的语料库?我试过的方法:

from gensim import corpora, models
import numpy.random
numpy.random.seed(10)

doc0 = [(0, 1), (1, 1)]
doc1 = [(0,1)]
doc2 = [(0, 1), (1, 1)]
doc3 = [(0, 3), (1, 1)]

corpus = [doc0,doc1,doc2,doc3]
dictionary = corpora.Dictionary(corpus)

tfidf = models.TfidfModel(corpus)
corpus_tfidf = tfidf[corpus]
corpus_tfidf.save('x.corpus_tfidf')

# To access the tfidf fitted corpus i've saved i used corpora.MmCorpus.load()
corpus_tfidf = corpora.MmCorpus.load('x.corpus_tfidf')

lda = models.ldamodel.LdaModel(corpus_tfidf, id2word=dictionary, num_topics=2)
corpus_lda = lda[corpus]
corpus_lda.save('x.corpus_lda')

for i,j in enumerate(corpus_lda):
  print j, corpus[i]

上面的代码会输出:

[(0, 0.54259038344543631), (1, 0.45740961655456358)] [(0, 1), (1, 1)]
[(0, 0.56718063124157458), (1, 0.43281936875842542)] [(0, 1)]
[(0, 0.54255407573666647), (1, 0.45744592426333358)] [(0, 1), (1, 1)]
[(0, 0.75229707773868093), (1, 0.2477029222613191)] [(0, 3), (1, 1)]

# [(<topic_number_from x.corpus_lda model>, 
#   <probability of this topic for this document>), 
#  (<topic# from lda model>, <prob of this top for this doc>)] [<document[i] from corpus>]

如果我想加载保存的 LDA 转换语料库,我应该使用 gensim 中的哪个类来加载?

我试过使用 corpora.MmCorpus.load(),它没有给我如上所示的转换语料库的相同输出:

>>> lda_corpus = corpora.MmCorpus.load('x.corpus_lda')
>>> for i,j in enumerate(lda_corpus):
...   print j, corpus[i]
... 
[(0, 0.55087839240547309), (1, 0.44912160759452685)] [(0, 1), (1, 1)]
[(0, 0.56715974584850259), (1, 0.43284025415149735)] [(0, 1)]
[(0, 0.54275680271070581), (1, 0.45724319728929413)] [(0, 1), (1, 1)]
[(0, 0.75233330695720912), (1, 0.24766669304279079)] [(0, 3), (1, 1)]

最佳答案

您的代码中还有更多问题。

要以 MatrixMarket 格式保存语料库,您需要

corpora.MmCorpus.serialize('x.corpus_lda', corpus_lda)

文档是 here .

您在 corpus_tfidf 上进行训练,但随后仅转换 lda[corpus](无 tfidf)。使用 tfidf 或普通的词袋,但始终如一地使用它。

关于python - 我应该使用哪个 gensim 语料库类来加载 LDA 转换后的语料库? - Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15184655/

相关文章:

python - 在 Python 中访问 void 指针(使用 SWIG 或其他东西)

python - 使用机器学习的段落分割

machine-learning - 定义文本分类中的词汇量

java - 如何 "update"一个现有的命名实体识别模型——而不是从头开始创建?

python - 如何为 python NLTK 构建翻译语料库?

python - 使用函数给定的值初始化 numpy 数组的最快方法

python - django websocket在循环中异步发送消息

python - Flask with Jinja 在第一页之后出现分页问题

python - 如何从文本语料库构建 PPMI 矩阵?

python - 有没有办法将 python pandas 数据框转换为 NLP 语料库或文档?