import numpy
a = numpy.array([
[0, 1, 0, 0],
[1, 0, 0, 0],
[0, 0, 1, 0],
[0, 0, 0, 0],
[0, 0, 0, 0],
])
numpy.any(a, axis=0)
numpy.any(a, axis=1)
produces
array([ True, True, True, False])
array([ True, True, True, False, False])
然而,之后
from scipy import sparse
a = sparse.csr_matrix(a)
相同numpy.any(a, axis)
调用产生
<5x4 sparse matrix of type '<class 'numpy.intc'>'
with 3 stored elements in Compressed Sparse Row format>
and
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<__array_function__ internals>", line 5, in any
File "C:\Users\user\.conda\envs\py385\lib\site-packages\numpy\core\fromnumeric.py", line 2330, in any
return _wrapreduction(a, np.logical_or, 'any', axis, None, out, keepdims=keepdims)
File "C:\Users\user\.conda\envs\py385\lib\site-packages\numpy\core\fromnumeric.py", line 87, in _wrapreduction
return ufunc.reduce(obj, axis, dtype, out, **passkwargs)
numpy.AxisError: axis 1 is out of bounds for array of dimension 0
当然,a
实际上是一个很大的稀疏矩阵,需要转换为普通矩阵numpy
数组不是一个选项。我怎样才能获得相同(或等效)的结果csr_matrix
和别的scipy.sparse
矩阵?
ADDED:
根据scipy 官方文档中的使用信息 https://docs.scipy.org/doc/scipy/reference/sparse.html#usage-information,
尽管它们与 NumPy 数组相似,但它是强烈劝阻直接在这些矩阵上使用 NumPy 函数,因为 NumPy 可能无法正确转换它们进行计算,从而导致意外(且不正确)的结果。如果您确实想将 NumPy 函数应用于这些矩阵,请首先检查 SciPy 是否有针对给定稀疏矩阵类的自己的实现,或者将稀疏矩阵转换为 NumPy 数组(例如,使用数组()类的方法)首先在应用该方法之前。
我正在寻找“它自己的实现”或同等内容。