如何有效地将scipy稀疏矩阵转换为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],[ 6.82195979e-17,1.00000000e+00,-4.11166786e-17,[-4.98202332e-17,1.13957868e-17,[ 4.56847824e-15,1.32261454e-14,-7.22890998e-15,[-9.11597396e-15,-2.28796167e-14,1.26624823e-14,[ 1.80765584e-14,1.93779820e-14,-1.36520100e-14,1.00000000e+00]])

现在,我正尝试从此稀疏稀疏矩阵创建一个 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,**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文档可能不是最清晰的文档,但是大多数示例要么显示点的字典,要么显示ALL值加上形状的平面数组,要么显示列表参差不齐。我怀疑它正在尝试以这种方式处理您的矩阵,逐行查看它。

但是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格式,而且可能不是其他格式。加上{{1 }}在scipy.sparse文档中没有提到!

来自密集数组

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

SparseMatrix

或列表列表:

In [297]: M.A                                                                                        
Out[297]: 
array([[0.,0.,0.        ],[0.,0.17737341,0.12362175,0.24324156,[0.7666429,0.21848551],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,3): 0.24324155883057885,(3,4): 0.21848551209470246}

我不知道什么是最有效的。通常,在与SparseMatrix(5,dict(M.todok())) 合作时,我们(或至少我)不担心效率。只要让它工作就足够了。在sympy中,效率可能更为重要,因为其中的数组可能很大,而使用快速编译的numpy方法会大大提高速度。

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

,
from sympy.matrices import SparseMatrix
import scipy.sparse as sps

A = sps.random(100,10,format="dok")
B = SparseMatrix(100,dict(A.items()))

从喜欢高效内存结构的人的角度来看,这就像盯着深渊。但这会起作用。

,

这是错误的简化版本。

from scipy import sparse
row = np.array([0,1,2,2])
col = np.array([0,2])
data = np.array([1,3,4,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,2],[0,3],[4,6]])