如何使用Gensim获取LDA模型的最佳主题数?

11

我正在尝试在Gensim中获取LDA模型的最佳主题数量。 我发现的一种方法是计算每个模型的对数似然,并将其与其他模型进行比较,例如在使用潜在狄利克雷分配的输入参数上。

因此,我研究了如何使用Gensim计算LDA模型的对数似然,并找到了以下帖子:如何估计潜在狄利克雷分配模型的α参数?

它基本上说明update_alpha()方法实现了《Huang,Jonathan. Dirichlet分布参数的最大似然估计》中描述的方法。 但我不知道如何在不更改代码的情况下使用库获取此参数。

我如何使用Gensim从LDA模型获取对数似然?

有没有更好的方法在Gensim中获得最佳主题数量?


你可以在这里找到关于“最佳”主题数量的答案:http://stackoverflow.com/questions/31729227/how-to-evaluate-the-best-k-for-lda-using-mallet。实际上,你所谓的最佳主题数量取决于你想在数据中看到什么。 - Sir Cornflakes
你找到可能性了吗? - Peanut
2个回答

15
一般的经验法则是创建不同主题数的LDA模型,然后检查每个模型的Jaccard相似度和连贯性。在这种情况下,连贯性通过主题中得分高的词之间的语义相似度来衡量(这些词是否在文本语料库中同时出现)。以下内容将为最佳主题数提供强烈的直觉。在尝试使用分层狄利克雷过程之前,应该先建立一个基线,因为在实际应用中发现该技术存在问题。
首先,为你想要考虑的各种主题数量创建模型和主题单词的字典,其中在这种情况下,corpus是清理后的标记,num_topics是你想要考虑的主题列表,num_words是你想要考虑的每个主题的前几个高频词的数量。
import seaborn as sns
import matplotlib.pyplot as plt
import numpy as np
from gensim.models import LdaModel, CoherenceModel
from gensim import corpora

dirichlet_dict = corpora.Dictionary(corpus)
bow_corpus = [dirichlet_dict.doc2bow(text) for text in corpus]

# Considering 1-15 topics, as the last is cut off
num_topics = list(range(16)[1:])
num_keywords = 15

LDA_models = {}
LDA_topics = {}
for i in num_topics:
    LDA_models[i] = LdaModel(corpus=bow_corpus,
                             id2word=dirichlet_dict,
                             num_topics=i,
                             update_every=1,
                             chunksize=len(bow_corpus),
                             passes=20,
                             alpha='auto',
                             random_state=42)

    shown_topics = LDA_models[i].show_topics(num_topics=i, 
                                             num_words=num_keywords,
                                             formatted=False)
    LDA_topics[i] = [[word[0] for word in topic[1]] for topic in shown_topics]

现在创建一个函数来计算两个主题的Jaccard相似度:
def jaccard_similarity(topic_1, topic_2):
    """
    Derives the Jaccard similarity of two topics

    Jaccard similarity:
    - A statistic used for comparing the similarity and diversity of sample sets
    - J(A,B) = (A ∩ B)/(A ∪ B)
    - Goal is low Jaccard scores for coverage of the diverse elements
    """
    intersection = set(topic_1).intersection(set(topic_2))
    union = set(topic_1).union(set(topic_2))
                    
    return float(len(intersection))/float(len(union))

使用上述方法通过考虑下一个主题来推导跨主题的稳定性均值:

LDA_stability = {}
for i in range(0, len(num_topics)-1):
    jaccard_sims = []
    for t1, topic1 in enumerate(LDA_topics[num_topics[i]]): # pylint: disable=unused-variable
        sims = []
        for t2, topic2 in enumerate(LDA_topics[num_topics[i+1]]): # pylint: disable=unused-variable
            sims.append(jaccard_similarity(topic1, topic2))    
        
        jaccard_sims.append(sims)    
    
    LDA_stability[num_topics[i]] = jaccard_sims
                
mean_stabilities = [np.array(LDA_stability[i]).mean() for i in num_topics[:-1]]

gensim内置了一个主题连贯性模型(使用'c_v'选项):

coherences = [CoherenceModel(model=LDA_models[i], texts=corpus, dictionary=dirichlet_dict, coherence='c_v').get_coherence()\
              for i in num_topics[:-1]]

从这里可以通过每个主题的连贯性和稳定性之间的差异大致推导出理想的主题数量:

coh_sta_diffs = [coherences[i] - mean_stabilities[i] for i in range(num_keywords)[:-1]] # limit topic numbers to the number of keywords
coh_sta_max = max(coh_sta_diffs)
coh_sta_max_idxs = [i for i, j in enumerate(coh_sta_diffs) if j == coh_sta_max]
ideal_topic_num_index = coh_sta_max_idxs[0] # choose less topics in case there's more than one max
ideal_topic_num = num_topics[ideal_topic_num_index]

最后在主题数量上绘制这些指标的图表:
plt.figure(figsize=(20,10))
ax = sns.lineplot(x=num_topics[:-1], y=mean_stabilities, label='Average Topic Overlap')
ax = sns.lineplot(x=num_topics[:-1], y=coherences, label='Topic Coherence')

ax.axvline(x=ideal_topic_num, label='Ideal Number of Topics', color='black')
ax.axvspan(xmin=ideal_topic_num - 1, xmax=ideal_topic_num + 1, alpha=0.5, facecolor='grey')

y_max = max(max(mean_stabilities), max(coherences)) + (0.10 * max(max(mean_stabilities), max(coherences)))
ax.set_ylim([0, y_max])
ax.set_xlim([1, num_topics[-1]-1])
                
ax.axes.set_title('Model Metrics per Number of Topics', fontsize=25)
ax.set_ylabel('Metric Level', fontsize=20)
ax.set_xlabel('Number of Topics', fontsize=20)
plt.legend(fontsize=20)
plt.show()   

enter image description here

您理想的主题数量应最大化连贯性并最小化基于Jaccard相似度的主题重叠。在这种情况下,选择约14个主题数量是比较安全的。


有人能详细说明一下层次狄利克雷过程在实践中存在的问题吗? - dgrogan
您选择的主题数量也只是最大相干分数。这种情况不会每次都发生吗? - Desi Pilla

6

虽然我不能针对Gensim发表评论,但我可以提供一些优化主题的一般建议。

正如你所说,使用对数似然是一种方法。另一个选择是在模型生成过程中保留一组文档,并在模型完成后推断这些文档上的主题并检查其是否合理。

您可以尝试完全不同的方法,即分层狄利克雷过程,该方法可以动态地找到语料库中的主题数量而无需指定。

有许多论文介绍如何最佳指定参数和评估主题模型,根据您的经验水平,这些可能或可能不适合您:

重新思考LDA:为什么先验很重要, Wallach, H.M., Mimno, D. and McCallum, A.

主题模型的评估方法, Wallach H.M., Murray, I., Salakhutdinov, R. and Mimno, D.

此外,这是关于分层狄利克雷过程的论文:

分层狄利克雷过程, Teh, Y.W., Jordan, M.I., Beal, M.J. and Blei, D.M.


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接