【问题标题】:Building sparse COO matrix structure from Cartesian product of indices从索引的笛卡尔积构建稀疏的 COO 矩阵结构
【发布时间】:2018-08-22 11:19:28
【问题描述】:

问题

考虑

P: A (N, n_x) matrix.

然后我想找到一个稀疏 COO 矩阵的索引,这样

indices = []
for i in range(N):
    for j1 in range(n_x):
        for j2 in range(n_x):
            indices.append([P[i, j1], P[i, j2]])

indices = unique(indices, axis=0)

更快的解决方案

上述解决方案在时间和内存方面都是低效的。下面是使用 Numpy 的更快选项

col_idx = np.reshape(np.tile(P, n_x), [N, n_x, n_x]) 
row_idx = np.transpose(col_idx, [0,2,1])
indices = np.concatenate((row_idx[:,None], col_idx[:, None]), axis=1)
indices = np.unique(indices, axis=0)

但是请注意,这仍然需要构建 2 个 N*n_x*n_x 数组,如果我们只有少量的唯一元素,这可能会比必要的大得多。

问题

我如何构建一个快速但内存高效的算法来执行以下操作。目前快速解决方案不可用,因为它需要太多内存。

解决方案可以是 Python,但我可以用 C 编码的算法就足够了。

【问题讨论】:

    标签: python sparse-matrix


    【解决方案1】:

    我认为在 C++ 和 Python 中,要走的路都是使用集合。

    在下面的版本中,我使用了提供 apox 的 Numba。比纯 Python 版本提速 30 倍。

    Python

    import numba as nb
    import numpy as np
    import time
    
    N=500
    n_x=600
    
    P=np.random.randint(0,50,N*n_x).reshape(N,n_x)
    
    @nb.jit()
    def nb_sparse_coo(P):
      indices = set()
      for i in range(P.shape[0]):
          for j1 in range(P.shape[1]):
              for j2 in range(j1,P.shape[1]):
                  indices.add((P[i, j1], P[i, j2]))
      return np.array(list(indices))
    
    indices=nb_sparse_coo(P)
    

    【讨论】:

      猜你喜欢
      • 2019-06-11
      • 1970-01-01
      • 2021-09-22
      • 1970-01-01
      • 2011-10-02
      • 2016-03-14
      • 1970-01-01
      • 1970-01-01
      • 2017-02-17
      相关资源
      最近更新 更多