慢行比较与NumPy中的Forloops如何改进?

2024-10-02 20:35:23 发布

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

我使用pythonnumpy来比较两个数组或相等形状的坐标(x,y,z),以便匹配它们,如下所示:

coordsCFS
array([[ 0.02      ,  0.02      ,  0.        ],
       [ 0.03      ,  0.02      ,  0.        ],
       [ 0.02      ,  0.025     ,  0.        ],
        ..., 
       [ 0.02958333,  0.029375  ,  0.        ],
       [ 0.02958333,  0.0290625 ,  0.        ],
       [ 0.02958333,  0.0296875 ,  0.        ]])

以及

^{pr2}$

使用h5py从两个hdf5文件读取数据。 为了进行比较,我使用allclose,它测试“几乎相等”。坐标在python的常规浮点精度内不匹配。这就是我使用for循环的原因,否则它将使用numpy.where。我通常试图避免for循环,但在这种情况下,我不知道如何避免。所以我想出了一个非常慢的片段:

mapList = []
for cfsXYZ in coordsCFS:
    # print cfsXYZ
    indexMatch = 0
    match = []
    for asterXYZ in coordRMED:
        if numpy.allclose(asterXYZ,cfsXYZ):
            match.append(indexMatch)
            # print "Found match at index " + str(indexMatch)
            # print asterXYZ
        indexMatch += 1

    # check: must only find one match. 
    if len(match) != 1:
        print "ERROR matching"
        print match
        print cfsXYZ
        return 1

    # save to list
    mapList.append(match[0])

if len(mapList) != coordsRMED.shape[0]:
    print "ERROR: matching consistency check"
    print mapList
    return 1

这对于我的测试样本大小(800行)来说非常慢。我打算比较大一点的。我可以删除一致性检查,并在内部for循环中使用break,以提高速度。还有更好的方法吗?在


Tags: innumpyforlenifcheckmatchprint
3条回答

你可以用这样的方法去掉内部循环:

for cfsXYZ in coordsCFS:
    match = numpy.nonzero(
        numpy.max(numpy.abs(coordRMED - cfsXYZ), axis=1) < TOLERANCE)

首先要记住的是,默认情况下,在NumPy中,“迭代总是以C风格的连续方式进行(最后一个索引变化最快)”[1]。您可以通过颠倒迭代顺序(迭代coordMED.TcoordMED的转置…)来改进事情

然而,我仍然对您需要一个循环感到惊讶:您声称“坐标在python的常规浮点精度内不匹配”:您是否尝试调整rtol和{}参数,如其doc所述?在

[1]

一种解决方案是对两个数组进行排序(添加一个索引列,以便排序后的数组仍然包含原始索引)。然后,为了匹配,在lock step中逐步遍历数组。由于您希望得到精确的1-1对应关系,所以您应该始终能够匹配出成对的行。在

相关问题 更多 >