【问题标题】:numpy array to scipy.sparse matrixnumpy 数组到 scipy.sparse 矩阵
【发布时间】:2012-05-28 01:15:20
【问题描述】:

给定一个任意的 numpy 数组 (ndarray),是否有将其转换为 scipy.sparse 矩阵的函数或捷径?

我想要一些类似的东西:

A = numpy.array([0,1,0],[0,0,0],[1,0,0])
S = to_sparse(A, type="csr_matrix")

【问题讨论】:

    标签: numpy python-3.x scipy sparse-matrix


    【解决方案1】:

    请参考这个答案:https://stackoverflow.com/a/65017153/9979257

    在这个答案中,我已经解释了如何将二维 NumPy 矩阵转换为 CSR 或 CSC 格式。

    【讨论】:

      【解决方案2】:

      帮助中有一个非常有用且相关的示例!

      import scipy.sparse as sp
      help(sp)
      

      这给出了:

      Example 2
      ---------
      
      Construct a matrix in COO format:
      
      >>> from scipy import sparse
      >>> from numpy import array
      >>> I = array([0,3,1,0])
      >>> J = array([0,3,1,2])
      >>> V = array([4,5,7,9])
      >>> A = sparse.coo_matrix((V,(I,J)),shape=(4,4))
      

      还值得注意的是各种构造函数(再次来自帮助):

          1. csc_matrix: Compressed Sparse Column format
          2. csr_matrix: Compressed Sparse Row format
          3. bsr_matrix: Block Sparse Row format
          4. lil_matrix: List of Lists format
          5. dok_matrix: Dictionary of Keys format
          6. coo_matrix: COOrdinate format (aka IJV, triplet format)
          7. dia_matrix: DIAgonal format
      
      To construct a matrix efficiently, use either lil_matrix (recommended) or
      dok_matrix. The lil_matrix class supports basic slicing and fancy
      indexing with a similar syntax to NumPy arrays.  
      

      你的例子很简单:

      S = sp.csr_matrix(A)
      

      【讨论】:

      • @clstaudt 我不确定您在寻找什么,sp.csr_matrix(A) 将从密集的 numpy 数组 A 构造一个 csr 类型矩阵,而 sp.csc_matrix(A) 将构造一个类型 @ 987654329@ 矩阵等...构造函数您正在寻找的高效转换函数(尽管阅读帮助中的注意事项)。
      • 你说得对,构造函数完成了我正在寻找的转换。我希望他们只采用与条目存储方式相对应的参数,例如: A = sparse.coo_matrix((V,(I,J)),shape=(4,4))
      【解决方案3】:

      我通常会做类似的事情

      >>> import numpy, scipy.sparse
      >>> A = numpy.array([[0,1,0],[0,0,0],[1,0,0]])
      >>> Asp = scipy.sparse.csr_matrix(A)
      >>> Asp
      <3x3 sparse matrix of type '<type 'numpy.int64'>'
          with 2 stored elements in Compressed Sparse Row format>
      

      【讨论】:

      • 嗯,这很简单,我应该尝试一下。我没想到构造函数会进行转换。这也适用于其他稀疏矩阵类型的构造函数。
      猜你喜欢
      • 1970-01-01
      • 2011-03-21
      • 1970-01-01
      • 2023-04-09
      • 2015-02-04
      • 1970-01-01
      • 2021-10-25
      • 2013-11-26
      相关资源
      最近更新 更多