Search code examples
python-3.xpandasscikit-learncluster-analysisk-means

What does the ordering/index of cluster_centers_ represent in KMeans clustering SKlearn


I have implemented the following code

k_mean = KMeans(n_clusters=5,init=centroids,n_init=1,random_state=SEED).fit(X_input)
k_mean.cluster_centers_.shape
>>
(5, 50)

I have 5 clusters of the data.

How are the clusters ordered? Are the indices of the clusters centres representing the labels?

Means does the cluster_center index at 0th position represent the label = 0 or not?


Solution

  • In the docs you have a smiliar example:

    >>> from sklearn.cluster import KMeans
    >>> import numpy as np
    >>> X = np.array([[1, 2], [1, 4], [1, 0],
    ...               [10, 2], [10, 4], [10, 0]])
    >>> kmeans = KMeans(n_clusters=2, random_state=0).fit(X)
    >>> kmeans.labels_
    array([1, 1, 1, 0, 0, 0], dtype=int32)
    >>> kmeans.predict([[0, 0], [12, 3]])
    array([1, 0], dtype=int32)
    >>> kmeans.cluster_centers_
    array([[10.,  2.],
           [ 1.,  2.]])
    

    The indexes are ordered yes. Btw with k_mean.cluster_centers_.shapeyou only return the shape of your array, and not the values. So in your case you have 5 clusters, and the dimension of your features is 50.

    To get the nearest point, you can have a look here.