【问题标题】:Non-Assert Way To Compare Two 2D Arrays for Accuracy比较两个二维数组的准确性的非断言方法
【发布时间】:2019-01-22 03:34:38
【问题描述】:

我目前正在训练一个对帧进行分类的 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 中有一些东西可以解决这个问题,但我没有找到内置函数。

【问题讨论】:

  • np.all_close
  • 等等,堆栈溢出降价现在允许三次反引号?太棒了!

标签: python python-3.x numpy multidimensional-array scipy


【解决方案1】:

正如 hpaulj 在评论中指出的那样,您可以使用 numpy.allclose() 来检查数组是否相等,可接受的差异最多为某个容差值(见下文或 NumPy 注释)。

这是一个带有两个简单浮点数组的小插图。

In [7]: arr1 = np.array([1.3, 1.4, 1.5, 3.4]) 
In [8]: arr2 = np.array([1.299999, 1.4, 1.4999999, 3.3999999999]) 

In [9]: np.allclose(arr1, arr2) 
Out[9]: True

numpy.allclose 将返回 True 如果数组中的对应元素不同(仅达到容差值)。否则它将返回False。 NumPy 默认的相对和绝对容差值分别为rtol=1e-05atol=1e-08


话虽如此,如果您只想比较int 数组,那么您最好使用numpy.array_equal(),它大约为。比 numpy.allclose 快​​ 8 倍。

In [17]: arr1 = np.random.randint(23045) 
In [18]: arr2 = np.random.randint(23045) 

In [19]: %timeit np.allclose(arr1, arr2) 
22.9 µs ± 471 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)

In [20]: %timeit np.array_equal(arr1, arr2) 
3.99 µs ± 68.6 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

【讨论】:

  • 这不是比较整数数组相等性的最佳选择。
  • @MadPhysicist 谢谢,我用替代方法更新了答案。
  • OP 将问题更改为不重复。
【解决方案2】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-28
    • 1970-01-01
    • 1970-01-01
    • 2016-04-14
    • 1970-01-01
    相关资源
    最近更新 更多