R:稀疏矩阵乘法 data.table 和 quanteda 包?
R: sparse matrix multiplication with data.table and quanteda package?
我正在尝试使用与此线程 here 相关的 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 包和稀疏矩阵进行矩阵乘法运算?
使用 t
命令,而不是 transpose
命令,用于矩阵乘法使得
as.matrix(myMatrix) %*% t(as.matrix(myMatrix))
也如评论所述,as.matrix 是非稀疏的,而 Matrix::matrix 是稀疏的但这里不需要,所以更好
myMatrix %*% t(myMatrix)
甚至可能更好
crossprod(myMatrix)
tcrossprod(myMatrix)
但它需要 numeric/complex matrix/vector 个参数,不适用于问题中的示例:
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)
这很好用:
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" 对象,因为它不再是按特征排列的文档矩阵。
我正在尝试使用与此线程 here 相关的 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 包和稀疏矩阵进行矩阵乘法运算?
使用 t
命令,而不是 transpose
命令,用于矩阵乘法使得
as.matrix(myMatrix) %*% t(as.matrix(myMatrix))
也如评论所述,as.matrix 是非稀疏的,而 Matrix::matrix 是稀疏的但这里不需要,所以更好
myMatrix %*% t(myMatrix)
甚至可能更好
crossprod(myMatrix)
tcrossprod(myMatrix)
但它需要 numeric/complex matrix/vector 个参数,不适用于问题中的示例:
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)
这很好用:
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" 对象,因为它不再是按特征排列的文档矩阵。