【问题标题】:R memory-efficient squaring of a sparse matrix稀疏矩阵的 R 内存高效平方
【发布时间】:2021-10-25 06:35:34
【问题描述】:

假设我有一个大的稀疏矩阵并且想要对其进行平方。

但是,m %*% m 会占用大量内存,例如20-40 Gb。

有没有更高效的方法来做到这一点?例如。包之类的?

【问题讨论】:

    标签: r sparse-matrix matrix-multiplication


    【解决方案1】:

    也许Matrix 中的sparseMatrix 会提高内存效率。

    library(Matrix)
    m <- sparseMatrix(1:5, 1:5, x=1:5)
    m %*% m
    #m^2 #Alternative
    #5 x 5 sparse Matrix of class "dgCMatrix"
    #                
    #[1,] 1 . .  .  .
    #[2,] . 4 .  .  .
    #[3,] . . 9  .  .
    #[4,] . . . 16  .
    #[5,] . . .  . 25
    

    另一个选项可能是slam 包:

    library(slam)
    m <- simple_triplet_matrix(1:5, 1:5, 1:5)
    m^2
    

    spray:

    library(spray)
    m <- spray(cbind(1:5, 1:5), 1:5)
    m$value <- m$value^2
    

    比较方法:

    n <- 1e3
    bench::mark(check = FALSE
              , base = {m <- diag(1:n); m %*% m}
              , base2 = {m <- diag(1:n); m^2}
              , Matrix = {m <- sparseMatrix(1:n, 1:n, x=1:n); m %*% m}
              , Matrix2 = {m <- sparseMatrix(1:n, 1:n, x=1:n); m^2}
              , slam = {m <- simple_triplet_matrix(1:n, 1:n, 1:n); m^2}
              , spray = {m <- spray(cbind(1:n, 1:n), 1:n); m$value <- m$value^2; m}
                )
    #  expression      min   median `itr/sec` mem_alloc `gc/sec` n_itr  n_gc
    #  <bch:expr> <bch:tm> <bch:tm>     <dbl> <bch:byt>    <dbl> <int> <dbl>
    #1 base       711.65ms 711.65ms      1.41    26.7MB     1.41     1     1
    #2 base2        2.48ms   2.66ms    236.      11.4MB    76.7    123    40
    #3 Matrix     687.17µs 712.63µs   1379.      63.1KB     4.00   690     2
    #4 Matrix2    610.89µs 637.48µs   1541.      55.2KB     4.00   771     2
    #5 slam         36.1µs  39.18µs  15309.      19.7KB     4.00  7652     2
    #6 spray        2.49ms   2.76ms    338.      81.3KB     5.97   170     3
    

    看起来slam 在内存使用和速度方面效率最高。

    【讨论】:

      猜你喜欢
      • 2018-12-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-10-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多