简体   繁体   English

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

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

I have three sparse matrices A , B , and C , and I want to compute the element-wise result of: (A*B)/C , ie element-wise multiply A with B , then element-wise divide by C .我有三个稀疏矩阵ABC ,我想计算以下元素的结果: (A*B)/C ,即按元素乘以AB ,然后按元素除以C

Naturally, since C is sparse, division by zero results in most of the matrix elements set to infinity/nan.自然地,由于C是稀疏的,除以零会导致大多数矩阵元素设置为无穷大/nan。 However, I am not interested in these elements since for my needs A is essentially a mask, and all zero indices in A should stay zeros in the result.但是,我对这些元素不感兴趣,因为根据我的需要, A本质上是一个掩码,并且A所有零索引都应在结果中保持为零。 In practice, scipy does calculate these items even though they could be masked if we decide that 0/0=0 .在实践中,即使我们决定0/0=0可以屏蔽它们,scipy 也会计算这些项目。

What is the best way to avoid the redundant calculations of elements that are zeros in A ?避免对A中为零的元素进行冗余计算的最佳方法是什么?

Example for concreteness:具体性示例:

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

Required result:要求的结果:

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

Note: I am mostly interested in the performance of this operation.注意:我最感兴趣的是这个操作的性能。

This is the best way to do this but if C.data has any 0s in it they'll still come out as NaN .这是执行此操作的最佳方法,但如果C.data有任何 0,它们仍然会作为NaN How you choose to handle this probably depends on what exactly you're doing.您选择如何处理此问题可能取决于您究竟在做什么。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM