使用numpy矩阵计算距离的Python方法?
我有一个使用numpy矩阵计算距离的Python方法?,python,numpy,Python,Numpy,我有一个numpy矩阵中的点列表 A = [[x11,x12,x13],[x21,x22,x23] ] 我有一个点原点o=[o1,o2,o3],从这里我必须计算每个点的距离 A-o将从每个点减去o。目前我必须做每个属性的平方运算和加法运算,我在for循环中进行。有没有更直观的方法 附言:我作为kmeans集群应用程序的端口进行上述计算。我已经计算了质心,现在我必须计算每个点到质心的距离 input_mat = input_data_per_minute.values[:,2:5] scale
numpy
矩阵中的点列表
A = [[x11,x12,x13],[x21,x22,x23] ]
我有一个点原点o=[o1,o2,o3]
,从这里我必须计算每个点的距离
A-o
将从每个点减去o
。目前我必须做每个属性的平方运算和加法运算,我在for循环中进行。有没有更直观的方法
附言:我作为kmeans集群应用程序的端口进行上述计算。我已经计算了质心,现在我必须计算每个点到质心的距离
input_mat = input_data_per_minute.values[:,2:5]
scaled_input_mat = scale2(input_mat)
k_means = cluster.KMeans(n_clusters=5)
print 'training start'
k_means.fit(scaled_input_mat)
print 'training over'
out = k_means.cluster_centers_
我必须计算
input\u mat
和每个簇质心之间的距离。您应该能够这样做:(假设我正确阅读了您的问题;)
input_mat = input_data_per_minute.values[:,2:5]
scaled_input_mat = scale2(input_mat)
k_means = cluster.KMeans(n_clusters=5)
print 'training start'
k_means.fit(scaled_input_mat)
print 'training over'
out = k_means.cluster_centers_
Numpy是伟大的,因为它在数组元素中移动!这意味着90%以上的时间可以在不使用for循环的情况下迭代数组。在阵列外部使用for循环也会大大降低速度。Numpy解决方案:
Numpy是伟大的广播,所以你可以欺骗它做所有的距离在一步。但它将消耗大量内存,具体取决于点和集群中心的数量。事实上,它将创建一个number\u of_points*number\u of_cluster\u centers*3
数组:
首先,你需要了解一些关于广播的知识,我将自己播放,并手工定义每个维度
为了便于演示,我将首先定义一些点和中心:
import numpy as np
points = np.array([[1,1,1],
[2,1,1],
[1,2,1],
[5,5,5]])
centers = np.array([[1.5, 1.5, 1],
[5,5,5]])
现在,我将准备这些阵列,以便使用numpy广播获得每个维度的距离:
distance_3d = points[:,None,:] - centers[None,:,:]
实际上,第一个维度现在是点“标签”,第二个维度是中心“标签”,第三个维度是坐标。减法就是得到每个维度的距离。结果将具有以下形状:
(number_of_points, number_of_cluster_centers, 3)
现在只需要应用欧几里德距离公式:
# Square each distance
distance_3d_squared = distance_3d ** 2
# Take the sum of each coordinates distance (the result will be 2D)
distance_sum = np.sum(distance_3d_squared, axis=2)
# And take the square root
distance = np.sqrt(distance_sum)
对于我的测试数据,最终结果是:
#array([[ 0.70710678, 6.92820323],
# [ 0.70710678, 6.40312424],
# [ 0.70710678, 6.40312424],
# [ 6.36396103, 0. ]])
因此距离[i,j]
元素将给出点i
到中心j
的距离
总结:
您可以将所有这些放在一行中:
distance2 = np.sqrt(np.sum((points[:,None,:] - centers[None,:,:]) ** 2, axis=2))
Scipy解决方案(更快、更短):
或者,如果您有scipy,请使用:
结果总是一样的,但是对于许多点和中心来说,
cdist
是最快的。从scipy
查看cdist
。
from scipy.spatial.distance import cdist
distance3 = cdist(points, centers)