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

Viewed 936

I have used python's sklearn package for K-means clustering. So far I am able to get the coordinates of the cluster centers using the following code.

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)

How do I find the index of the point closest to cluster centers?

1 Answers

According to the scikit-learn documentation, the attribute .labels_ contains the labels of each point, by their index. Thus, you can use this to group each of your points into a cluster and then calculate the distance to each cluster center. You can use the following code for this:

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])
Related