如何使用sklearn找到最接近K均值聚类中心的点的索引?

How to find the index of the point closest to K means cluster centers using sklearn?

我已经使用 python 的 sklearn 包进行 K 均值聚类。到目前为止,我可以使用以下代码获取聚类中心的坐标。

import numpy as np
from sklearn.cluster import KMeans

p50 = np.load('tsnep400.npy')
kmeans = KMeans(n_clusters=50).fit(p50) 
np.savetxt('kmeans_50clusters_centers_tsnep400', kmeans.cluster_centers_, fmt='%1.3f')
np.savetxt('kmeans_50clusters_tsnep400.dat', kmeans.labels_, fmt='%1.1d')

centroids = {i: np.where(kmeans.labels_ == i)[0] for i in range(kmeans.n_clusters)}
np.save('kmeans_50clusters_memebers_tsnep400.npy',centroids)

如何找到距离聚类中心最近的点的索引?

根据 scikit-learn 文档,属性 .labels_ 包含每个点的标签,按它们的索引。因此,您可以使用它将每个点分组到一个集群中,然后计算到每个集群中心的距离。您可以为此使用以下代码:

from scipy.spatial.distance import euclidean

# Loop over all clusters and find index of closest point to the cluster center and append to closest_pt_idx list.
closest_pt_idx = []
for iclust in range(kmeans.n_clusters):
    # get all points assigned to each cluster:
    cluster_pts = p50[kmeans.labels_ == iclust]
    # get all indices of points assigned to this cluster:
    cluster_pts_indices = np.where(kmeans.labels_ == iclust)[0]

    cluster_cen = kmeans.cluster_centers_[iclust]
    min_idx = np.argmin([euclidean(p50[idx], cluster_cen) for idx in cluster_pts_indices])
    
    # Testing:    
    print('closest point to cluster center: ', cluster_pts[min_idx])
    print('closest index of point to cluster center: ', cluster_pts_indices[min_idx])
    print('  ', p50[cluster_pts_indices[min_idx]])
    closest_pt_idx.append(cluster_pts_indices[min_idx])