clustext

clustext is a collection of optimized tools for clustering text data
via various text appropriate clustering algorithms. There are many great
R clustering tools
to locate topics within documents. I have had success with hierarchical
clustering for topic extraction. This initial success birthed the
hclustext package.
Additional techniques such as kmeans and non-negative matrix
factorization also proved useful. These algorithms began to be collected
in a consistent manor of use in the clustext package. This package
wraps many of the great R tools for clustering and working with sparse
matrices to aide in the workflow associated with topic extraction.
The general idea is that we turn the documents into a matrix of words.
After this we weight the terms by importance using
tf-idf.
This helps the more salient words to rise to the top. Some clustering
algorithms require a similarity matrix while others require just the
tf-idf weighted DocumentTermMatrices. Likewise, some algorithms require
k terms to be specified before the model fit while others allow k
topics to be determined after the model has been fit.
With algorithms that require a similarity matrix (e.g., hierarchical
clustering) we apply cosine distance measures to compare the terms (or
features) of each document. I have found cosine distance to work well
with sparse matrices to produce distances metrics between the documents.
The clustering model is fit to separate the documents into clusters. In
the case of some clustering techniques (e.g., hierarchical clustering)
the user then may apply k clusters to the fit, clustering documents with
similar important text features. Other techniques require that k be
specified prior to fitting the model. The documents can then be grouped
by clusters and their accompanying salient words extracted as well.
Table of Contents
Functions
The main functions, task category, & descriptions are summarized in the
table below:
| Function |
Category |
Description |
data_store |
data structure |
clustext's data structure (list of dtm + text) |
hierarchical_cluster |
cluster fit |
Fits a hierarchical cluster model |
kmeans_cluster |
cluster fit |
Fits a kmeans cluster model |
skmeans_cluster |
cluster fit |
Fits an skmeans cluster model |
nfm_cluster |
cluster fit |
Fits a non-negative matrix factorization cluster model |
assign_cluster |
assignment |
Assigns cluster to document/text element |
get_text |
extraction |
Get text from various clustext objects |
get_dtm |
extraction |
Get tm::DocumentTermMatrix from various clustext objects |
get_removed |
extraction |
Get removed text elements from various clustext objects |
get_documents |
extraction |
Get clustered documents from an assign_cluster object |
get_terms |
extraction |
Get clustered weighted important terms from an assign_cluster object |
as_topic |
categorization |
View get_terms object as topics (pretty printed important words) |
write_cluster_text |
categorization |
Write get_text(assign_cluster(myfit)) to file for human coding |
read_cluster_text |
categorization |
Read in a human coded write_cluster_text file |
categorize |
categorization |
Assign human categories and matching clusters to original data |
Installation
To download the development version of clustext:
Download the zip
ball or tar
ball, decompress
and run R CMD INSTALL on it, or use the pacman package to install
the development version:
if (!require("pacman")) install.packages("pacman")
pacman::p_load_gh(
"trinker/textshape",
"trinker/gofastr",
"trinker/termco",
"trinker/clustext"
)
Contact
You are welcome to:
Demonstration
Load Packages and Data
if (!require("pacman")) install.packages("pacman")
pacman::p_load(clustext, dplyr, textshape, ggplot2, tidyr)
data(presidential_debates_2012)
Data Structure
The data structure for clustext is very specific. The data_storage
produces a DocumentTermMatrix which maps to the original text. The
empty/removed documents are tracked within this data structure, making
subsequent calls to cluster the original documents and produce weighted
important terms more robust. Making the data_storage object is the
first step to analysis.
We can give the DocumentTermMatrix rownames via the doc.names
argument. If these names are not unique they will be combined into a
single document as seen below. Also, if you want to do stemming, minimum
character length, stopword removal or such this is when/where it's done.
ds <- with(
presidential_debates_2012,
data_store(dialogue, doc.names = paste(person, time, sep = "_"))
)
ds
## <<Data Store (documents: 10, terms: 3,180)>>
## Text Elements : 10
## Elements Removed : 0
## Non-/sparse entries: 6916/24884
## Sparsity : 78%
## Maximal term length: 16
## Minimum term length: 3
Fit the Model: Hierarchical Cluster
Next we can fit a hierarchical cluster model to the data_store object
via hierarchical_cluster.
myfit <- hierarchical_cluster(ds)
myfit
##
## Call:
## fastcluster::hclust(d = distmes(x[["dtm"]]), method = method)
##
## Cluster method : ward.D
## Number of objects: 10
This object can be plotted with various k or h parameters specified
to experiment with cutting the dendrogram. This cut will determine the
number of clusters or topics that will be generated in the next step.
The visual inspection allows for determining how to cluster the data as
well as determining if a tf-idf, cosine, hierarchical cluster model is a
right fit for the data and task. By default plot uses an approximation
of k based on Can & Ozkarahan's (1990) formula (m * n)/t where
m and n are the dimensions of the matrix and t is the length of
the non-zero elements in matrix A.
- Can, F., Ozkarahan, E. A. (1990). Concepts and effectiveness of the
cover-coefficient-based clustering methodology for text databases.
ACM Transactions on Database Systems 15 (4): 483.
doi:10.1145/99935.99938
Interestingly, in the plots below where k = 6 clusters, the model
groups each of the candidates together at each of the debate times.
plot(myfit)
##
## k approximated to: 5



Assigning Clusters
The assign_cluster function allows the user to dictate the number of
clusters. Because the model has already been fit the cluster assignment
is merely selecting the branches from the dendrogram, and is thus very
quick. Unlike many clustering techniques the number of clusters is done
after the model is fit, this allows for speedy cluster assignment,
meaning the user can experiment with the number of clusters.
ca <- assign_cluster(myfit, k = 6)
ca
## CROWLEY_time 2 LEHRER_time 1 OBAMA_time 1 OBAMA_time 2
## 1 2 3 4
## OBAMA_time 3 QUESTION_time 2 ROMNEY_time 1 ROMNEY_time 2
## 5 6 3 4
## ROMNEY_time 3 SCHIEFFER_time 3
## 5 2
Cluster Loading
To check the number of documents loading on a cluster there is a
summary method for assign_cluster which provides a descending data
frame of clusters and counts. Additionally, a horizontal bar plot shows
the document loadings on each cluster.

## cluster count
## 1 2 2
## 2 3 2
## 3 4 2
## 4 5 2
## 5 1 1
## 6 6 1
Cluster Text
The user can grab the texts from the original documents grouped by
cluster using the get_text function. Here I demo a 40 character
substring of the document texts.
get_text(ca) %>%
lapply(substring, 1, 40)
## $`1`
## [1] "Good evening from Hofstra University in "
##
## $`2`
## [1] "We'll talk about specifically about heal"
## [2] "Good evening from the campus of Lynn Uni"
##
## $`3`
## [1] "Jim, if I if I can just respond very qui"
## [2] "What I support is no change for current "
##
## $`4`
## [1] "Jeremy, first of all, your future is bri"
## [2] "Thank you, Jeremy. I appreciate your you"
##
## $`5`
## [1] "Well, my first job as commander in chief"
## [2] "Thank you, Bob. And thank you for agreei"
##
## $`6`
## [1] "Mister President, Governor Romney, as a "
Cluster Frequent Terms
As with many topic clustering techniques, it is useful to get the to
salient terms from the model. The get_terms function uses the
min-max
scaled, tf-idf weighted,
DocumentTermMatrix to extract the most frequent salient terms. These
terms can give a sense of the topic being discussed. Notice the absence
of clusters 1 & 6. This is a result of only a single document included
in each of the clusters. The term.cutoff hyperparmeter sets the lower
bound on the min-max scaled tf-idf to accept. If you don't get any terms
you may want to lower this or reduce min.n. Likewise, these two
parameters can be raised to eliminate noise.