【发布时间】:2019-07-02 21:19:36
【问题描述】:
我正在使用 R 中的 textmineR 运行潜在语义分析 (LSA)。我希望得到的是按主题矩阵的文档以及按文档的主题得分,我可以通过从我的 lsa 对象调用 theta 来做到这一点(下) .但是,我在获取创建的 lsa 对象并使用它对新数据集(即文档术语矩阵,dtm)进行评分时遇到了挑战,以便我可以将预先存在的主题结构应用于新数据。在下面的示例中,我创建了两个主题,然后当我尝试使用完全相同的 dtm(为了本示例而假装它是一个新文件)时,我收到以下错误:
"Error in predict.lsa_topic_model(model, dtm_m) : newdata must be a matrix of class dgCMatrix or a numeric vector"
我需要使用 lsa 对象来为新文本评分。我缺少一个简单的解决方法吗?我没有运气将矩阵强制为“dgCMatrix”。我实际上也不知道如何使用 lsa 等其他软件包来做到这一点。对此方法的任何帮助将不胜感激。
file = as.data.frame(matrix( c('case1', 'this is some SAMPLE TEXT!',
'case2', 'and this is the 2nd version of that text...',
'case3', 'more stuff to talk about'),
nrow=3,
ncol=2,
byrow = TRUE))
names(file) [1] <- 'doc_id'
names(file) [2] <- 'text'
library(tm)
wordCorpus <- Corpus(DataframeSource(file))
cleaner <- function (wordCorpus) {
wordCorpus <- tm_map(wordCorpus, removeNumbers)
wordCorpus <- tm_map(wordCorpus, content_transformer(tolower))
wordCorpus <- tm_map(wordCorpus, removePunctuation)
return (wordCorpus)
}
wordCorpus <- cleaner (wordCorpus)
tokenizer <- function(x)
NGramTokenizer(x, Weka_control(min = 1, max = 2))
dtm <- DocumentTermMatrix (wordCorpus, control = list (tokenize=tokenizer, weighting = weightTfIdf))
dtm_m <- as.matrix(dtm)
library(textmineR)
model <- FitLsaModel(dtm = dtm_m, k = 2)
#this is what I want to get, but ideally also
#be able to save the "model" object and use to create this in a new sample`
values <- as.data.frame (model$theta)
values
#pretending my original dataset is a new sample and using predict
values_other <- predict (model, dtm_m)
【问题讨论】:
-
您可以使用 Matrix 包创建 dgCMatrix。使用
Matrix::sparseMatrix()或Matrix::Matrix(x, sparse= TRUE)。第一个函数是推荐的方式。 -
太好了,回答了它。出于好奇,为什么首选第一个功能?我运行了第二个,但第一个需要概述来自原始矩阵的各种输入。
-
第一个选项给你更多的控制权,但在内存消耗方面也更有效率。对于小矩阵没关系,但对于稍微大一点的矩阵,你可能会遇到问题。