[英]How to calculate distance between cluster centres of kmeans and choose the minimum in python?
我已經使用sklearn.cluster.KMeans
運行了 kmeans 算法,我將結果保存在對象kmeans_results
我可以做cl_centers = kmeans_results.cluster_centers_
以獲得聚類中心。
cl_centers
看起來像這樣:
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 之間”
“距離”是指歐幾里得距離
有沒有一種pythonic的方式來做到這一點?
您可以嘗試scipy.spatial.distance.pdist(your_array)
它為您提供點之間的距離矩陣。 然后得到你的最小距離
您的問題的解決方案由兩部分組成。
cl_centers
數組的成對距離矩陣。 因此,正如@zelenov aleksey 在第一部分所建議的那樣, scipy.spatial.distance.pdist
將計算成對距離。 然后您可以創建一個成對索引組合列表,以使用itertools.combinations
進行選擇
以下內容將為您提供您在問題中所述的理想輸出:
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)]))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.