python - 如何使用经过训练的 LDA 模型使用 gensim 预测新查询的主题?

标签 python nlp lda topic-modeling gensim

我已经使用 gensim 为 LDA 主题建模训练了一个语料库。

浏览 gensim 网站上的教程(这不是全部代码):

question = 'Changelog generation from Github issues?';

temp = question.lower()
for i in range(len(punctuation_string)):
    temp = temp.replace(punctuation_string[i], '')

words = re.findall(r'\w+', temp, flags = re.UNICODE | re.LOCALE)
important_words = []
important_words = filter(lambda x: x not in stoplist, words)
print important_words
dictionary = corpora.Dictionary.load('questions.dict')
ques_vec = []
ques_vec = dictionary.doc2bow(important_words)
print dictionary
print ques_vec
print lda[ques_vec]

这是我得到的输出:

['changelog', 'generation', 'github', 'issues']
Dictionary(15791 unique tokens)
[(514, 1), (3625, 1), (3626, 1), (3627, 1)]
[(4, 0.20400000000000032), (11, 0.20400000000000032), (19, 0.20263215848547525), (29, 0.20536784151452539)]

我不知道最后的输出如何帮助我找到问题的可能主题!!!

请帮忙!

最佳答案

我在 python 中编写了一个函数,它为新查询提供了可能的主题:

def getTopicForQuery (question):
    temp = question.lower()
    for i in range(len(punctuation_string)):
        temp = temp.replace(punctuation_string[i], '')

    words = re.findall(r'\w+', temp, flags = re.UNICODE | re.LOCALE)

    important_words = []
    important_words = filter(lambda x: x not in stoplist, words)

    dictionary = corpora.Dictionary.load('questions.dict')

    ques_vec = []
    ques_vec = dictionary.doc2bow(important_words)

    topic_vec = []
    topic_vec = lda[ques_vec]

    word_count_array = numpy.empty((len(topic_vec), 2), dtype = numpy.object)
    for i in range(len(topic_vec)):
        word_count_array[i, 0] = topic_vec[i][0]
        word_count_array[i, 1] = topic_vec[i][1]

    idx = numpy.argsort(word_count_array[:, 1])
    idx = idx[::-1]
    word_count_array = word_count_array[idx]

    final = []
    final = lda.print_topic(word_count_array[0, 0], 1)

    question_topic = final.split('*') ## as format is like "probability * topic"

    return question_topic[1]

在进行此操作之前,请引用 this链接!

在代码的初始部分,对查询进行了预处理,以便去除停用词和不必要的标点符号。

然后,加载使用我们自己的数据库制作的字典。

然后,我们将新查询的标记转换为词袋,然后查询的主题概率分布由 topic_vec = lda[ques_vec] 计算,其中 lda 是上面提到的链接中解释的训练模型。

然后根据主题的概率对分布进行排序。然后,question_topic[1] 显示概率最高的主题。

关于python - 如何使用经过训练的 LDA 模型使用 gensim 预测新查询的主题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16262016/

相关文章:

python - 异常后恢复Python程序?

python - 使用 py2exe 时使用 Numpy 创建一个 tcl 文件夹

nlp - 我应该研究机器学习的哪些领域来自动从消息中提取某些信息

scala - Spark 1.5 MlLib LDA - 获取新文档的主题分布

python - 将 Python 字典写入 CSV

python - 在 Python 2.7 中,通过 super(self.__class__, self)... 调用 super 构造函数不是更好吗?

python - 使用 NLTK 训练自定义 BIO 标记

python - FastText - 由于 C++ 扩展无法分配内存而无法加载 model.bin

matlab - 线性判别分析LDA

python - LDA基因模拟。如何使用每个文档的正确主题编号更新 Postgres 数据库?