简体   繁体   English

Python - 计算两个点列表(坐标)的最小欧氏距离

[英]Python - calculate minimum euclidean distance of two lists of points (coordinates)

I have two lists of n shape and each point will be compared(euclidean distance) to each point of the second list and then the minimum distance will be chosen, example:我有两个 n 形状的列表,每个点将与第二个列表的每个点进行比较(欧氏距离),然后选择最小距离,例如:

A: [(1,1),(2,1),(3,1)]答:[(1,1),(2,1),(3,1)]

B: [(2,2),(3,3)]乙:[(2,2),(3,3)]

The output will be 3 distances:输出将是 3 个距离:

min((1,1) -> (2,2), (1,1) -> (3,3)), min((1,1) -> (2,2), (1,1) -> (3,3)),

min( (2,1) -> (2,2), (2,1) -> (3,3) ), min( (2,1) -> (2,2), (2,1) -> (3,3) ),

min ( (3,1) -> (2,2), (3,1) -> (3,3) )分钟 ( (3,1) -> (2,2), (3,1) -> (3,3) )

-> euclidean distance -> 欧氏距离

The difficult part is to make an efficient code.困难的部分是编写有效的代码。

Here is a sample code that may help:这是一个可能有帮助的示例代码:

from scipy.spatial import distance

A = [(1,1),(2,1),(3,1)]
B = [(2,2),(3,3)]

min_dist = []
for a in A:
    dist = []
    for b in B:
        dist.append(distance.euclidean(a,b))
    min_dist.append(min(dist))

>> min_dist
>> [1.4142135623730951, 1.0, 1.4142135623730951]

I am using scipy library for this.我为此使用了scipy库。 It is also possible using numpy.linalg.norm .也可以使用numpy.linalg.norm Does this approach work for you?这种方法对你有用吗?

HTH.哈。

I found a way, I don't know if someone can make it more efficiently,我找到了一个方法,不知道有没有人可以更有效地,

import numpy as np
from scipy.spatial import distance

s1 = np.array([(0,0), (0,1), (1,0), (1,1)])
s2 = np.array([(3,2), (1,9)])
print(distance.cdist(s1,s2).min(axis=1))
# array([3.60555128, 3.16227766, 2.82842712, 2.23606798]) 

Depends on what you mean by "efficient."取决于你所说的“高效”是什么意思。 If you have sizable lists and you are going to be doing a lot of comparisons, you should just look for the minimum squared distance, which is much faster to compute because you avoid the square root operation.如果您有相当大的列表并且要进行大量比较,则应该只查找最小平方距离,由于避免了平方根运算,因此计算速度要快得多。 This is a standard hack when working with euclidean distances.这是使用欧几里得距离时的标准技巧。

If in the end, you want the actual euclidean distance, then take the square root.如果最后,您想要实际的欧几里得距离,取平方根。

Consider:考虑:

import numpy as np

A = [(1, 1), (2, 1), (3, 1)]
B = [(2, 2), (3, 3)]

# compare each point in A to all points in B, return the shortest distance

for pt in A:
    min_sq_dist = min( (pt[0] - t[0])**2 + (pt[1] - t[1])**2 for t in B )
    print(np.sqrt(min_sq_dist))

Output:输出:

1.4142135623730951
1.0
1.4142135623730951

What's the big difference?有什么大的区别? The code above computes 3 square roots.上面的代码计算了 3 个平方根。 The naive approach computes 6 (|{B}| times as many)天真的方法计算 6(|{B}| 倍)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM