2017-05-04 105 views
0

我有一個大稀疏矩陣,稱其爲,P:稀疏(dgCMatrix)矩陣的行歸一化中的R

> str(P) 
    Formal class 'dgCMatrix' [package "Matrix"] with 6 slots 
    [email protected] i  : int [1:7868093] 4221 6098 8780 10313 11102 14243 20570 22145 24468 24977 ... 
    [email protected] p  : int [1:7357] 0 0 269 388 692 2434 3662 4179 4205 4256 ... 
    [email protected] Dim  : int [1:2] 1303967 7356 
    [email protected] Dimnames:List of 2 
    .. ..$ : NULL 
    .. ..$ : NULL 
    [email protected] x  : num [1:7868093] 1 1 1 1 1 1 1 1 1 1 ... 
    [email protected] factors : list() 

我想行歸一化(比方說,用L-2範數)。 ..(利用矢量回收的)的直接方法會是這樣的:

> row_normalized_P <- P/rowSums(P^2) 

但是,這會導致內存分配錯誤,因爲它出現在rowSums結果被回收到密集矩陣尺寸等於dim(P)。 鑑於P已知是稀疏的(或至少以稀疏格式存儲),是否有人知道非迭代方法來實現上面所示的期望row_normalized_P? (即所產生的矩陣將同樣作爲稀疏本身P ...我想避免永遠不必在正常化的步驟分配的密集矩陣。)

唯一的半有效的方法,我發現身邊這是applyP跨越行(更準確地說,通過強行進入密集子矩陣的行),但我想嘗試從我的代碼庫中刪除循環邏輯,如果可以的話,我想知道是否有一個內置於Matrix軟件包(我只是不知道),這有助於這種特殊類型的計算。

乾杯和感謝您的任何幫助!

-murat

回答

2

我想出了一個很好的解決方案(像往常一樣,發佈後約15分鐘: - /)...

> row_normalized_P <- Matrix::Diagonal(x = 1/sqrt(Matrix::rowSums(P^2))) %*% P 
+0

而對於山坳正常化,記得換乘法順序: 'P%*%矩陣::對角線(x = 1/sqrt(Matrix :: colSums(P^2)))' – mdup