我该如何高效地将scipy稀疏矩阵转换成sympy稀疏矩阵?

3
我有一个矩阵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稀疏矩阵? - hpaulj
3个回答

3

错误

当您遇到一个您不理解的错误时,请花一些时间查看回溯信息。或者至少把它展示给我们看!

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。因此,以列表和字典的形式输入最合理。


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

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

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

1
这是您的错误的简化版本。
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]])

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接