【问题标题】:How to convert a regular matrix to a sparse matrix in R?如何将常规矩阵转换为 R 中的稀疏矩阵?
【发布时间】:2018-01-18 16:50:55
【问题描述】:

我有一个 200K 行 x 27K 列矩阵,我想将其转换为稀疏矩阵。我试过这样做,但出现分段错误:

> dim(my_regular)
[1] 196501  26791

> my_sparse <- as(my_regular, "sparseMatrix")

 *** caught segfault ***
address 0x2b9e3e10e000, cause 'memory not mapped'

有没有更好的办法?

【问题讨论】:

  • 使用Matrix(my_regular,sparse=TRUE) 包中的Matrix
  • @AndrewGustar 我得到同样的错误

标签: r matrix sparse-matrix


【解决方案1】:

这绝对不理想,但我可以进行转换的唯一方法是将矩阵分解为 50K 行的组,然后使用 rbind 将它们组合起来:

my_sparse_1 <- Matrix::Matrix(my_regular[1:50000,], sparse = TRUE)
my_sparse_2 <- Matrix::Matrix(my_regular[50001:100000,], sparse = TRUE)
# etc.
my_sparse <- rbind(my_sparse_1, my_sparse_2, etc.)

我不会接受我的回答,以防有人有更好的建议

【讨论】:

    【解决方案2】:

    首先,如果as(my_regular, "sparseMatrix") 给出了段错误 - 请向Matrix 包维护者报告(可以在这里找到https://cran.r-project.org/web/packages/Matrix/index.html)。

    作为一种解决方法,您可以使用以下方法:

    library(Matrix)
    nc = 50
    nr = 100
    sparsity = 0.9
    m = sample(c(0, 1), size = nr * nc, replace = TRUE, prob = c(sparsity, 1 - sparsity))
    m = matrix(m, nr, nc)
    
    # normal way of coercing dense to sparse
    spm1 = as(m, "CsparseMatrix")
    
    # get indices of non-zero elements
    ind_nnz = which(m != 0)
    
    # construct zero-based indices of row and column
    i = (ind_nnz - 1L) %% nr
    j = as.integer((ind_nnz - 1L) / nr)
    # get non-zero values
    x = m[ind_nnz]
    
    spm2 = sparseMatrix(i = i, j = j, x = x, dims = c(nr, nc), index1 = FALSE)
    
    identical(spm1, spm2)
    # TRUE
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-04-10
      • 2021-11-25
      • 2017-07-02
      • 2013-06-26
      • 2014-12-21
      • 1970-01-01
      • 2020-12-07
      • 2015-07-24
      相关资源
      最近更新 更多