找出两个numpy数组之间的差异

2024-10-03 17:22:07 发布

您现在位置:Python中文网/ 问答频道 /正文

我有两个来自文本文件的数组。通过观察,它看起来完全一样。但是当我测试这两个数组的等价性时,它们失败了——元素方面,形状方面等等。。我用了numpy测试,答案是here。在

这是两个matrices。在

import numpy as np

class TextMatrixAssertions(object):
    def assertArrayEqual(self, dataX, dataY):
        x = np.loadtxt(dataX)
        y = np.loadtxt(dataY)

        if not np.array_equal(x, y):
            raise Exception("array_equal fail.")

        if not np.array_equiv(x, y):
            raise Exception("array_equiv fail.")

        if not np.allclose(x, y):
            raise Exception("allclose fail.")

dataX = "MyMatrix.txt"
dataY = "MyMatrix2.txt"
test = TextMatrixAssertions()
test.assertArrayEqual(dataX, dataY)

我想知道这两个数组之间是否真的存在一些差异,如果没有,是什么导致了失败。在


Tags: numpyifnpexceptionnot数组equalarray
3条回答

它们不相等,它们有54种不同的元素。在

np.sum(x!=y)

54

要查找哪些元素不同,可以执行以下操作:

^{pr2}$

还有一个解决方案。您可以看到不相等的元素的值。如果运行下面的代码,您将看到具有nan值的元素不相等,因此导致引发异常。在

import numpy as np

class TextMatrixAssertions(object):
    def assertArrayEqual(self, dataX, dataY):
        x = np.loadtxt(dataX)
        y = np.loadtxt(dataY)

        if not np.array_equal(x, y):
            not_equal_idx = np.where(x != y)
            for idx1, idx2 in zip(not_equal_idx[0],not_equal_idx[1]):
                print(x[idx1][idx2])
                print(y[idx1][idx2])
            raise Exception("array_equal fail.")

        if not np.array_equiv(x, y):
            raise Exception("array_equiv fail.")

        if not np.allclose(x, y):
            raise Exception("allclose fail.")

dataX = "MyMatrix.txt"
dataY = "MyMatrix2.txt"
test = TextMatrixAssertions()
test.assertArrayEqual(dataX, dataY)

输出:

^{pr2}$

你应该先用一个更小更简单的矩阵来测试你的函数。在

例如:

import numpy as np
from io import StringIO



class TextMatrixAssertions(object):
    def assertArrayEqual(self, dataX, dataY):
        x = np.loadtxt(dataX)
        y = np.loadtxt(dataY)

        if not np.array_equal(x, y):
            raise Exception("array_equal fail.")

        if not np.array_equiv(x, y):
            raise Exception("array_equiv fail.")

        if not np.allclose(x, y):
            raise Exception("allclose fail.")

        return True

a = StringIO(u"0 1\n2 3")
b = StringIO(u"0 1\n2 3")
test = TextMatrixAssertions()
test.assertArrayEqual(a,b)

输出

^{pr2}$

我想不是你的代码问题。您也可以尝试在x和y中加载相同的文件并查看输出。在

要查看哪些元素不同,可以使用not_equal

示例

^{3}$

相关问题 更多 >