【问题标题】:How can I efficiently convert a scipy sparse matrix into a sympy sparse matrix?如何有效地将 scipy 稀疏矩阵转换为 sympy 稀疏矩阵?
【发布时间】:2020-12-07 23:09:38
【问题描述】:

我有一个具有以下属性的矩阵 A。

<1047x1047 sparse matrix of type '<class 'numpy.float64'>'
    with 888344 stored elements in Compressed Sparse Column format>

A 有这个内容。

array([[ 1.00000000e+00, -5.85786642e-17, -3.97082034e-17, ...,
         0.00000000e+00,  0.00000000e+00,  0.00000000e+00],
       [ 6.82195979e-17,  1.00000000e+00, -4.11166786e-17, ...,
         0.00000000e+00,  0.00000000e+00,  0.00000000e+00],
       [-4.98202332e-17,  1.13957868e-17,  1.00000000e+00, ...,
         0.00000000e+00,  0.00000000e+00,  0.00000000e+00],
       ...,
       [ 4.56847824e-15,  1.32261454e-14, -7.22890998e-15, ...,
         1.00000000e+00,  0.00000000e+00,  0.00000000e+00],
       [-9.11597396e-15, -2.28796167e-14,  1.26624823e-14, ...,
         0.00000000e+00,  1.00000000e+00,  0.00000000e+00],
       [ 1.80765584e-14,  1.93779820e-14, -1.36520100e-14, ...,
         0.00000000e+00,  0.00000000e+00,  1.00000000e+00]])

现在我正在尝试从这个 scipy 稀疏矩阵创建一个 sympy 稀疏矩阵。

from sympy.matrices import SparseMatrix
A = SparseMatrix(A)

但我收到此错误消息。

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all().

我很困惑,因为这个矩阵没有逻辑条目。

感谢您的帮助!

【问题讨论】:

  • sympy 函数接受哪些输入?有没有提到 acipy sparse?

标签: scipy sparse-matrix sympy


【解决方案1】:

错误

当您遇到不理解的错误时,请花点时间查看回溯。或者至少给我们看看!

In [288]: M = sparse.random(5,5,.2, 'csr')                                                           

In [289]: M                                                                                          
Out[289]: 
<5x5 sparse matrix of type '<class 'numpy.float64'>'
    with 5 stored elements in Compressed Sparse Row format>

In [290]: print(M)                                                                                   
  (1, 1)    0.17737340878962138
  (2, 2)    0.12362174819457106
  (2, 3)    0.24324155883057885
  (3, 0)    0.7666429046432961
  (3, 4)    0.21848551209470246

In [291]: SparseMatrix(M)                                                                            
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-291-cca56ea35868> in <module>
----> 1 SparseMatrix(M)

/usr/local/lib/python3.6/dist-packages/sympy/matrices/sparse.py in __new__(cls, *args, **kwargs)
    206             else:
    207                 # handle full matrix forms with _handle_creation_inputs
--> 208                 r, c, _list = Matrix._handle_creation_inputs(*args)
    209                 self.rows = r
    210                 self.cols = c

/usr/local/lib/python3.6/dist-packages/sympy/matrices/matrices.py in _handle_creation_inputs(cls, *args, **kwargs)
   1070                             if 0 in row.shape:
   1071                                 continue
-> 1072                         elif not row:
   1073                             continue
   1074 

/usr/local/lib/python3.6/dist-packages/scipy/sparse/base.py in __bool__(self)
    281             return self.nnz != 0
    282         else:
--> 283             raise ValueError("The truth value of an array with more than one "
    284                              "element is ambiguous. Use a.any() or a.all().")
    285     __nonzero__ = __bool__

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all().

完全理解需要阅读sympy 代码,但粗略一看表明它正在尝试将您的输入作为“完整矩阵”处理,并查看行。该错误不是您对条目进行逻辑运算的结果,而是sympy 正在对您的稀疏矩阵进行逻辑测试。它正在尝试检查该行是否为空(因此它可以跳过它)。

SparseMatrix 文档可能不是最清楚的,但大多数示例要么显示点的字典,要么显示所有值加上形状的平面数组,或者显示不规则的列表列表。我怀疑它试图以这种方式处理您的矩阵,逐行查看它。

但是M这一行本身就是一个稀疏矩阵:

In [295]: [row for row in M]                                                                         
Out[295]: 
[<1x5 sparse matrix of type '<class 'numpy.float64'>'
    with 0 stored elements in Compressed Sparse Row format>,
 <1x5 sparse matrix of type '<class 'numpy.float64'>'
    with 1 stored elements in Compressed Sparse Row format>,
...]

并尝试检查该行是否为空 not row 会产生此错误:

In [296]: not [row for row in M][0]                                                                  
...
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all().

很明显SparseMatrix 不能按原样处理scipy.sparse 矩阵(至少不是csr 或csc 格式,可能不是其他格式。另外scipy.sparse 在@987654334 的任何地方都没有提到@文档!

来自密集数组

将稀疏矩阵转换为密集矩阵确实有效:

In [297]: M.A                                                                                        
Out[297]: 
array([[0.        , 0.        , 0.        , 0.        , 0.        ],
       [0.        , 0.17737341, 0.        , 0.        , 0.        ],
       [0.        , 0.        , 0.12362175, 0.24324156, 0.        ],
       [0.7666429 , 0.        , 0.        , 0.        , 0.21848551],
       [0.        , 0.        , 0.        , 0.        , 0.        ]])

In [298]: SparseMatrix(M.A)                                                                          
Out[298]: 
⎡        0                  0                  0                  0                  0        ⎤
...⎦

或列表列表:

 SparseMatrix(M.A.tolist()) 

来自字典

dok 格式将稀疏矩阵存储为dict,然后可以是

In [305]: dict(M.todok())                                                                            
Out[305]: 
{(3, 0): 0.7666429046432961,
 (1, 1): 0.17737340878962138,
 (2, 2): 0.12362174819457106,
 (2, 3): 0.24324155883057885,
 (3, 4): 0.21848551209470246}

作为输入效果很好:

SparseMatrix(5,5,dict(M.todok()))

我不知道什么是最有效的。通常在使用sympy 时,我们(或至少我)不担心效率。只要让它工作就足够了。效率在numpy/scipy 中更为相关,其中数组可能很大,并且使用快速编译的 numpy 方法在速度上有很大差异。

最后 - numpy 和 sympy 没有集成。这也适用于稀疏版本。 sympy 是基于 Python 构建的,而不是 numpy。所以列表和字典形式的输入是最有意义的。

【讨论】:

    【解决方案2】:

    这是您的错误的简化版本。

    from scipy import sparse
    row = np.array([0, 0, 1, 2, 2, 2])
    col = np.array([0, 2, 2, 0, 1, 2])
    data = np.array([1, 2, 3, 4, 5, 6])
    A = sparse.csc_matrix((data, (row, col)), shape=(3, 3))
    

    所以A是一个有6个元素的稀疏矩阵:

    <3x3 sparse matrix of type '<class 'numpy.intc'>'
        with 6 stored elements in Compressed Sparse Column format>
    

    在其上调用SparseMatrix() 会返回与您遇到的相同类型的错误。您可能想先将 A 转换为 numpy 数组:

    >>> SparseMatrix(A.todense())
    Matrix([
    [1, 0, 2],
    [0, 0, 3],
    [4, 5, 6]])
    

    【讨论】:

      【解决方案3】:
      from sympy.matrices import SparseMatrix
      import scipy.sparse as sps
      
      A = sps.random(100, 10, format="dok")
      B = SparseMatrix(100, 10, dict(A.items()))
      

      从喜欢高效记忆结构的人的角度来看,这就像凝视深渊。但它会起作用。

      【讨论】:

        猜你喜欢
        • 2023-04-10
        • 2014-12-21
        • 2021-11-25
        • 2017-07-02
        • 1970-01-01
        • 2018-01-19
        • 1970-01-01
        • 1970-01-01
        • 2017-03-26
        相关资源
        最近更新 更多