行向量矩阵之间的python numpy欧几里德距离计算

时间:2010-12-06 21:08:31

标签: python vector numpy scipy euclidean-distance

我是Numpy的新手,我想问你如何计算矢量中存储的点之间的欧氏距离。

让我们假设我们有一个numpy.array,每一行都是一个向量和一个numpy.array。我想知道是否可以计算所有点和这一点之间的欧氏距离,并将它们存储在一个numpy.array中。

这是一个界面:

points #2d list of row-vectors
singlePoint #one row-vector

listOfDistances= procedure( points,singlePoint)

我们能有这样的事吗? 或者是否可以使用一个命令将单个点作为其他点的列表,最后我们得到一个距离矩阵?

由于

4 个答案:

答案 0 :(得分:16)

虽然你可以使用矢量化,但是对于numpy数组,@ Karl的方法会相当慢。

更简单的方法就是np.hypot(*(points - single_point).T)。 (转置假定点是Nx2数组,而不是2xN。如果它是2xN,则不需要.T

然而,这有点难以辨认,所以你更明确地写出来(使用一些固定的示例数据......):

import numpy as np
single_point = [3, 4]
points = np.arange(20).reshape((10,2))

dist = (points - single_point)**2
dist = np.sum(dist, axis=1)
dist = np.sqrt(dist)

答案 1 :(得分:5)

import numpy as np
def distance(v1, v2):
    return np.sqrt(np.sum((v1 - v2) ** 2))    

答案 2 :(得分:2)

要将函数应用于numpy数组的每个元素,请尝试numpy.vectorize

要进行实际计算,我们需要两个向量中坐标对之间差异平方和的平方根(哇!)。

我们可以使用zip配对坐标,并使用sum进行理解以总结结果。看起来像是:

sum((x - y) ** 2 for (x, y) in zip(singlePoint, pointFromArray)) ** 0.5

答案 3 :(得分:0)

import numpy as np
single_point = [3, 4]
points = np.arange(20).reshape((10,2))   
distance = euclid_dist(single_point,points)

def euclid_dist(t1, t2):
    return np.sqrt(((t1-t2)**2).sum(axis = 1))