首页 > 解决方案 > 检测不同主题模型之间的文本相似性

问题描述

在主题建模方法中,我们有两个不同的主题模型结果,如下所示:

library(dplyr)
library(ggplot2)
library(stm)
library(janeaustenr)
library(tidytext)

library(quanteda)
testDfm <- gadarian$open.ended.response %>%
    tokens(remove_punct = TRUE, remove_numbers = TRUE, remove_symbols = TRUE)  %>%
    dfm()
    
out <- convert(testDfm, to = "stm")
documents <- out$documents
vocab <- out$vocab
meta <- out$meta

topic_model1 <- stm(documents = out$documents, vocab = out$vocab, K = 5)
topic_model2 <- stm(documents = out$documents, vocab = out$vocab, K = 3)

让我们称它们为 topic_model1 和 topic_model2(也许使用不同的数据输入可能会更好,但由于可重复性原因,gadarian 数据集是最容易的)。

有没有办法比较两个模型的文本结果并提供某种元分析或创建任何图表来比较两个模型的主题?

标签: rquanteda

解决方案


两个模型的比较有点棘手——因为我们有单词、主题、两个模型,当然还有 beta 值。可视化一个模型的简单图表如下:

library(tidytext)
library(dplyr)
library(ggplot2)

tidytext::tidy(topic_model2) %>% 
  dplyr::group_by(topic) %>% 
  dplyr::slice_max(beta, n = 5) %>% # just the top 5 beta values to keep the plot readable
  ggplot2::ggplot(aes(reorder(term, beta), beta))+
  ggplot2::geom_col() +
  ggplot2::coord_flip() +
  ggplot2::facet_wrap(~topic)

在此处输入图像描述

可以使用和改进这种方法来并排制作每个模型的热图:

tidytext::tidy(topic_model1) %>% 
  dplyr::group_by(topic) %>% 
  dplyr::slice_max(beta, n = 5) %>% 
  dplyr::mutate(MODEL = "K5") %>% 
  dplyr::union(tidytext::tidy(topic_model2) %>% 
                     dplyr::group_by(topic) %>% 
                     dplyr::slice_max(beta, n = 5) %>% 
                     dplyr::mutate(MODEL = "K3") ) %>% 
  ggplot2::ggplot(aes(topic, term, fill = beta)) +
  ggplot2::geom_tile() +
  ggplot2::facet_wrap(~MODEL) 

在此处输入图像描述

您可以查看本教程和案例以获得一些灵感:https ://www.tidytextmining.com/topicmodeling.html


推荐阅读