方法#1:我们可以使用稀疏元素的行索引作为 ID,并将这些元素的相应值与np.multiply.reduceat https://docs.scipy.org/doc/numpy/reference/generated/numpy.ufunc.reduceat.html以获得所需的输出。
因此,实施将是 -
from scipy import sparse
from scipy.sparse import csc_matrix
r,c,v = sparse.find(a) # a is input sparse matrix
out = np.zeros(a.shape[0],dtype=a.dtype)
unqr, shift_idx = np.unique(r,return_index=1)
out[unqr] = np.multiply.reduceat(v, shift_idx)
样本运行 -
In [89]: # Let's create a sample csc_matrix
...: A = np.array([[-1,2,0,0],[0,0,0,0],[2,0,3,0],[4,5,6,0],[1,9,0,2]])
...: a = csc_matrix(A)
...:
In [90]: a
Out[90]:
<5x4 sparse matrix of type '<type 'numpy.int64'>'
with 10 stored elements in Compressed Sparse Column format>
In [91]: a.toarray()
Out[91]:
array([[-1, 2, 0, 0],
[ 0, 0, 0, 0],
[ 2, 0, 3, 0],
[ 4, 5, 6, 0],
[ 1, 9, 0, 2]])
In [92]: out
Out[92]: array([ -2, 0, 6, 120, 0, 18])
方法#2:我们正在执行基于 bin 的乘法。我们有基于箱的求和解决方案np.bincount https://docs.scipy.org/doc/numpy/reference/generated/numpy.bincount.html。因此,这里可以使用的一个技巧是将数字转换为对数,执行基于 bin 的求和,然后使用以下命令转换回原始格式exponential
(日志的反面)就是这样!对于负数,我们可能会添加一个或更多步骤,但让我们看看非负数的实现是什么样的 -
r,c,v = sparse.find(a)
out = np.exp(np.bincount(r,np.log(v),minlength = a.shape[0]))
out[np.setdiff1d(np.arange(a.shape[0]),r)] = 0
使用非负数运行的样本 -
In [118]: a.toarray()
Out[118]:
array([[1, 2, 0, 0],
[0, 0, 0, 0],
[2, 0, 3, 0],
[4, 5, 6, 0],
[1, 9, 0, 2]])
In [120]: out # Using listed code
Out[120]: array([ 2., 0., 6., 120., 18.])