错误
当您遇到不理解的错误时,请花点时间查看回溯。或者至少给我们看看!
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。所以列表和字典形式的输入是最有意义的。