首页 > 解决方案 > 比较两个二维数组的准确性的非断言方法

问题描述

我目前正在训练一个对帧进行分类的 LSTM。我想要做的是比较两个 2d numpy 数组以检查我的预测和目标之间的准确性。我目前正在寻找使用 NumPy / SciPy 解决这个问题的非天真的方法。

我知道有 np.testing.assert_array_equal(x, y) 它使用断言来输出结果。我正在寻找一种使用 NumPy / SciPy 解决此问题的方法,以便我可以存储结果而不是 Assert 打印输出:

Arrays are not equal

(mismatch 14.285714285714292%)
 x: array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0])
 y: array([0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0])
x = np.asarray([[0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0]])

y = np.asarray([[0, 0, 0], [0, 0, 0], [0, 0, 1], [0, 1, 0], [1, 0, 0], [0, 0, 0], [0, 0, 0]])

try:
    np.testing.assert_array_equal(x, y)
    res = True
except AssertionError as err:
    res = False
    print (err)

我正在寻找一种方法来存储这两个数组的不匹配而不使用幼稚的方式(两个比较循环):

accuracy = thisFunction(x,y)

我确信 NumPy 中有一些东西可以解决这个问题,我没有运气搜索内置函数。

标签: pythonpython-3.xnumpymultidimensional-arrayscipy

解决方案


np.array_equal(x, y)大致相当于(x == y).all()。您可以使用它来计算差异:

def array_comp(x, y):
    """
    Return the status of the comparison and the discrepancy.

    For arrays of the same shape, the discrepancy is a ratio of mismatches to the total size.
    For arrays of different shapes or sizes, the discrepancy is a message indicating the mismatch.
    """
    if x.shape != y.shape:
        return False, 'shape'
    count = x.size - np.count_nonzero(x == y)
    return count == 0, count / x.size

推荐阅读