Scipy 稀疏矩阵——仅对非零元素进行逐元素乘除

Scipy sparse matrix – element-wise multiplication and division of only non-zero elements

我有三个稀疏矩阵 ABC,我想计算以下元素的结果:(A*B)/C,即元素-明智地将 AB 相乘,然后按元素除以 C.

自然地,由于 C 是稀疏的,除以零会导致大多数矩阵元素设置为 infinity/nan。但是,我对这些元素不感兴趣,因为根据我的需要 A 本质上是一个掩码,并且 A 中的所有零索引应该在结果中保持为零。实际上,scipy 确实会计算这些项目,即使如果我们决定 0/0=0.

可以屏蔽它们也是如此

避免冗余计算 A 中为零的元素的最佳方法是什么?

具体示例:

A = sparse.csr_matrix(np.identity(100))
B = sparse.csr_matrix(np.identity(100) * 2)
C = sparse.csr_matrix(np.identity(100) * 5)

Z = ((A*B)/C)

Z[0,0]
>>> 0.4
Z[0,1]
>>> nan

要求的结果:

Z[0,0]
>>> 0.4
Z[0,1]
>>> 0.0

注意:我最感兴趣的是这个操作的性能。

这是执行此操作的最佳方法,但如果 C.data 中有任何 0,它们仍然会显示为 NaN。你选择如何处理这个可能取决于你到底在做什么。

A = sparse.csr_matrix(np.identity(100))
B = sparse.csr_matrix(np.identity(100) * 2)
C = sparse.csr_matrix(np.identity(100) * 5)

C.data = 1 / C.data

Z = A*B*C

>>> Z
<100x100 sparse matrix of type '<class 'numpy.float64'>'
    with 100 stored elements in Compressed Sparse Row format>

>>> Z[0,0]
0.4
>>> Z[0,1]
0.0