我想2个阵列之间,以计算在多个维度的欧几里得距离(24种尺寸)。我使用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]);
但是,我用qazxsw POI计算欧几里得距离。
但它给了我一个错误
scipy.spatial.distance.cdist(A[numpy.newaxis,:],B,'euclidean')
我似乎并不了解它。
我抬头raise ValueError('XB must be a 2-dimensional array.');
,但不知道如何使用它?
是否有其他更好的方式来做到这一点?
也许scipy.spatial.distance.pdist
?
例子
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
或者更简单
numpy.sqrt(numpy.sum((A - B)**2))
除了计算的欧氏距离的已经提到的方式,这里有一个很接近你原来的代码:
scipy.spatial.distance.euclidean(A, B)
要么
scipy.spatial.distance.cdist([A], [B], 'euclidean')
这将返回一个1×1 scipy.spatial.distance.cdist(np.atleast_2d(A), np.atleast_2d(B), 'euclidean')
保持L2距离。
由于上述所有答案指numpy的和或SciPy的,只是想指出的是非常简单的东西可以减少在这里完成
np.ndarray
这将总结所有对(一个[J] - B [j])的^ 2为在维数所有的j(请注意,为了简单起见,这并不支持无<2维的距离)。
开始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))
,你可以使用标准库的Python 3.8
模块和新math
函数,返回两个点之间的欧氏距离(给出列表或坐标元组):
dist