numpy.any(axis=i) for scipy.sparse


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)

产生

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>

Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<__array_function__ internals>", line 5, in any
File "C:Usersuser.condaenvspy385libsite-packagesnumpycorefromnumeric.py", line 2330, in any
return _wrapreduction(a, np.logical_or, 'any', axis, None, out, keepdims=keepdims)
File "C:Usersuser.condaenvspy385libsite-packagesnumpycorefromnumeric.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矩阵相同(或等效(的结果?

添加:

根据官方scipy文档中的使用信息,

尽管它们与NumPy数组相似,但强烈建议直接在这些矩阵上使用NumPy函数,因为NumPy可能无法正确转换它们进行计算,从而导致意外(和不正确(的结果。如果您确实想将NumPy函数应用于这些矩阵,请首先检查SciPy是否对给定的稀疏矩阵类有自己的实现,或者在应用该方法之前,先将稀疏矩阵转换为NumPy数组(例如,使用类的toarray((方法(。

我正在寻找"它自己的实现";或等效物。

您可以在布尔数组上使用sum而不是any

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],
])
from scipy import sparse
a = sparse.csr_matrix(a.astype(bool))
# Use sum instead of any on a bool array
print(a.sum(axis=0).astype(bool))
print(a.sum(axis=1).flatten().astype(bool))

输出:

[[ True  True  True False]]
[[ True  True  True False False]]

如果你想做"所有",那就有点棘手了,因为scipy似乎没有"prod"的实现。但这篇文章对这种情况有一个答案。

最新更新