检查两个scipy.sparse.csr_matrix是否相等 [英] Check if two scipy.sparse.csr_matrix are equal

查看:191
本文介绍了检查两个scipy.sparse.csr_matrix是否相等的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想检查是否两个 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 all those it would have to test all those zeros.

您需要一个相对较新的版本才能使用像这样的逻辑运算符.您是要在某些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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆