【发布时间】:2016-12-08 15:54:09
【问题描述】:
我正在尝试将 mallet 主题模型与 LDAvis 包一起使用。 To do so you must extract a number of parameters 来自 topic.model 对象:phi、theta、vocab、doc.length 和 term.frequency。
malletdocumentation 没有提及这些参数。如何从使用mallet.import() 和MalletLDA() 的数据生成的topic.model 对象中提取它们?
到目前为止,我已经使用 mallet 来拟合主题模型:
id_numbers <- as.integer(c(1, 2, 3))
comments <- c("words to be used for text mining", "that may or may not be interesting", "but could serve as a good example")
df <- data.frame(id_numbers, comments, stringsAsFactors = F)
# Set up topic model
library(mallet)
stoplist <- c("to", "be", "or")
write.csv(stoplist, file = "example_stoplist.csv")
mallet.instances <- mallet.import(
as.character(df$id_numbers),
as.character(df$comments),
"example_stoplist.csv",
FALSE,
token.regexp="[\\p{L}']+")
topic.model <- MalletLDA(num.topics=10)
topic.model$loadDocuments(mallet.instances)
vocabulary <- topic.model$getVocabulary()
word.freqs <- mallet.word.freqs(topic.model)
topic.model$setAlphaOptimization(40, 80) # tweaking optimization interval and burn-in iterations)
topic.model$train(400)
topic.words.m <- mallet.topic.words(topic.model, smoothed=TRUE,
normalized=TRUE)
dim(topic.words.m)
vocabulary <- topic.model$getVocabulary()
colnames(topic.words.m) <- vocabulary
doc.topics.m <- mallet.doc.topics(topic.model, smoothed=T,
normalized=T)
doc.topics.df <- as.data.frame(doc.topics.m)
doc.topics.df <- cbind(id_numbers, doc.topics.df)
doc.topic.means.df <- aggregate(doc.topics.df[, 2:ncol(doc.topics.df)],
list(doc.topics.df[,1]),
mean)
除此之外,我现在需要为LDAvis 生成JSON。我尝试了以下方法:
# LDAvis
library(LDAvis)
phi <- t(mallet.topic.words(topic.model, smoothed = TRUE, normalized = TRUE))
phi.count <- mallet.topic.words(topic.model, smoothed = TRUE, normalized = FALSE)
topic.words <- mallet.topic.words(topic.model, smoothed=TRUE, normalized=TRUE)
topic.counts <- rowSums(topic.words)
topic.proportions <- topic.counts/sum(topic.counts)
vocab <- topic.model$getVocabulary()
doc.tokens <- data.frame(id=c(1:nrow(doc.topics.m)), tokens=0)
for(i in vocab){
# Find word if word in text
matched <- grepl(i, df$comments)
doc.tokens[matched,2] =doc.tokens[matched,2] + 1
}
createJSON(phi = phi,
theta = doc.topics.m,
doc.length = doc.tokens,
vocab = vocab,
term.frequency = apply(phi.count, 1, sum))
但是,这给了我以下错误消息:
Error in createJSON(phi = phi, theta = doc.topics.m, doc.length = doc.tokens, :
Number of rows of phi does not match
number of columns of theta; both should be equal to the number of topics
in the model.
所以我似乎以错误的方式生成 phi 和 theta 矩阵。
【问题讨论】:
-
请尝试向reproducible example 提供样本输入数据,以便我们了解您正在尝试做什么并测试可能的解决方案。
-
您的槌子对象上的
str会产生什么? -
@emilliman5:
str(topic.model)给Formal class 'jobjRef' [package "rJava"] with 2 slots ..@ jobj :<externalptr> ..@ jclass: chr "cc/mallet/topics/RTopicModel" -
我认为你不需要转换
mallet.topic.words来生成phi。查看phi的尺寸。theta和doc.length让他们摆平。 -
如果您不介意使用
lda包,您可以使用与 LDAvis 包兼容的格式的数据。
标签: r text-mining lda mallet