简体   繁体   English

如何在python中检查(numpy数组)的真实相等性?

[英]How to check for real equality (of numpy arrays) in python?

I have some function in python returning a numpy.array: 我在python中有一些返回numpy.array的函数:

matrix = np.array([0.,0.,0.,0.,0.,0.,1.,1.,1.,0.],
             [0.,0.,0.,1.,1.,0.,0.,1.,0.,0.])

def some_function:
    rows1, cols1 = numpy.nonzero(matrix)
    cols2 = numpy.array([6,7,8,3,4,7])
    rows2 = numpy.array([0,0,0,1,1,1])
    print numpy.array_equal(rows1, rows2) # returns True
    print numpy.array_equal(cols1, cols2) # returns True
    return (rows1, cols1)                   # or (rows2, cols2)

It should normally extract the indices of nonzero entries of a matrix (rows1, cols1). 它通常应提取矩阵的非零项的索引(rows1,cols1)。 However, I can also extract the indices manually (rows2, cols2). 但是,我也可以手动提取索引(rows2,cols2)。 The problem is that the program returns different results depending on whether the function returns (rows1, cols1) or (rows2, cols2) , although the arrays should be equal. 问题是,尽管数组应该相等,但程序根据函数返回(rows1, cols1)还是(rows2, cols2)返回不同的结果。

I should probably add that this code is used in the context of pyipopt , which calls a c++ software package IPOPT . 我可能应该补充一点,该代码在pyipopt的上下文中使用 ,它调用了c ++软件包IPOPT The problem then occurs within this package. 然后在此程序包中发生问题。

Can it be that the arrays are not "completely" equal? 可能是数组不“完全”相等吗? I would say that they somehow must be because I am not modifying anything but returning one instead of the other. 我会说它们一定是因为我没有修改任何东西,而是返回了一个而不是另一个。

Any idea on how to debug this problem? 关于如何调试此问题的任何想法?

You could check where the arrays are not equal: 您可以检查其中的数组是不相等的:

print(where(rows1 != rows2))

But what you are doing is unclear, first there is no nonzeros function in numpy, only a nonzero which returns a tuple of coordinates. 但是您正在做什么尚不清楚,首先是numpy中没有nonzeros函数,只有一个非零返回坐标元组。 Are you only using the one corresponding to the rows? 您仅使用与行相对应的那个吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM