主题建模评估:连贯性分数(Coherence Score)

1.主题连贯性分数

主题连贯性分数(Coherence Score)是一种客观的衡量标准,它基于语言学的分布假设:具有相似含义的词往往出现在相似的上下文中。 如果所有或大部分单词都密切相关,则主题被认为是连贯的。

推荐阅读:Full-Text or Abstract ? Examining Topic Coherence Scores Using Latent Dirichlet Allocation

2.计算 LDA 模型的 Coherence Score

2.1 导入包

import pandas as pd
import numpy as np
from gensim.corpora import Dictionary
from gensim.models import LdaMulticore

2.2 数据预处理

# cast tweets to numpy array
docs = df.tweet_text.to_numpy()# create dictionary of all words in all documents
dictionary = Dictionary(docs)# filter extreme cases out of dictionary
dictionary.filter_extremes(no_below=15, no_above=0.5, keep_n=100000)# create BOW dictionary
bow_corpus = [dictionary.doc2bow(doc) for doc in docs]

2.3 构建模型

LdaMulticore:使用所有 CPU 内核并行化并加速模型训练。

  • workers:用于并行化的工作进程数。
  • passes:训练期间通过语料库的次数。
# create LDA model using preferred hyperparameters
lda_model = LdaMulticore(bow_corpus, num_topics=5, id2word=dictionary, passes=4, workers=2, random_state=21)# Save LDA model to disk
path_to_model = ""
lda_model.save(path_to_model)# for each topic, print words occuring in that topic
for idx, topic in lda_model.print_topics(-1):print('Topic: {} \nWords: {}'.format(idx, topic))

2.4 计算 Coherence Score

我们可以使用 Gensim 库中的 CoherenceModel 轻松计算主题连贯性分数。 对于 LDA,它的实现比较简单:

# import library from gensim
from gensim.models import CoherenceModel# instantiate topic coherence model
cm = CoherenceModel(model=lda_model, corpus=bow_corpus, texts=docs, coherence='c_v')# get topic coherence score
coherence_lda = cm.get_coherence()
print(coherence_lda)

3.计算 GSDMM 模型的 Coherence Score

GSDMM(Gibbs Sampling Dirichlet Multinomial Mixture)是一种基于狄利克雷多项式混合模型的收缩型吉布斯采样算法(a collapsed Gibbs Sampling algorithm for the Dirichlet Multinomial Mixture model)的简称,它是发表在 2014 2014 2014 年 KDD 上的论文《A Dirichlet Multinomial Mixture Model-based Approach for Short Text Clustering》的数学模型。

GSDMM 主要用于短文本聚类,短文本聚类是将大量的短文本(例如微博、评论等)根据计算某种相似度进行聚集,最终划分到几个类中的过程。GSDMM 主要具备以下优点:

  • 可以自动推断聚类的个数,并且可以快速地收敛;
  • 可以在完备性和一致性之间保持平衡;
  • 可以很好的处理稀疏、高纬度的短文本,可以得到每一类的代表词汇;
  • 较其它的聚类算法,在性能上表现更为突出。

3.1 安装并导入包

pip install git+https://github.com/rwalk/gsdmm.git
import pandas as pd
import numpy as np
from gensim.corpora import Dictionary
from gsdmm import MovieGroupProcess

3.2 数据预处理

# cast tweets to numpy array
docs = df.tweet_text.to_numpy()# create dictionary of all words in all documents
dictionary = Dictionary(docs)# filter extreme cases out of dictionary
dictionary.filter_extremes(no_below=15, no_above=0.5, keep_n=100000)# create variable containing length of dictionary/vocab
vocab_length = len(dictionary)# create BOW dictionary
bow_corpus = [dictionary.doc2bow(doc) for doc in docs]

3.3 构建模型

# initialize GSDMM
gsdmm = MovieGroupProcess(K=15, alpha=0.1, beta=0.3, n_iters=15)# fit GSDMM model
y = gsdmm.fit(docs, vocab_length)

# print number of documents per topic
doc_count = np.array(gsdmm.cluster_doc_count)
print('Number of documents per topic :', doc_count)# Topics sorted by the number of document they are allocated to
top_index = doc_count.argsort()[-15:][::-1]
print('Most important clusters (by number of docs inside):', top_index)# define function to get top words per topic
def top_words(cluster_word_distribution, top_cluster, values):for cluster in top_cluster:sort_dicts = sorted(cluster_word_distribution[cluster].items(), key=lambda k: k[1], reverse=True)[:values]print("\nCluster %s : %s"%(cluster, sort_dicts))# get top words in topics
top_words(gsdmm.cluster_word_distribution, top_index, 20)

3.4 结果可视化

# Import wordcloud library
from wordcloud import WordCloud# Get topic word distributions from gsdmm model
cluster_word_distribution = gsdmm.cluster_word_distribution# Select topic you want to output as dictionary (using topic_number)
topic_dict = sorted(cluster_word_distribution[topic_number].items(), key=lambda k: k[1], reverse=True)[:values]# Generate a word cloud image
wordcloud = WordCloud(background_color='#fcf2ed', width=1800,height=700,font_path=path_to_font,colormap='flag').generate_from_frequencies(topic_dict)# Print to screen
fig, ax = plt.subplots(figsize=[20,10])
plt.imshow(wordcloud, interpolation='bilinear')
plt.axis("off");# Save to disk
wordcloud_24.to_file(path_to_file)

3.5 计算 Coherence Score

Gensim 官网对 LDA 之外的模型使用另一种方法计算 连贯性分数

from gensim.test.utils import common_corpus, common_dictionary
from gensim.models.coherencemodel import CoherenceModeltopics = [['human', 'computer', 'system', 'interface'],['graph', 'minors', 'trees', 'eps']
]cm = CoherenceModel(topics=topics, corpus=common_corpus, dictionary=common_dictionary, coherence='u_mass')coherence = cm.get_coherence()  # get coherence value

GSDMM 的实现需要更多的工作,因为我们首先必须将 主题中的单词作为列表(变量主题)获取,然后将其输入 CoherenceModel。

# import library from gensim
from gensim.models import CoherenceModel# define function to get words in topics
def get_topics_lists(model, top_clusters, n_words):'''Gets lists of words in topics as a list of lists.model: gsdmm instancetop_clusters:  numpy array containing indices of top_clustersn_words: top n number of words to include'''# create empty list to contain topicstopics = []# iterate over top n clustersfor cluster in top_clusters:# create sorted dictionary of word distributionssorted_dict = sorted(model.cluster_word_distribution[cluster].items(), key=lambda k: k[1], reverse=True)[:n_words]# create empty list to contain wordstopic = []# iterate over top n words in topicfor k,v in sorted_dict:# append words to topic listtopic.append(k)# append topics to topics list    topics.append(topic)return topics# get topics to feed to coherence model
topics = get_topics_lists(gsdmm, top_index, 20) # evaluate model using Topic Coherence score
cm_gsdmm = CoherenceModel(topics=topics, dictionary=dictionary, corpus=bow_corpus, texts=docs, coherence='c_v')# get coherence value
coherence_gsdmm = cm_gsdmm.get_coherence()  print(coherence_gsdmm)

原文:Short-Text Topic Modelling: LDA vs GSDMM

【自然语言处理】主题建模评估:连贯性分数(Coherence Score)相关推荐

  1. 【自然语言处理】不同策略的主题建模方法比较

    不同策略的主题建模方法比较 本文将介绍利用 LSA.pLSA.LDA.NMF.BERTopic.Top2Vec 这六种策略进行主题建模之间的比较. 1.简介 在自然语言处理(NLP)中,主题建模一词包 ...

  2. 【自然语言处理】主题建模:BERTopic(实战篇)

    主题建模:BERTopic(实战篇) BERTopic 是基于深度学习的一种主题建模方法. 2018 2018 2018 年底, D e v l i n e t a l . Devlin\ et\ a ...

  3. 犀牛建模软件的英文语言包_使用tidytext和textmineR软件包在R中进行主题建模(

    犀牛建模软件的英文语言包 In this article, we will learn to do Topic Model using tidytext and textmineR packages ...

  4. 独家 | 使用Python的LDA主题建模(附链接)

    作者:Kamil Polak翻译:刘思婧 校对:孙韬淳本文约2700字,建议阅读5分钟本文为大家介绍了主题建模的概念.LDA算法的原理,示例了如何使用Python建立一个基础的LDA主题模型,并使用p ...

  5. 独家 | 利用Python实现主题建模和LDA 算法(附链接)

    作者:Susan Li翻译:陈之炎校对:陈汉青本文约1900字,建议阅读5分钟在这篇文章,我们将LDA应用于一组文档,并将文档按照主题分类. 标签:LDA 算法 主题建模是一种用于找出文档集合中抽象& ...

  6. 一文读懂如何用LSA、PSLA、LDA和lda2vec进行主题建模

    选自 Medium,作者:Joyce X,机器之心编译. 本文是一篇关于主题建模及其相关技术的综述.文中介绍了四种最流行的技术,用于探讨主题建模,它们分别是:LSA.pLSA.LDA,以及最新的.基于 ...

  7. 主题建模-corpora语料库-PCA进行降维

    https://colab.research.google.com/drive/1F-1Ej7T2xnUKXSmDPjjOChNbBTvQlpnM?usp=sharing 考试 https://col ...

  8. python建模大赛算法_利用Python实现主题建模和LDA 算法(附链接)

    主题建模是一种用于找出文档集合中抽象"主题"的统计模型.LDA(Latent Dirichlet Allocation)是主题模型的一个示例,用于将文档中的文本分类为特定的主题.L ...

  9. 独家 | LDA主题建模和pyLDAvis可视化

    作者:Xuan Qi 翻译:方星轩 校对:欧阳锦 本文约1700字,建议阅读6分钟 本文的数据来自美国著名电视节目<老友记>.作者用python-Beautiful Soup抓取了224集 ...

最新文章

  1. virtualbox 创建桥接网络_Windows 10下的Virtualbox中的桥接网络不起作用
  2. centos7下nginx配置
  3. 机器学习基础-主成分分析PCA-16
  4. android137 360 双击三击事件
  5. centos禁用exec_CentOS停用按下Ctrl-Alt-Del 重启系统的功能
  6. 【转】shell十三问,为linux学习打基础(上)
  7. Practice Lab 7:路由再分发
  8. 关于java和C语言i=i++问题描述
  9. 小米销量被荣耀赶超:手机枭雄如何跌落神坛?
  10. 百度关键词排名提升软件-免费百度关键词排名提升工具
  11. 使用Dotfuscator混淆winphone8应用XAP
  12. 文件被后台程序占用无法删除_Windows系统中,教你彻底删除C盘的顽固文件,瞬间多出10个G...
  13. 国内十大白银期货APP最新排名
  14. 一文读懂蓝绿发布、A/B 测试和金丝雀发布的优缺点
  15. python打包deb_python开发将项目打包成deb
  16. 香港云服务器网站备案,中国香港云服务器网站备案
  17. AtCoder Grand Contest 030 (AGC030) C - Coloring Torus 构造
  18. npm官网注册账号失败
  19. ACM-NEFU新生训练2-排序和CMP
  20. quectel(调用相关命令)7

热门文章

  1. 架构拆分:如何让笨重的系统架构变灵巧?
  2. 最黑外包文思海辉西安分公司(连载二之法院结果)
  3. java接口能定义非抽象方法吗_接口中只能定义常量和抽象方法,对么
  4. 用VMware虚拟机安装Ubuntu时出现窗口显示不完全的解决方案
  5. 7的整除特征 三位一截_整数的整除特征
  6. vue自定义一个指令实现el-input-number组件显示千分号,但实际拿到的值是number类型
  7. 拳皇重生服务器维护,便捷培养之格斗家重生系统降临
  8. 计算机应用基础网络题的视频,计算机应用基础统考题库 2016年4月网络统考演示文稿...
  9. 浅谈未来趋势Web 3.0时代
  10. LEADTOOLS医学影像本地部署环境设置以及部署教程