首页 > 解决方案 > 如何在稀疏矩阵上执行 <= 和 >=?

问题描述

是否可以在 Scipy 稀疏矩阵上执行 <= 或 >= 操作,如果所有相应元素的操作为真,则表达式返回 True ?例如,a <= b 表示对于矩阵 (A, B) 中的所有对应元素 (a, b),a <= b? 这是一个需要考虑的例子:

import numpy as np
from scipy.sparse import csr_matrix

np.random.seed(0)
mat = csr_matrix(np.random.rand(10, 12)>0.7, dtype=int)
print(mat.A)
print()

np.random.seed(1)
matb = csr_matrix(np.random.rand(10, 12)>0.7, dtype=int)
print(matb.A)

运行它会给出警告:SparseEfficiencyWarning: Comparing sparse matrices using >= and <= is inefficient, using <, >, or !=, instead并给出错误:ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all().

我希望能够采用2个稀疏矩阵A和B,并确定(A,B)中每对对应元素(a,b)的A <= B。这可能吗?这种操作的性能是什么?

标签: pythonnumpyscipysparse-matrix

解决方案


In [402]: np.random.seed = 0
     ...: mat = sparse.csr_matrix(np.random.rand(10, 12)>0.7, dtype=int)
In [403]: mat
Out[403]: 
<10x12 sparse matrix of type '<class 'numpy.int64'>'
    with 40 stored elements in Compressed Sparse Row format>
In [404]: mat.A
Out[404]: 
array([[1, 1, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0],
       [1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0],
       ...
       [0, 1, 0, 1, 0, 0, 0, 1, 1, 0, 1, 1],
       [0, 0, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1]], dtype=int64)
In [405]: np.random.seed = 1
     ...: matb = sparse.csr_matrix(np.random.rand(10, 12)>0.7, dtype=int)

In [407]: mat<matb
Out[407]: 
<10x12 sparse matrix of type '<class 'numpy.bool_'>'
    with 27 stored elements in Compressed Sparse Row format>
In [408]: mat>=matb
/home/paul/.local/lib/python3.6/site-packages/scipy/sparse/compressed.py:295: SparseEfficiencyWarning: Comparing sparse matrices using >= and <= is inefficient, using <, >, or !=, instead.
  "using <, >, or !=, instead.", SparseEfficiencyWarning)
Out[408]: 
<10x12 sparse matrix of type '<class 'numpy.float64'>'
    with 93 stored elements in Compressed Sparse Row format>

在您的情况下,既不是mat也不matb是特别稀疏,可能的 120 个中有 40 个和 36 个非零。即便如此,mat<matb结果还是 27 个非零(真)值,而>=测试结果是 93。只要两个矩阵都是 0,结果就是真.

它警告我们,如果我们进行这种测试,使用稀疏矩阵不会为我们节省空间或时间(与密集数组相比)。它不会杀死我们,它只是不会那么有效。


推荐阅读