如何将稀疏矩阵一分为二

问题描述 投票:0回答:1

我有一个大的稀疏矩阵,我需要关联它,这对我来说是不可能的,因为:

  1. 由于R的内存限制,我无法将稀疏矩阵转换为密集矩阵
  2. 我尝试使用软件包bigstatsbigmemory,我的R冻结了(使用Windows 10、8GB笔记本电脑)
  3. R的Matrix程序包中没有相关函数
  4. NB:我试图以'M'X + X'M - M'M'格式关联稀疏矩阵,这就是为什么我试图将稀疏矩阵分为两个或三个,然后使用as.matrix()转换为密集矩阵,然后使用cor()然后使用cbind()将相关结果合并为一个

    现在:

[我想问是否有可能将稀疏矩阵分为两部分或三部分,转换为稠密矩阵,然后将每个稠密矩阵关联,然后将两个或三个稠密矩阵绑定为一个,然后导出到文本文件。

考虑到稀疏矩阵的ip部分大小相等且具有相同dim,我可以使用什么函数将稀疏矩阵分为两个或三个?

Formal class 'dgCMatrix' [package "Matrix"] with 7 slots
  ..@ i       : int [1:73075722]  ...
  ..@ p       : int [1:73075722] 0 0 1 1 1 1 1 2 2 2 ...
  ..@ Dim     : int [1:2] 500232 500232
  ..@ Dimnames:List of 2
  .. ..$ : NULL
  .. ..$ : NULL
  ..@ x       : num [1:73075722]  ...
  ..@ uplo    : chr "L"
  ..@ factors : list()

相关输出将采用以下格式:

         [,1]       [,2]       [,3]        [,4]
[1,]  1.00000000 -0.8343860  0.3612926  0.09678096
[2,] -0.83438600  1.0000000 -0.8154071  0.24611830
[3,]  0.36129256 -0.8154071  1.0000000 -0.51801346
[4,]  0.09678096  0.2461183 -0.5180135  1.00000000
[5,]  0.67411584 -0.3560782 -0.1056124  0.60987601
[6,]  0.23071712 -0.4457467  0.5117711  0.21848068
[7,]  0.49200080 -0.4246502  0.2016633  0.46971736
           [,5]       [,6]       [,7]
[1,]  0.6741158  0.2307171  0.4920008
[2,] -0.3560782 -0.4457467 -0.4246502
[3,] -0.1056124  0.5117711  0.2016633
[4,]  0.6098760  0.2184807  0.4697174
[5,]  1.0000000  0.2007979  0.7198228
[6,]  0.2007979  1.0000000  0.6965899
[7,]  0.7198228  0.6965899  1.0000000

我需要关联一个大的稀疏矩阵,这对我来说是不可能的,因为:由于我尝试使用...的内存限制,我无法将稀疏矩阵转换为密集矩阵。

r matrix sparse-matrix correlation
1个回答
0
投票

cor()函数是一种有效计算所有列之间的pearson相关性的方法。 cor非常有效,但是如果我们不介意效率下降,我们可以手动计算pearson相关性:

n_row <- nrow(res)
cor_mat <- Matrix(0L,n_row, ncol(res))
cMeans <- Matrix::colMeans(res)

for (i in seq_len(nrow(res)-1)){
  x_delta = res[, i] - cMeans[i]
  sum_x_delta_sq = sum(x_delta^2)

  for (j in (i+1):nrow(res)){
    y_delta = res[, j] - cMeans[j]

    tmp <- sum(x_delta * y_delta) / sqrt((sum_x_delta_sq * sum(y_delta^2)))
    if (abs(tmp) > 0.05) cor_mat[i, j] <- tmp
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.