我在R中有一个稀疏矩阵
我现在希望在 R 上执行非负矩阵分解
data.txt 是我使用 Python 创建的文本文件,它由 3 列组成,其中第一列指定行号,第二列指定列号,第三列指定值
数据.txt
1 5 10
3 2 5
4 6 9
原始数据.txt包含 164009 行,这是 250000x250000 稀疏矩阵的数据
我使用了 NMF 库,我正在做
x=scan('data.txt',what=list(integer(),integer(),numeric()))
library('Matrix')
R=sparseMatrix(i=x[[1]],j=x[[2]],x=x[[3]])
res<-nmf(R,3)
它给了我一个错误:
函数(类、fdef、mtable)中的错误:找不到继承的函数 nmf 的方法,用于签名"dgCMAtrix"、"缺失","失踪"
谁能帮我弄清楚我做错了什么?
第一个问题是你向nmf提供了一个dgCMatrix。
> class(R)
[1] "dgCMatrix"
attr(,"package")
[1] "Matrix"
帮助在这里:
help(nmf)
请参阅方法部分。 它想要一个真正的矩阵。 由于条目数量众多,使用 as.matrix 进行强制操作可能对您没有多大帮助。
现在,即使使用您的示例数据,对矩阵的强制也是不够的:
> nmf(as.matrix(R))
Error: NMF::nmf : when argument 'rank' is not provided, argument 'seed' is required to inherit from class 'NMF'. See ?nmf.
让我们给它一个排名:
> nmf(as.matrix(R),2)
Error in .local(x, rank, method, ...) :
Input matrix x contains at least one null row.
事实上,它确实如此:
> R
4 x 6 sparse Matrix of class "dgCMatrix"
[1,] . . . . 10 .
[2,] . . . . . .
[3,] . . 5 . . .
[4,] . . . . . 9
将近 10 年后,有解决方案。这是一个快速的。
如果你有一个 250k 平方的 dgCMatrix 的dgCMatrix
,它的稀疏度接近 1%,你需要一个稀疏分解算法。
我为大型稀疏矩阵编写了RcppML::NMF
:
library(RcppML)
A <- rsparsematrix(1000, 10000, 0.01)
model <- RcppML::nmf(A, k = 10)
str(model)
这在笔记本电脑上应该需要几秒钟。
您也可以查看rsparse::WRMF
,尽管它没有那么快。
现在有一个优秀的 NMF 包可用:https://cran.r-project.org/web/packages/NMF/NMF.pdf
提供各种热图,纯度/熵,选择不同的NMF算法(Brunet,Lee,sNMF,nsNMF,欧几里得/K-L散度等)以及创建自己的框架。
尝试:
library(NMF)
x = read.table('data.txt')
# estimate rank
estim.x = nmf(x, 2:5, nrun=50, method = 'nsNMF', seed = 'random', .options = "v")
# plot clustering accuracy
plot(estim.x, what = c("cophenetic", "dispersion"))
# inspect consensus matrices
consensusmap(estim.x)