生成随机稀疏矩阵

Generating random sparse matrix

我正在处理大型矩阵 - 按 10^8 列和 10^3-10^4 行的顺序。由于这些矩阵只有 1 和 0(超过 99% 为 0),我认为 Matrix 包中的稀疏构造是合适的。但是,我没有看到像下面示例中那样生成随机矩阵的方法。请注意,非零条目由 概率 col_prob.

定义
set.seed(1) #For reproducibility
ncols <- 20
nrows <- 10
col_prob <- runif(ncols,0.1,0.2)
rmat <- matrix(rbinom(nrows*ncols,1,col_prob),
       ncol=ncols,byrow=T)

当然我可以将rmat转换成稀疏矩阵:

rmat_sparse <- Matrix(rmat, sparse=TRUE)

但是,我想一步生成稀疏矩阵。我不确定函数 Matrix::rsparsematrix 是否可以完成此操作。

以下函数将通过操作空白 dgCMatrix 对象的值生成您要查找的类型的稀疏矩阵。它基本上一次创建 rbinom 行并相应地填充 @i@p 值。

library(Matrix)    
randsparse <- function(nrows, ncols, col_prob) {
  mat <- Matrix(0, nrows, ncols, sparse = TRUE)  #blank matrix for template
  i <- vector(mode = "list", length = ncols)     #each element of i contains the '1' rows
  p <- rep(0, ncols)                             #p will be cumsum no of 1s by column
  for(r in 1:nrows){
    row <- rbinom(ncols, 1, col_prob)            #random row
    p <- p + row                                 #add to column identifier
    if(any(row == 1)){
      for (j in which(row == 1)){
        i[[j]] <- c(i[[j]], r-1)                 #append row identifier
      }
    }
  }
  p <- c(0, cumsum(p))                           #this is the format required
  i <- unlist(i)
  x <- rep(1, length(i))
  mat@i <- as.integer(i)
  mat@p <- as.integer(p)
  mat@x <- x
  return(mat)
}

set.seed(1)
randsparse(10, 20, runif(20, 0.1, 0.2))

10 x 20 sparse Matrix of class "dgCMatrix"

 [1,] 1 . . . . . . . 1 . . . . . 1 . . . . .
 [2,] . . . . . . . . . . . . . . . . . . . .
 [3,] 1 . . . . . . . . . . . . . . 1 1 . . 1
 [4,] . . . . . . . . . . . . . 1 . . . . . .
 [5,] . . . 1 . . . . 1 . 1 . . . . . . . . .
 [6,] 1 . . . . . . . . . . . . . 1 . . . 1 .
 [7,] . . . . . . . . . . . . . . . . . . . .
 [8,] . 1 . . 1 . . . . . . . 1 . . 1 . . . 1
 [9,] . . 1 . . . . . 1 . . . . 1 . . . 1 . .
[10,] . . . . . . . . . . 1 . . 1 . . . 1 1 .