【问题标题】:Compare NumPy arrays with threshold and return the differences将 NumPy 数组与阈值进行比较并返回差异
【发布时间】:2017-12-23 15:25:48
【问题描述】:

在我的脚本中,我需要将相当大的 NumPy 数组(2D 或 3D)与阈值进行比较。 比较本身可以使用“allclose”函数轻松完成,如下所示:

Threshold = 0.1
if (np.allclose(Arr1, Arr2, Threshold, equal_nan=True)):
    Print('Same')

了解哪些单元格不同的最简单(但幼稚)的方法是使用简单的 for 循环代码,如下所示:

def CheckWhichCellsAreNotEqualInArrays(Arr1,Arr2,Threshold):
   if not Arr1.shape == Arr2.shape:
       return ['Arrays size not the same']
   Dimensions = Arr1.shape  
   Diff = []
   for i in range(Dimensions [0]):
       for j in range(Dimensions [1]):
           if not np.allclose(Arr1[i][j], Arr2[i][j], Threshold, equal_nan=True):
               Diff.append(',' + str(i) + ',' + str(j) + ',' + str(Arr1[i,j]) + ',' 
               + str(Arr2[i,j]) + ',' + str(Threshold) + ',Fail\n')
       return Diff

(对于 3D 数组也是如此 - 还有 1 个 for 循环)

当数组很大并且充满不相等的单元格时,这种方式非常慢。

如果它们不相同,是否有一种快速直接的方法 - 获取不均匀单元格的列表?也许是 NumPy 本身的一些内置函数?

【问题讨论】:

  • 生成样本数据?
  • 是的。如果单元格不相等 - 我想获取单元格的坐标,以及两个数组中的值。

标签: python arrays python-3.x numpy


【解决方案1】:

函数allclose相当于allisclose的组合。因此,您可以将isclose 应用于整个数组,然后在需要时将all 应用于某些轴,而不是循环遍历数组的某些维度。 (至关重要的是,all 采用轴参数,而 allclose 没有)。以 4D 随机数据数组为例,其中正在比较一些 2D 切片。

threshold = 0.1
arr1 = 10 + np.random.normal(size=((40, 30, 20, 10)))
arr2 = arr1 + 0.3 * np.random.normal(size=((40, 30, 20, 10)))
print(np.all(np.isclose(arr1, arr2, threshold), axis=(2, 3)))

打印一个二维数组,显示哪些切片满足allclose 条件:

array([[False,  True,  True, ...,  True,  True, False],
       [ True, False,  True, ...,  True,  True, False],
       [False,  True,  True, ..., False,  True,  True],
       ..., 
       [False, False,  True, ...,  True,  True,  True],
       [ True,  True,  True, ..., False,  True,  True],
       [ True, False,  True, ...,  True, False, False]], dtype=bool)

arr1[0, 0]arr2[0, 0]不接近;但arr1[0, 1]arr2[0, 1] 是。如有必要,您可以深入到元素级别以找出究竟是什么不符合close 条件; np.isclose(arr1, arr2, threshold) 拥有所有这些信息。

【讨论】:

    猜你喜欢
    • 2017-08-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-17
    • 1970-01-01
    • 1970-01-01
    • 2019-08-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多