检查两个 scipy.sparse.csr_matrix 是否相等 [英] Check if two scipy.sparse.csr_matrix are equal
问题描述
我想检查两个 csr_matrix 是相等的.
I want to check if two csr_matrix are equal.
如果我这样做:
x.__eq__(y)
我明白了:
raise ValueError("The truth value of an array with more than one "
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all().
然而,这很有效:
assert (z in x for z in y)
有没有更好的方法来做到这一点?也许使用一些 scipy
优化的函数代替?
Is there a better way to do it? maybe using some scipy
optimized function instead?
非常感谢
推荐答案
我们可以假设它们的形状相同吗?
Can we assume they are the same shape?
In [202]: a=sparse.csr_matrix([[0,1],[1,0]])
In [203]: b=sparse.csr_matrix([[0,1],[1,1]])
In [204]: (a!=b).nnz==0
Out[204]: False
这会检查不等式数组的稀疏性.
This checks the sparsity of the inequality array.
如果您尝试 a==b
(至少第一次使用它),它会给您一个效率警告.那是因为它必须测试所有这些零.它不能充分利用稀疏性.
It will give you an efficiency warning if you try a==b
(at least the 1st time you use it). That's because it has to test all those zeros. It can't take much advantage of the sparsity.
您需要一个相对较新的版本才能使用这样的逻辑运算符.您是否尝试在某些 if
表达式中使用 x.__eq__(y)
,还是仅从该表达式中出错?
You need a relatively recent version to use logical operators like this. Were you trying to use x.__eq__(y)
in some if
expression, or did you get error from just that expression?
一般来说,您可能想先检查几个参数.相同的shape
,相同的nnz
,相同的dtype
.你需要小心浮动.
In general you probably want to check several parameters first. Same shape
, same nnz
, same dtype
. You need to be careful with floats.
对于密集数组 np.allclose
是测试相等性的好方法.如果稀疏数组不太大,那也不错
For dense arrays np.allclose
is a good way of testing equality. And if the sparse arrays aren't too large, that might be good as well
np.allclose(a.A, b.A)
allclose
使用 all(less_equal(abs(x-y), atol + rtol * abs(y)))
.您可以使用 a-b
,但我怀疑这也会发出效率警告.
allclose
uses all(less_equal(abs(x-y), atol + rtol * abs(y)))
. You can use a-b
, but I suspect that this too will give an efficiecy warning.
这篇关于检查两个 scipy.sparse.csr_matrix 是否相等的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!