在python中,如何计算kmeans集群中心之间的距离并选择最小值?
我使用在python中,如何计算kmeans集群中心之间的距离并选择最小值?,python,python-3.x,Python,Python 3.x,我使用sklearn.cluster.kmeans运行了一个kmeans算法,我将结果保存在对象kmeans\u results 我可以执行cl\u centers=kmeans\u results.cluster\u centers\uu以获得聚类中心 cl_中心如下所示: array([[0.69332691, 0.9118433 , 0.14215727, 0.00903798], [0.41407049, 0.95964501, 0.19565154, 0.03157038
sklearn.cluster.kmeans
运行了一个kmeans算法,我将结果保存在对象kmeans\u results
我可以执行cl\u centers=kmeans\u results.cluster\u centers\uu
以获得聚类中心
cl_中心
如下所示:
array([[0.69332691, 0.9118433 , 0.14215727, 0.00903798],
[0.41407049, 0.95964501, 0.19565154, 0.03157038],
[0.88239715, 0.65602688, 0.20304053, 0.01066663],
[0.65413307, 0.92372214, 0.36504241, 0.03482278]])
我想计算这4个点之间的距离,并选择最小的一个,以及它们的“标签”(其中标签只是数组索引)
理想的输出是:
最小距离为x,出现在群集0和群集3之间
“距离”是指欧几里得距离
有没有类似python的方法呢?你可以试试scipy.space.distance.pdist(你的数组),它会给出点之间的距离矩阵。然后获取您的最小距离您可以尝试
scipy.spatial.distance.pdist(您的_数组)
,它提供点之间的距离矩阵。然后获得最小距离问题的解决方案由两部分组成
cl\u中心
阵列的成对距离矩阵import numpy as np
from scipy.spatial.distance import pdist
import itertools as it
centers_arr = np.array([[0.69332691, 0.9118433 , 0.14215727, 0.00903798],
[0.41407049, 0.95964501, 0.19565154, 0.03157038],
[0.88239715, 0.65602688, 0.20304053, 0.01066663],
[0.65413307, 0.92372214, 0.36504241, 0.03482278]])
pairs = list(it.combinations(range(4),2))
d = pdist(centers_arr)
print("The smallest distance is {:}, and it occurs between cluster {:} and cluster {:}".format(d.min(), *pairs[d.argmin(axis=0)]))
问题的解决方案由两部分组成
cl\u中心
阵列的成对距离矩阵import numpy as np
from scipy.spatial.distance import pdist
import itertools as it
centers_arr = np.array([[0.69332691, 0.9118433 , 0.14215727, 0.00903798],
[0.41407049, 0.95964501, 0.19565154, 0.03157038],
[0.88239715, 0.65602688, 0.20304053, 0.01066663],
[0.65413307, 0.92372214, 0.36504241, 0.03482278]])
pairs = list(it.combinations(range(4),2))
d = pdist(centers_arr)
print("The smallest distance is {:}, and it occurs between cluster {:} and cluster {:}".format(d.min(), *pairs[d.argmin(axis=0)]))
当你说“pythonic”时,就像我的一样,一个一行程序?不使用for loopHi,你可以尝试
scipy.space.distance.pdist(你的数组)
,它给出了你之间的距离矩阵points@zelenovaleksey您可以将其作为答案发布:)@quant done,如果有帮助,请将其标记为答案:)当您说“pythonic”你在我的单行程序中有什么?不使用for loopHi,你可以尝试scipy.spatial.distance.pdist(你的数组)
,它提供你之间的距离矩阵points@zelenovaleksey您可以将其作为答案发布:)@quant done,如果有帮助,请将其标记为答案:)