Python中的多维Eucledian距离

gar*_*rak 8 python numpy cluster-analysis scipy euclidean-distance

我想计算2个阵列之间多维度(24维)的eucledian距离.我正在使用Numpy-Scipy.

这是我的代码:

import numpy,scipy;

A=numpy.array([116.629, 7192.6, 4535.66, 279714, 176404, 443608, 295522, 1.18399e+07, 7.74233e+06, 2.85839e+08, 2.30168e+08, 5.6919e+08, 168989, 7.48866e+06, 1.45261e+06, 7.49496e+07, 2.13295e+07, 3.74361e+08, 54.5, 3349.39, 262.614, 16175.8, 3693.79, 205865]);

B=numpy.array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 151246, 6795630, 4566625, 2.0355328e+08, 1.4250515e+08, 3.2699482e+08, 95635, 4470961, 589043, 29729866, 6124073, 222.3]);
Run Code Online (Sandbox Code Playgroud)

但是,我曾经scipy.spatial.distance.cdist(A[numpy.newaxis,:],B,'euclidean')计算过核心距离.

但它给了我一个错误

raise ValueError('XB must be a 2-dimensional array.');
Run Code Online (Sandbox Code Playgroud)

我好像不明白.

我抬头scipy.spatial.distance.pdist但不明白如何使用它?

还有其他更好的方法吗?

Mic*_*ior 14

也许scipy.spatial.distance.euclidean吧?

例子

>>> from scipy.spatial import distance
>>> distance.euclidean([1, 0, 0], [0, 1, 0])
1.4142135623730951
>>> distance.euclidean([1, 1, 0], [0, 1, 0])
1.0
Run Code Online (Sandbox Code Playgroud)


YXD*_*YXD 11

使用其中之一

numpy.sqrt(numpy.sum((A - B)**2))
Run Code Online (Sandbox Code Playgroud)

或者更简单

numpy.linalg.norm(A - B)
Run Code Online (Sandbox Code Playgroud)


Ade*_* YU 7

A并且B在24-D空间中是2分.你应该用scipy.spatial.distance.euclidean.

在这里

scipy.spatial.distance.euclidean(A, B)
Run Code Online (Sandbox Code Playgroud)


Xav*_*hot 6

开始Python 3.8,您可以使用标准库的math模块及其新dist函数,该函数返回两点之间的欧几里得距离(以列表或坐标元组形式给出):

from math import dist

dist([1, 0, 0], [0, 1, 0]) # 1.4142135623730951
Run Code Online (Sandbox Code Playgroud)


Foh*_*len 5

由于上述所有答案都指的是 numpy 和/或 scipy,只是想指出,这里可以使用 reduce 来完成一些非常简单的事情

def n_dimensional_euclidean_distance(a, b):
   """
   Returns the euclidean distance for n>=2 dimensions
   :param a: tuple with integers
   :param b: tuple with integers
   :return: the euclidean distance as an integer
   """
   dimension = len(a) # notice, this will definitely throw a IndexError if len(a) != len(b)

   return sqrt(reduce(lambda i,j: i + ((a[j] - b[j]) ** 2), range(dimension), 0))
Run Code Online (Sandbox Code Playgroud)

这将对维数中所有 j 的所有对 (a[j] - b[j])^2 求和(请注意,为简单起见,这不支持 n<2 维距离)。