scipy - 如何有效地将 scipy 稀疏矩阵转换为 sympy 稀疏矩阵?

标签 scipy sparse-matrix sympy

我有一个具有以下属性的矩阵 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().

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

感谢您的帮助!

最佳答案

错误

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

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 矩阵(至少在 csrcsc 格式,可能不是其他格式。另外 scipy.sparseSparseMatrix 文档的任何地方都没有提到!

从密集阵列

将稀疏矩阵转换为其等效的稠密矩阵确实可行:

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 方法会在速度上产生很大差异。

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

关于scipy - 如何有效地将 scipy 稀疏矩阵转换为 sympy 稀疏矩阵?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63474151/

相关文章:

python - 构造稀疏矩阵后,从稀疏到密集再到稀疏的转换会再次降低密度

scipy - 在 scipy 中获取非归一化特征向量

opencv - 在openCV中做SparseMat(稀疏矩阵)操作

python - Sympy 中符号的 boolean 运算

python - 使用 scipy : expm, expm2 和 expm3 进行矩阵求幂

python - 稀疏矩阵行中的连续元素

python - 访问python中特定矩阵行中的非零元素

Python/Sympy三次方程三角解法

Sympy 符号和 cls 参数

python - scipy 中的等距样条评估