【问题标题】:Scipy sparse matrix – element-wise multiplication and division of only non-zero elementsScipy 稀疏矩阵 - 仅非零元素的元素乘法和除法
【发布时间】:2020-09-25 20:29:52
【问题描述】:

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

自然,由于C 是稀疏的,除以零会导致大多数矩阵元素设置为无穷大/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

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

【问题讨论】:

  • 如果所有矩阵的稀疏度都相同,我们可以使用data 属性进行数学运算,这将是一个一维数组。
  • 这很好,但data 包含明确的零。

标签: python numpy scipy time-complexity sparse-matrix


【解决方案1】:

这是执行此操作的最佳方式,但如果 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

【讨论】:

    猜你喜欢
    • 2015-03-27
    • 1970-01-01
    • 1970-01-01
    • 2015-09-20
    • 2014-05-04
    • 1970-01-01
    • 2017-07-21
    • 2021-06-26
    • 1970-01-01
    相关资源
    最近更新 更多