Select number of topics for LDA model

# library(printr)
# knitr::opts_chunk$set(cache=TRUE)
# knitr::opts_chunk$set(collapse = TRUE, comment = "#>")

Package can be installed from CRAN

install.packages("ldatuning")

or downloaded from the GitHub repository (developer version).

install.packages("devtools")
devtools::install_github("nikita-moor/ldatuning")

Package ldatuning realizes 4 metrics to select perfect number of topics for LDA model.

library("ldatuning")

Load "AssociatedPress" dataset from the topicmodels package.

library("topicmodels")
data("AssociatedPress", package="topicmodels")
dtm <- AssociatedPress[1:10, ]

The most easy way is to calculate all metrics at once. All existing methods require to train multiple LDA models to select one with the best performance. It is computation intensive procedure and ldatuning uses parallelism, so do not forget to point correct number of CPU cores in mc.core parameter to archive the best performance.

All standard LDA methods and parameters from topimodels package can be set with method and control.

result <- FindTopicsNumber(
  dtm,
  topics = seq(from = 2, to = 15, by = 1),
  metrics = c("Griffiths2004", "CaoJuan2009", "Arun2010", "Deveaud2014"),
  method = "Gibbs",
  control = list(seed = 77),
  mc.cores = 2L,
  verbose = TRUE
)

Result is a number of topics and corresponding values of metrics

knitr::kable(result)

Simple approach in analyze of metrics is to find extremum, more complete description is in corresponding papers:

Support function FindTopicsNumber_plot can be used for easy analyze of the results

FindTopicsNumber_plot(result)

Results calculated on the whole dataset (about 10 hours on quad-core computer) look like

result <- read.csv(file = "files/APress.csv", header = TRUE)
FindTopicsNumber_plot(result[result$topics < 500, ])

From this plot can be made conclusion that optimal number of topics is in range 90-140. Metric Deveaud2014 is not informative in this situation.

References



Try the ldatuning package in your browser

Any scripts or data that you put into this service are public.

ldatuning documentation built on April 21, 2020, 9:05 a.m.