gpt4 book ai didi

使用 numpy 矩阵计算距离的 Pythonic 方法?

转载 作者:太空宇宙 更新时间:2023-11-03 10:59:23 24 4
gpt4 key购买 nike

我有一个 numpy 矩阵中的点列表,

A = [[x11,x12,x13],[x21,x22,x23] ]

我有一个点原点 o= [o1,o2,o3] 我必须计算每个点的距离,

A - o 将从每个点中减去 o。目前我必须对每个属性进行平方和加法运算,我在 for 循环中进行。有没有更直观的方法来做到这一点?

P.S:我正在将上述计算作为 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_mat 和每个簇质心之间的距离。

最佳答案

Numpy 解决方案:

Numpy 非常适合广播,因此您可以欺骗它一步完成所有距离。但它会根据点数和聚类中心的数量消耗大量内存。事实上,它会创建一个 number_of_points * number_of_cluster_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. ]])

因此 distance[i, j] 元素将为您提供点 i 到中心 j 的距离。

总结:

您可以将所有这些放在一行中:

distance2 = np.sqrt(np.sum((points[:,None,:] - centers[None,:,:]) ** 2, axis=2))

Scipy 解决方案(更快更短):

或者如果你有 scipy 使用 cdist :

from scipy.spatial.distance import cdist
distance3 = cdist(points, centers)

结果总是相同的,但是 cdist 对于很多点和中心来说是最快的。

关于使用 numpy 矩阵计算距离的 Pythonic 方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35955293/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com