0

我正在尝试使用与此线程相关的 data.table 包创建一个具有稀疏矩阵和名为 quanteda 的包的矩阵乘法。所以

require(quanteda) 

mytext <- c("Let the big dogs hunt", "No holds barred", "My child is an honor student")     
myMatrix <-dfm(mytext, ignoredFeatures = stopwords("english"), stem = TRUE) #a data.table
as.matrix(myMatrix) %*% transpose(as.matrix(myMatrix))

如何使用 quanteda 包和稀疏矩阵使矩阵乘法在这里工作?

4

2 回答 2

1

对矩阵乘法使用t命令,而不是transpose命令,使得

as.matrix(myMatrix) %*% t(as.matrix(myMatrix))

也如评论所述, as.matrix 是非稀疏的,而 Matrix::matrix 是稀疏的,但在这里是不必要的,所以更好

myMatrix %*% t(myMatrix)

甚至可能更好

crossprod(myMatrix) 
tcrossprod(myMatrix) 

但它需要数字/复数矩阵/向量参数,不适用于问题中的示例:

require(quanteda)  
mytext <- c("Let the big dogs hunt", "No holds barred", "My child is an honor student")      
myMatrix <-dfm(mytext, ignoredFeatures = stopwords("english"), stem = TRUE) 
crossprod(myMatrix) 
tcrossprod(myMatrix)
于 2017-01-09T15:41:12.880 回答
1

这工作得很好:

mytext <- c("Let the big dogs hunt", 
            "No holds barred", 
            "My child is an honor student")     
myMatrix <- dfm(mytext)

myMatrix %*% t(myMatrix)
## 3 x 3 sparse Matrix of class "dgCMatrix"
##       text1 text2 text3
## text1     5     .     .
## text2     .     3     .
## text3     .     .     6

无需使用 强制转换为密集矩阵as.matrix()。请注意,它不再是“dfmSparse”对象,因为它不再是按特征排列的文档矩阵。

于 2017-01-09T19:00:51.423 回答