在Numpy中,找到两个阵列中每对之间的欧几里德距离

时间:2013-07-30 00:45:55

标签: python arrays numpy scipy euclidean-distance

我有两个2D坐标点阵列(x,y)

a = [ (x1,y1), (x2,y2), ... (xN,yN) ]
b = [ (X1,Y1), (X2,Y2), ... (XN,YN) ]

如何在(xi,yi) to (Xi,Yi)数组中的每个对齐对1xN之间找到欧几里德距离?

scipy.spatial.cdist函数给出了NxN数组中所有对之间的距离。

如果我只是使用norm函数来逐个计算距离,那么它似乎很慢。

是否有内置功能来执行此操作?

2 个答案:

答案 0 :(得分:10)

我没有看到内置的,但你可以很容易地自己做。

distances = (a-b)**2
distances = distances.sum(axis=-1)
distances = np.sqrt(distances)

答案 1 :(得分:2)

hypot是另一种有效的替代方案

a, b = randn(10, 2), randn(10, 2)
ahat, bhat = (a - b).T
r = hypot(ahat, bhat)

人工计算与timeit之间hypot的结果:

手册:

timeit sqrt(((a - b) ** 2).sum(-1))
100000 loops, best of 3: 10.3 µs per loop

使用hypot

timeit hypot(ahat, bhat)
1000000 loops, best of 3: 1.3 µs per loop

现在一些成人大小的阵列怎么样:

a, b = randn(1e7, 2), randn(1e7, 2)
ahat, bhat = (a - b).T

timeit -r10 -n3 hypot(ahat, bhat)
3 loops, best of 10: 208 ms per loop

timeit -r10 -n3 sqrt(((a - b) ** 2).sum(-1))
3 loops, best of 10: 224 ms per loop

这两种方法之间没有太大的性能差异。通过避免pow

,您可以从后者中挤出更多一点
d = a - b

timeit -r10 -n3 sqrt((d * d).sum(-1))
3 loops, best of 10: 184 ms per loop