【发布时间】:2018-10-26 15:45:40
【问题描述】:
我正在 R 中尝试我的第一个 LDA 模型,但遇到了错误
Error in LDA(Corpus_clean_dtm, k, method = "Gibbs", control = list(nstart = nstart, : Each row of the input matrix needs to contain at least one non-zero entry
这是我的模型代码,包括一些标准的预处理步骤
library(tm)
library(topicmodels)
library(textstem)
df_withduplicateID <- data.frame(
doc_id = c("2095/1", "2836/1", "2836/1", "2836/1", "9750/2",
"13559/1", "19094/1", "19053/1", "20215/1", "20215/1"),
text = c("He do subjects prepared bachelor juvenile ye oh.",
"He feelings removing informed he as ignorant we prepared.",
"He feelings removing informed he as ignorant we prepared.",
"He feelings removing informed he as ignorant we prepared.",
"Fond his say old meet cold find come whom. ",
"Wonder matter now can estate esteem assure fat roused.",
".Am performed on existence as discourse is.",
"Moment led family sooner cannot her window pulled any.",
"Why resolution one motionless you him thoroughly.",
"Why resolution one motionless you him thoroughly.")
)
clean_corpus <- function(corpus){
corpus <- tm_map(corpus, stripWhitespace)
corpus <- tm_map(corpus, removePunctuation)
corpus <- tm_map(corpus, tolower)
corpus <- tm_map(corpus, lemmatize_strings)
return(corpus)
}
df <- subset(df_withduplicateID, !duplicated(subset(df_withduplicateID, select = ID)))
Corpus <- Corpus(DataframeSource(df))
Corpus_clean <- clean_corpus(Corpus)
Corpus_clean_dtm <- DocumentTermMatrix(Corpus_clean)
burnin <- 4000
iter <- 2000
thin <- 500
seed <-list(203,500,623,1001,765)
nstart <- 5
best <- TRUE
k <- 5
LDAresult_1683 <- LDA(Corpus_clean_dtm, k, method = "Gibbs",
control = list(nstart = nstart, seed = seed, best = best,
burnin = burnin, iter = iter, thin = thin))
经过一番搜索,我的 DocumentTermMatrix 似乎可能包含空文档(之前在 here 和 here 中提到过,导致出现此错误消息。
然后我继续删除空文档,重新运行 LDA 模型,一切顺利。没有抛出任何错误。
rowTotals <- apply(Corpus_clean_dtm , 1, sum)
Corpus_clean_dtm.new <- Corpus_clean_dtm[rowTotals >0, ]
Corpus_clean_dtm.empty <- Corpus_clean_dtm[rowTotals <= 0, ]
Corpus_clean_dtm.empty$dimnames$Docs
我继续从 Corpus_clean_dtm.empty 中手动查找行号 ID(取出所有空文档条目)并匹配“Corpus_clean”中的相同 ID(& 行号),并意识到这些文档并不是真正的“空” ' 并且每个“空”文档至少包含 20 个字符。
我错过了什么吗?
【问题讨论】:
-
如果您包含一个简单的reproducible example,其中包含可用于测试和验证可能解决方案的示例输入和所需输出,则更容易为您提供帮助。
-
干杯,我添加了一个带有重复 ID 和随机文本的数据框 - 在单词/字符长度方面与我的原始数据框非常相似。我希望在将数据帧转换为 LDA 的 DocumentTermMatrix 时,我放在这里的代码将保留所有唯一条目并且没有非零条目错误。如果您还需要什么,请告诉我!谢谢。
-
你在哪里定义
k和control=参数中传递的所有变量?如果未定义所有变量,此示例仍然无法重现。 -
在此编辑中添加了所有训练参数 :)
-
如果我在将
select = ID更改为select = doc_id后运行您的示例,我没有任何错误。但是您应该知道,将语料库转换为文档术语矩阵默认情况下会删除短于 3 的单词。因此,诸如“he”、“be”、“so”之类的单词将被删除。如果您不希望在创建文档术语矩阵时需要调整wordLengths参数,例如DocumentTermMatrix(Corpus_clean), control = list(wordLengths = c(1, Inf))
标签: r text tm lda topic-modeling