python - 如何在稀疏矩阵上执行 <= 和 >=?
问题描述
是否可以在 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。这可能吗?这种操作的性能是什么?
解决方案
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,结果就是真.
它警告我们,如果我们进行这种测试,使用稀疏矩阵不会为我们节省空间或时间(与密集数组相比)。它不会杀死我们,它只是不会那么有效。
推荐阅读
- python - 为什么 pkgutil 风格的命名空间包缺少 __init__.py?
- git - 过时的 PR 差异
- javascript - 当散列锚在 URL 中时显示选择 DIV
- c# - 如何为 AvalonEdit (ICSharpCode) 文本编辑器控件创建事件处理程序?
- c# - 从数据库表中检索数据并在标签中获取其值时出错
- ruby - 我可以从它的受让人那里得到变量名吗?
- c - 用于小数据文件 (~10KB) 的快速且强大的校验和算法
- bash - 从 bash 中的原始数据中提取列表,或者只是格式化输出 list_name 后跟列表内容
- reactjs - React 和 TypeScript - 组件
- objective-c - 为什么我不能访问这个指针的值。目标c