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

2023-11-06

主题建模评估:连贯性分数(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 CoherenceModel

topics = [
    ['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 instance
    top_clusters:  numpy array containing indices of top_clusters
    n_words: top n number of words to include
    
    '''
    # create empty list to contain topics
    topics = []
    
    # iterate over top n clusters
    for cluster in top_clusters:
        # create sorted dictionary of word distributions
        sorted_dict = sorted(model.cluster_word_distribution[cluster].items(), key=lambda k: k[1], reverse=True)[:n_words]
         
        # create empty list to contain words
        topic = []
        
        # iterate over top n words in topic
        for k,v in sorted_dict:
            # append words to topic list
            topic.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

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

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

  • Python计算机视觉第七章 图像搜索

    文章目录 7 1基于内容的图像检索 从文本挖掘中获取灵感 矢量空间模型 7 2视觉单词 创建词汇 7 3图像索引 7 3 1建立数据库 7 3 2添加图像 7 4在数据库中搜索图像 7 4 1利用索引获取候选图像 7 4 2用一幅图像进行查
  • 如何在styles.xml中使用控件自定义属性

    开发过程中 对于通用控件的属性我们习惯在styles xml中抽取出来 然后在用到的地方通过 style style Your Style 引入 可以简化代码 在Material Design风格的app里面大量使用到CarView 但是C

随机推荐

  • VS中新建Qt项目工程后显示无法打开源文件“QtWidgets/QApplication”的解决方案

    1 环境 VS2015 Qt 5 6 2 现象描述 在vs中新建工程后一般都会显示无法打开源文件 QtWidgets QApplication 就像这样 3 原因 新建Qt项目时VC 包含目录没有自动包含Qt所需要的头文件路径 需要手动添加
  • VSCode一些小问题及解决方式

    01 插件安装目录改换 使用Installer安装VSCode 插件的默认安装目录为 C User
  • win10 安装SVN时提示2503的错误代码

    最近给别人装了一个win10 装完之后装sql 装vs 在装svn客户端时出现了以下错误 在网上找了好久 都说是权限不足 然后 就试了个中给权限的方法 1 在svn 安装包上 右键属性 设置完全控制 没解决 2 通过win R 命令提示符
  • 7、Mac iTerm2 + Zsh 打造舒适终端

    iTerm2 Zsh 打造舒适终端 最终效果图 一 准备工作 git xcode 本文默认各位同学已经安装了git环境和xcode command line tools 遇到提示找不到git命令或需要安装command line tool的
  • Java拷贝之深拷贝与浅拷贝

    Java中的拷贝分为引用拷贝和对象拷贝 1 引用拷贝 浅拷贝 引用拷贝 只会生成一个新的对象引用地址 但两个对峙最终指向的还是同一个对象 代码示例 定义的测试对象 Data public class User private String
  • 程序—java年月日转换

    年月日格式转换练习 目标 输入n组 0 lt n lt 100 8位或6位数字 将8位数转换为xxxx xx xx的格式 将6位数转换为xxxx xx的格式 举例 输入 19970102 199701 输出 1997 01 02 1997
  • 2023JavaWeb面试问答

    说一说Servlet的生命周期 Servlet有良好的生存期的定义 包括加载和实例化 初始化 处理请求以及服务结束 这个生存期由javax servlet Servlet接口的init service 和destroy方法表达 Servle
  • [综述] Generative AI meets 3D: A Survey on Text-to-3D in AIGC Era

    论文 改文章是23年5月27日挂在arxiv上 本文重点关注4 1节Text Guided 3D Avatar Generation 4 4节Text Guided 3D Shape Transformation和第5章Discussion
  • 第十一届泰迪杯B题全部问题部分代码

    数据预处理 导入需要的包 import pandas as pd import numpy as np df train pd read csv 数据 order train1 csv encoding utf 8 df train df
  • 安装MySQL数据库

    登录游戏需要账号和密码 进入游戏还会创建角色 服务器需要把这些账号和角色信息保存到硬盘里 这便会涉及到数据库 MySQL是游戏开发中最常用的数据库之一 它是当前最流行的关系型数据库管理系统 MySQL是一个关系型数据库管理系统 最早由瑞典M
  • 产品设计的步骤有哪些?

    饭要一口一口吃 一口吃不成个大胖子 事情应该一个接一个地做 越是匆忙和混乱 就会产生越多的问题 今天我们来谈谈产品设计的步骤 以便更好地进行产品设计 1 市场调查 对调查内容进行深入细致的调查研究 分类分析 包括 设计对象的经营理念和未来前
  • U盘安装Centos 7系统

    开始安装 一 制作U盘启动盘 参考 http jingyan baidu com article a378c960630e61b329283045 html 1 安装UltraISO 2 安装完成后点击 试用 3 点击文件 选择打开 4 找
  • Android Studio快捷开发(常用快捷键)

    本文记录自己常用的快捷开发操作 会持续更新 慢慢补 1 鼠标左键双击选中所点击的部分 2 在句末鼠标左键双击选中该句 3 在 大括号前后鼠标左键双击选中该 大括号包裹的代码段 xml文件中在 lt gt 前后双击也可以选择代码段 4 鼠标点
  • c语言显示器编程,VC实现Windows多显示器编程的方法

    本文实例讲述了VC实现Windows多显示器编程的方法 分享给大家供大家参考 具体如下 一 Windows中接入多个显示器时 可设置为复制和扩展屏 1 设置为复制屏幕时 多个显示器的分辨率是一样的 位置为0 分辨率值 2 设置为扩展屏幕时
  • ubuntu安装redis

    可以自己下载安装包 然后上传到服务器上 或者直接下载 wget c http download redis io releases redis 5 0 7 tar gz 解压 tar zxvf redis 5 0 7 tar gz 进入re
  • Windows 下OpenSSL安装过程及错误解决办法

    Windows下使用OpenSSL有两种方式 一 直接下载别人编译好的安装包 http slproweb com products Win32OpenSSL html 二 自己编译安装 1 下载并安装perl http www active
  • Error: getaddrinfo ENOTFOUND localhost

    根据报错内容 推断是localhost的问题 有可能是localhost没有绑定127 0 0 1 我就当是localhost没有绑定127 0 0 1 1 打开hosts文件 终端执行 sudo vim etc hosts 打开hosts
  • 笔记本gtx1650最好用驱动_各型号笔记本显卡定位

    笔记本显卡目前主要有三大阵营 分别是NVIDA显卡 AMD显卡以及Intel处理器内置的核心显卡 其中NVIDA显卡在笔记本领域中 占据的份额最高 其次是AMD笔记本显卡 最后是Intel处理器内置的核心显卡 显卡主要影响游戏性能表现 对于
  • java的封装继承和多态

    封装 继承和多态 封裝 定义 面向对象编程语言 需要对现实世界中的事物进行抽象 模拟 现实世界中的对象属性 都是隐藏 在对象内部的 外界无法直接操作和修改 在类中定义属性的时候 一般需要把属性隐藏起来 如果外界需要访问这个属性 那么就需要提
  • 【自然语言处理】主题建模评估:连贯性分数(Coherence Score)

    主题建模评估 连贯性分数 Coherence Score 1 主题连贯性分数 主题连贯性分数 Coherence Score 是一种客观的衡量标准 它基于语言学的分布假设 具有相似含义的词往往出现在相似的上下文中 如果所有或大部分单词都密切