Get the closest point to the center, scikit-learn?

I use the K tool for the clustering task. I am trying to find the data point that is closest to the centroid, which I assume is called medoid.

Is there a way to do this in scikit-learn?

+3
source share
2 answers

This is not a medodea, but here you can try:

>>> import numpy as np
>>> from sklearn.cluster import KMeans
>>> from sklearn.metrics import pairwise_distances_argmin_min
>>> X = np.random.randn(10, 4)
>>> km = KMeans(n_clusters=2).fit(X)
>>> closest, _ = pairwise_distances_argmin_min(km.cluster_centers_, X)
>>> closest
array([0, 8])

The array closestcontains the index of point in X, closest to each centroid. Thus, X[0]it is the nearest point to Xto the centroid of 0, and X[8]is closest to the centroid 1.

+8
source

, . . , .

, , .

, , .

import numpy as np
from sklearn.cluster import KMeans
from sklearn.metrics import pairwise_distances_argmin_min

# assume the total number of data is 100
all_data = [ i for i in range(100) ]
tf_matrix = numpy.random.random((100, 100))

# set your own number of clusters
num_clusters = 2

m_km = KMeans(n_clusters=num_clusters)  
m_km.fit(tf_matrix)
m_clusters = m_km.labels_.tolist()

centers = np.array(m_km.cluster_centers_)

clostest_data = []
for i in range(num_clusters):
    center_vec = centers[i]
    data_idx_within_i_cluster = [ idx for idx, clu_num in enumerate(m_clusters) if clu_num == i ]

    one_cluster_tf_matrix = np.zeros( (  len(pmids_idx_in_i_cluster) , centers.shape[1] ) )
    for row_num, data_idx in enumerate(data_idx_in_i_cluster):
        one_row = tf_matrix[data_idx]
        one_cluster_tf_matrix[row_num] = one_row

    closest, _ = pairwise_distances_argmin_min(center_vec, one_cluster_tf_matrix)
    closest_idx_in_one_cluster_tf_matrix = closest[0]
    closest_data_row_num = data_idx_within_i_cluster[closest_idx_in_one_cluster_tf_matrix]
    data_id = all_data[closest_data_row_num]

    closest_data.append(data_id)

closest_data = list(set(closest_data))

assert len(closest_data) == num_clusters
0

All Articles