在python中给定阈值时有效删除彼此接近的数组

Pj-*_*Pj- 5 python numpy distance duplicates

我使用 python 来完成这项工作,并且在这里非常客观,我想找到一种“pythonic”方法来从数组数组中删除距离阈值彼此接近的“重复项”。例如,给出这个数组:

[[ 5.024,  1.559,  0.281], [ 6.198,  4.827,  1.653], [ 6.199,  4.828,  1.653]]
Run Code Online (Sandbox Code Playgroud)

观察[ 6.198, 4.827, 1.653][ 6.199, 4.828, 1.653]彼此非常接近,它们的欧几里德距离是0.0014,所以它们几乎是“重复的”,我希望我的最终输出只是:

[[ 5.024,  1.559,  0.281], [ 6.198,  4.827,  1.653]]
Run Code Online (Sandbox Code Playgroud)

我现在拥有的算法是:

to_delete = [];
for i in unique_cluster_centers:
    for ii in unique_cluster_centers:
        if i == ii:
            pass;
        elif np.linalg.norm(np.array(i) - np.array(ii)) <= self.tolerance:
            to_delete.append(ii);
            break;

for i in to_delete:
    try:
        uniques.remove(i);
    except:
        pass;
Run Code Online (Sandbox Code Playgroud)

但它真的很慢,我想知道一些更快和“Pythonic”的方法来解决这个问题。我的公差是0.0001。

Wil*_*sem 2

通用方法可能是:

def filter_quadratic(data,condition):
    result = []
    for element in data:
        if all(condition(element,other) for other in result):
            result.append(element)
    return result
Run Code Online (Sandbox Code Playgroud)

filter这是一个有条件的通用高阶。仅当列表*中已存在的所有元素都满足条件时,才会添加该元素。

现在我们仍然需要定义条件

def the_condition(xs,ys):
    # working with squares, 2.5e-05 is 0.005*0.005 
    return sum((x-y)*(x-y) for x,y in zip(xs,ys)) > 2.5e-05
Run Code Online (Sandbox Code Playgroud)

这给出:

>>> filter_quadratic([[ 5.024,  1.559,  0.281], [ 6.198,  4.827,  1.653], [ 6.199,  4.828,  1.653]],the_condition)
[[5.024, 1.559, 0.281], [6.198, 4.827, 1.653]]
Run Code Online (Sandbox Code Playgroud)

该算法的运行时间为O(n 2 ),其中n是您赋予函数的元素数量。然而,您可以使用k -d 树使其更加高效,但这需要一些更高级的数据结构。