use*_*472 5 r normalization matrix sparse-matrix
我在R中有一个非常大的(~500,000 x~500,000)稀疏矩阵,我试图用每个列除以它的总和:
sm = t(t(sm) / colSums(sm))
Run Code Online (Sandbox Code Playgroud)
但是,当我这样做时,我收到以下错误:
# Error in evaluating the argument 'x' in selecting a method for function 't':
# Error: cannot allocate vector of size 721.1 Gb
Run Code Online (Sandbox Code Playgroud)
在R中有更好的方法吗?我能够存储colSums精细,以及计算和存储稀疏矩阵的转置,但问题似乎在尝试执行时到达"/".看起来稀疏矩阵在这里被转换为全密集矩阵.
任何帮助将不胜感激.谢谢!
这是我们可以做的,假设A是dgCMatrix:
A@x <- A@x / rep.int(colSums(A), diff(A@p))
Run Code Online (Sandbox Code Playgroud)
这需要对dgCMatrix课程有所了解.
@x 在打包的1D数组中存储非零矩阵值;@p按列存储非零元素的累积数量,因此diff(A@p)给出每列的非零元素数.我们重复colSums(A)该列中非零元素的每个元素,然后除以A@x该向量.为此,我们A@x通过重新调整的值进行更新.以这种方式,列重新缩放以稀疏方式完成.
例:
library(Matrix)
set.seed(2); A <- Matrix(rbinom(100,10,0.05), nrow = 10)
#10 x 10 sparse Matrix of class "dgCMatrix"
# [1,] . . 1 . 2 . 1 . . 2
# [2,] 1 . . . . . 1 . 1 .
# [3,] . 1 1 1 . 1 1 . . .
# [4,] . . . 1 . 2 . . . .
# [5,] 2 . . . 2 . 1 . . .
# [6,] 2 1 . 1 1 1 . 1 1 .
# [7,] . 2 . 1 2 1 . . 2 .
# [8,] 1 . . . . 3 . 1 . .
# [9,] . . 2 1 . 1 . . 1 .
#[10,] . . . . 1 1 . . . .
diff(A@p) ## number of non-zeros per column
# [1] 4 3 3 5 5 7 4 2 4 1
colSums(A) ## column sums
# [1] 6 4 4 5 8 10 4 2 5 2
A@x <- A@x / rep.int(colSums(A), diff(A@p)) ## sparse column rescaling
#10 x 10 sparse Matrix of class "dgCMatrix"
# [1,] . . 0.25 . 0.250 . 0.25 . . 1
# [2,] 0.1666667 . . . . . 0.25 . 0.2 .
# [3,] . 0.25 0.25 0.2 . 0.1 0.25 . . .
# [4,] . . . 0.2 . 0.2 . . . .
# [5,] 0.3333333 . . . 0.250 . 0.25 . . .
# [6,] 0.3333333 0.25 . 0.2 0.125 0.1 . 0.5 0.2 .
# [7,] . 0.50 . 0.2 0.250 0.1 . . 0.4 .
# [8,] 0.1666667 . . . . 0.3 . 0.5 . .
# [9,] . . 0.50 0.2 . 0.1 . . 0.2 .
#[10,] . . . . 0.125 0.1 . . . .
Run Code Online (Sandbox Code Playgroud)
@thelatemail提到了另一种方法,首先转换dgCMatrix为dgTMatrix:
AA <- as(A, "dgTMatrix")
A@x <- A@x / colSumns(A)[AA@j + 1L]
Run Code Online (Sandbox Code Playgroud)
对于dgTMatrix类没有,@p但是@j给出了没有零矩阵元素的列索引(基于0).