To use the mallet R package, we need to use rJava, an R
package for using Java within R (to access the mallet Java code). See
details at github.com/s-u/rJava.
Next, install the mallet R package from CRAN. To
install, simply use install.packages()
Depending on the size of your data, it can be so that you need to
increase the Java virtual machine (JVM) heap memory to handle larger
corpora. To do this, you need to specify how much memory you want to
allocate to the JVM using the Xmx flag. Below is an example
of allocating 4 Gb to the JVM.
To load the package, use library().
There are multiple ways to read text data into R. A simple way is to
read individual text files into a character vector. Below is an example
of reading the different stop list txt files that come with the
mallet package into R as a character vector (that can be
used by the mallet R package as data).
# Note this is the path to the folder where the stoplists are stored in the R package.
# Change this path to another directory to read other txt files into R.
directory <- system.file("stoplists", package = "mallet")
files_in_directory <- list.files(directory, full.names = TRUE)
txt_file_content <- character(length(files_in_directory))
for(i in seq_along(files_in_directory)){
txt_file_content[i] <- paste(readLines(files_in_directory[i]), collapse = "\n")
}
# We can check the content with str()
str(txt_file_content)## chr [1:6] "aber\nals\nam\nan\nauch\nauf\naus\nbei\nbin\nbis\nbist\nda\ndadurch\ndaher\ndarum\ndas\ndaß\ndass\ndein\ndeine\"| __truncated__ ...
We will now use the example data set of the State of the Union
addresses from 1946 to 2000 that is included with the
mallet R package as a data.frame. This data
can be accessed as follows.
##
## Attaching package: 'dplyr'
## The following objects are masked from 'package:stats':
##
## filter, lag
## The following objects are masked from 'package:base':
##
## intersect, setdiff, setequal, union
## [1] "To the Congress of the United States: "
## [2] "A quarter century ago the Congress decided that it could no longer consider the financial programs of the various departments on a piecemeal basis. Instead it has called on the President to present a comprehensive Executive Budget. The Congress has shown its satisfaction with that method by extending the budget system and tightening its controls. The bigger and more complex the Federal Program, the more necessary it is for the Chief Executive to submit a single budget for action by the Congress. "
Mallet also comes with five different stop list files (see above). We can access the path to these lists as follows.
## [1] "de" "en" "fi" "fr" "jp"
As a first step, we need to create an LDA trainer object and supply
the trainer with documents. We start by creating a mallet instance list
object. This function has a few extra options (whether to lowercase or
how we define a token). See ?mallet.import for details.
sotu.instances <-
mallet.import(id.array = row.names(sotu),
text.array = sotu[["text"]],
stoplist = stopwords_en_file_path,
token.regexp = "\\p{L}[\\p{L}\\p{P}]+\\p{L}")If the data is already cleaned and we want to use the index of
text.array, we can supply the text.array.
It is also possible to supply stop words as a character vector.
stop_vector <- readLines(stopwords_en_file_path)
sotu.instances.short <-
mallet.import(text.array = sotu[["text"]],
stoplist = stop_vector)We first need to create a topic trainer object to fit a model.
Load our documents. We could also pass in the filename of a saved instance list file we build from the command-line tools.
We use the method getVocabulary() to get the model’s
vocabulary. The vocabulary may be helpful in further curating the
stopword list.
## [1] "congress" "united" "states" "quarter" "century" "ago"
Similarly, we can access the word and document frequencies with
mallet.word.freqs().
## word word.freq doc.freq
## 1 congress 1025 879
## 2 united 508 426
## 3 states 557 480
## 4 quarter 16 15
## 5 century 166 155
## 6 ago 179 171
To optimize hyperparameters ( and ) every 20 iterations, after 50 burn-in iterations, we set alpha optimization as follows.
Now train a model. Note that hyperparameter optimization is on by default. We can specify the number of iterations. Here we’ll use a large-ish round number.
We can also run through a few iterations where we pick the best topic for each token rather than sampling from the posterior distribution.
To analyze our corpus using our model, we usually want to access the probability of topics per document and the probability of words per topic. By default, these functions return raw word counts. Here we want probabilities, so we normalize and add “smoothing” so that nothing has exactly 0 probability.
doc.topics <- mallet.doc.topics(topic.model, smoothed=TRUE, normalized=TRUE)
topic.words <- mallet.topic.words(topic.model, smoothed=TRUE, normalized=TRUE)What are the top words in topic 2? Notice that R indexes from 1 and Java from 0, so this will be the topic that mallet called topic 1.
## term weight
## 1 people 0.020313973
## 2 children 0.018424672
## 3 work 0.016872746
## 4 make 0.011879593
## 5 education 0.009113116
Show the largest document with at least 50% tokens belonging to topic 2. Note, since the model is not identified, you might end up with another topic if you run the same code.
docs <- which(doc.topics[,2] > 0.50)
doc_size <- nchar(sotu[["text"]])[docs]
idx <- docs[order(doc_size, decreasing = TRUE)[1]]
sotu[["text"]][idx]## [1] "Goals 2000 links world-class standards to grassroots reforms and I hope Congress will pass it without delay. Our school to work initiative will for the first time link school to the world of work, providing at least one year of apprenticeship beyond high school. After all, most of the people we're counting on to build our economic future won't graduate from college. It's time to stop ignoring them and start empowering them. We must literally transform our outdated unemployment system into a new reemployment system. The old unemployment system just sort of kept you going while you waited for your old job to come back. We've got to have a new system to move people into new and better jobs because most of those old jobs just don't come back. And we know that the only way to have real job security in the future, to get a good job with a growing income, is to have real skills and the ability to learn new ones. So we've got to streamline today's patchwork of training programs and make them a source of new skill for our people who lose their jobs. Reemployment, not unemployment, must become the centerpiece of our economic renewal. I urge you to pass it in this session of Congress. "
We can also study the topics and how the differ in different parts of the corpus, for example in different time periods.
post1975_topic_words <- mallet.subset.topic.words(topic.model, sotu[["year"]] > 1975)
mallet.top.words(topic.model, word.weights = post1975_topic_words[2,], num.top.words = 5)## term weight
## 1 people 255
## 2 work 223
## 3 children 222
## 4 make 151
## 5 it's 129
Another functionality included in the mallet R package
is to (hierarchically) cluster the topics to assess what topics that are
“closer” to each other. Use ?mallet.topic.hclust to see
further details on how to cluster topics.
topic_labels <- mallet.topic.labels(topic.model, num.top.words = 2)
topic_clusters <- mallet.topic.hclust(doc.topics, topic.words, balance = 0.5)
plot(topic_clusters, labels=topic_labels, xlab = "", )We can also store our current topic model state to use it for postprocessing. We can store the state file either as a text file or a compressed gzip file.
state_file <- file.path(tempdir(), "temp_mallet_state.gz")
save.mallet.state(topic.model = topic.model, state.file = state_file)We also store the topic counts per document and remove the old model.
doc.topics.counts <- mallet.doc.topics(topic.model, smoothed=FALSE, normalized=FALSE)
rm(topic.model)To initialize a model with the sampled topic indicators, one needs to create a new model, load the same data and then load the topic indicators. Unfortunately, setting the alpha parameter vector is currently not possible, so it is not currently possible to initialize the model with the same alpha prior.
new.topic.model <- MalletLDA(num.topics=10, alpha.sum = 1, beta = 0.1)
new.topic.model$loadDocuments(sotu.instances)
load.mallet.state(topic.model = new.topic.model, state.file = state_file)
doc.topics.counts[1:3, 1:6]## [,1] [,2] [,3] [,4] [,5] [,6]
## [1,] 0 0 0 0 0 0
## [2,] 0 0 0 3 0 0
## [3,] 0 0 0 0 0 8
## [,1] [,2] [,3] [,4] [,5] [,6]
## [1,] 0 0 0 0 0 0
## [2,] 0 0 0 3 0 0
## [3,] 0 0 0 0 0 8
This vignette gives a first example of using the mallet R package for topic modelling.
We can also save Mallet topic models and load them back into R.
model_file <- file.path(tempdir(), "temp_mallet.model")
mallet.topic.model.save(new.topic.model, model_file)
read.topic.model <- mallet.topic.model.read(model_file)
doc.topics.counts[1:3, 1:6]## [,1] [,2] [,3] [,4] [,5] [,6]
## [1,] 0 0 0 0 0 0
## [2,] 0 0 0 3 0 0
## [3,] 0 0 0 0 0 8
## [,1] [,2] [,3] [,4] [,5] [,6]
## [1,] 0 0 0 0 0 0
## [2,] 0 0 0 3 0 0
## [3,] 0 0 0 0 0 8