Created
December 19, 2015 02:42
-
-
Save trinker/477d7ae65ff6ca73cace to your computer and use it in GitHub Desktop.
Convert topicmodels to LDAvis
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#' Transform Model Output for Use with the LDAvis Package | |
#' | |
#' Convert a \pkg{topicmodels} output into the JSON form required by the \pkg{LDAvis} package. | |
#' | |
#' @param model A \code{\link[]{topicmodel}} object. | |
#' @param \ldots Currently ignored. | |
#' @seealso \code{\link[LDAvis]{createJSON}} | |
#' @export | |
#' @examples | |
#' \dontrun{ | |
#' data("AssociatedPress", package = "topicmodels") | |
#' model <- LDA(AssociatedPress[1:20,], control = list(alpha = 0.1), k = 3) | |
#' LDAvis::serVis(topicmodels2LDAvis(model)) | |
#' } | |
topicmodels2LDAvis <- function(x, ...){ | |
post <- topicmodels::posterior(x) | |
if (ncol(post[["topics"]]) < 3) stop("The model must contain > 2 topics") | |
mat <- x@wordassignments | |
LDAvis::createJSON( | |
phi = post[["terms"]], | |
theta = post[["topics"]], | |
vocab = colnames(post[["terms"]]), | |
doc.length = slam::row_sums(mat, na.rm = TRUE), | |
term.frequency = slam::col_sums(mat, na.rm = TRUE) | |
) | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment