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

news2024/9/20 23:27:32

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

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/188980.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

如何使用ArcGIS计算道路中心线

1.概述 在制图等应用的时候,有时需要将双线的面状道路提取中心线,转换为线状的道路。 由于道路多为不规则的图形,提取难度比较高,加上能提取中心线的软件有限,更加增加了提取的难度。 ArcGIS虽然提供了提取中心线的…

C语言文件操作(二)

文件的随机读写fseek函数#include <stdio.h>int main() {FILE* pf fopen("test.txt", "r");if (NULL pf){perror("fopen");return 1;}char ch fgetc(pf);printf("%c\n", ch);fseek(pf, 2, SEEK_SET);ch fgetc(pf);printf(&q…

Mysql第四期 运算符规则计算】

文章目录写在前面1.算数运算符2.比较运算符3.逻辑运算符4.位运算符5.运算符的优先级拓展&#xff1a;使用正则表达式查询写在前面 基本的运算符号在计算机编程领域都是相通的&#xff0c;会有自己的一些特定符号语言&#xff0c;就像是各地的普通话一样&#xff0c;尽管语音描…

C语言小题,又3个学生的信息,放在结构体数组中,要求输出全部学生的信息。(指向结构体数组的指针)

前言&#xff1a; 此篇是针对 指向结构体数组的指针 方面的练习。 解题思路&#xff1a; 用指向结构体变量的指针来处理&#xff1a; &#xff08;1&#xff09;声明结构体类型 struct Student &#xff0c;并定义结构体数组&#xff0c;同时使之初始化&#xff1b; &#xff…

SpringBoot项目如何引入外部jar及将外部jar打包到项目发布war包

1 Springboot项目如何打成war包 1.1 环境准备 打包成war整体思路就是排查web容器依赖&#xff0c;添加maven-war-plugin插件。接下来就使用Tomcat容器给大家做个示范&#xff0c;亲测有效。 在讲解下说明一下环境&#xff0c;避免因为环境的问题&#xff0c;给大家带来不必要…

设计师都在用的5个设计素材库

作为一名设计师推荐几个设计素材网站&#xff0c;建议收藏起来&#xff01; 1、菜鸟图库 https://www.sucai999.com/?vNTYxMjky 站内平面海报、UI设计、电商淘宝、高清图片、样机模板等素材非常齐全。还有在线抠图、CDR版本转换功能&#xff0c;能有效的为设计师节省找素材时…

嵌入式Linux-线程属性

1. 线程的属性 1.1 概念 如前所述&#xff0c;调用 pthread_create()创建线程&#xff0c;可对新建线程的各种属性进行设置。在 Linux 下&#xff0c;使用pthread_attr_t 数据类型定义线程的所有属性。 调用 pthread_create()创建线程时&#xff0c;参数 attr 设置为 NULL&a…

Three.js 初阶入门篇(一)

系列文章目录 文章目录系列文章目录学习背景一、什么是3D&#xff08;直接看作品吧&#xff09;&#xff1f;汽车作品欣赏鼠标可以随意转动角度打开机盖&#xff08;交互效果&#xff09;尾部3D链接&#x1f517;如下&#xff08;链接打开会有一些慢&#xff09;二、如何创建一…

零入门容器云网络实战-7->Mac环境下为虚拟机磁盘空间进行扩容

在Mac环境下&#xff0c;使用PD软件创建的虚拟机磁盘空间不够时&#xff0c;如何扩容呢&#xff1f; 主要分两大步骤&#xff1a; 先通过PD界面&#xff0c;设置增加多少空间进入虚拟机里&#xff0c;通过fdisk等相关命令&#xff0c;使其增加的空间生效 1、第一大步&#xf…

机器学习之线性模型

定义 线性模型非常常见&#xff0c;但详细了解其中原理是必要的。 一般将样本特征进行线性组合达到预测的目标&#xff0c;如表达式yf(X;W)byf(X;W)byf(X;W)b,其中XXX为输入的样本数据&#xff0c;WWW为权重系数&#xff0c;bbb为偏置系数。 如对于图片样本&#xff0c;一种…

兔年春晚一大怪像,影视演员变成了万能,专业歌手却被晾在一边

怪事年年有&#xff0c;今年特别多。谁也没有想到&#xff0c;兔年春节还没有过去&#xff0c;就出现了一种奇怪的现象。中央电视台春晚&#xff0c;曾经执全国春晚之牛耳&#xff0c;然而谁能想到&#xff0c;四十多年后的今天&#xff0c;曾经的扛把子却变成了鸡肋。 今年央视…

【C++初阶】七、STL---vector(总)|vector的介绍|vector的使用

目录 一、vector的介绍 二、vector的使用 2.1 Construct 2.2 operator 2.3 Iterators 2.4 Capacity 2.5 Element access 2.6 Modifiers 一、vector的介绍 前面学习了 string类&#xff0c;所以 vector 的学习成本很低&#xff0c;因为接口都大致相同&#xff0c;功能也…

【促进开发】上海道宁与DHTMLX为您提供易于使用且功能丰富的JavaScript组件

DHTMLX提供 有效且专业设计的 JavaScript/HTML5工具 使开发人员 能够以更少的时间和精力 创建具有丰富界面和快速性能的 复杂Web和移动应用程序 DHTMLX使用 JavaScript UI 库促进开发 易于使用且功能丰富的 JavaScript组件 非常适合您在任何领域和 任何复杂性中的解…

SpringCloud微服务项目实战 - 7.kafka及文章上下架

一步一步地苦熬苦掖&#xff0c;终于我们也看见了花团锦簇&#xff0c;我们也知道了彩灯佳话。那一夜&#xff0c;我也曾梦见百万雄兵。 系列文章目录 项目搭建App登录及网关App文章自媒体平台&#xff08;博主后台&#xff09;内容审核(自动)延迟任务 文章目录系列文章目录一…

并查集应用

一、并查集模板 int find(int x) {if(p[x]!x) p[x]find(p[x]);return p[x]; }并查集高效率的核心是一旦更新过一次后&#xff0c;就会将路径压缩掉&#xff0c;避免后续重复遍历路径。 二、并查集应用 1、格子游戏 分析&#xff1a;每构成一个方框&#xff0c;当最后两个点连…

RA4M2开发(2)----基于IIC驱动OLED

概述 在e2studio中创建新的工程并导入必要的文件&#xff0c;包括I2C驱动代码和SSD1306 OLED显示驱动代码。配置RA4M2的I2C接口&#xff0c;使其作为I2C master进行通信。初始化SSD1306 OLED显示驱动代码&#xff0c;并配置显示屏的物理地址和分辨率。通过I2C驱动代码将数据写…

【Linux】初识环境变量

文章目录环境变量引入初见环境变量和环境变量有关的指令如何通过代码获取环境变量getenv()main函数的命令行参数第三方变量environ程序变量可以继承给子进程环境变量引入 Linux中有各种指令&#xff0c; 每个指令其实都是一个可执行程序&#xff1a; 和我们自己写的C语言代码…

API自动化测试【postman生成报告】

PostMan生成测试报告有两种&#xff1a; 1、控制台的模式 2、HTML的测试报告 使用到一个工具newman Node.js是前端的一个组件&#xff0c;主要可以使用它来开发异步的程序。 一、控制台的模式 1、安装node.js 双击node.js进行安装&#xff0c;安装成功后在控制台输入node…

Ansys Zemax | 多模光纤耦合

本文展示了利用几何图像分析特性来计算多模光纤耦合效率的方法。 还有使用IMAE操作数优化多模光纤耦合效率的方法。该方法只适用于包含大量模式的多模光纤。 下载 联系工作人员获取附件 简介 我们可以使用OpticStudio中的几何图像分析&#xff08;Geometric Image Analysi…

已解决error: legacy-instal1-failure

已解决&#xff08;pip install wxPython安装失败&#xff09;error: legacy-instal1-failure Encountered error while trying to install package.wxPython note: This is an issue with the package mentioned above&#xff0c;not pip. hint : See above for output from …