Generate Centriods of Kmeans in Ascending Order

Viewed 409

I am trying to use Kmean algorithm in Python using Sklearn library. My question is, that is there any way in which I can generate centriods in ascending orders. for example here is my code:

kmeanDataFrame = pd.DataFrame({'x':X,'y':Y})
kmean = KMeans(init='k-means++',n_clusters = 6,random_state=0, n_init=10)
kmean.fit(kmeanDataFrame)
print(kmean.labels_)
print(kmean.cluster_centers_)

Here X and Y are arrays, I am giving data of countries population ranking of different years. Centriods keep changing for instance when I give it 2011 it generates centriods like this:

[[ 4.22019639  2.88409457]
[ 1.15267995  0.7954897 ]
[ 2.49913831  1.64727509]
[-1.71104298 -1.54454861]
[ 6.99545873  6.08921786]
[ 0.20412018  0.0517948 ]]

and when I pass in 2012, it generates like this:

[[ 0.94596298  0.64243913]
[ 4.2710023   3.0083124 ]
[-0.27485671 -0.35197801]
[ 2.41465001  1.59198646]
[-6.514922   -4.53656495]
[ 7.77638888  7.18733868]]

Is there any way that I can generate centroids in ascending order (first negative points, then positive points) like this:

[[-1.71104298 -1.54454861],
[ 0.20412018  0.0517948 ],
[ 1.15267995  0.7954897 ],
[ 2.49913831  1.64727509],
[ 4.22019639  2.88409457],
[ 6.99545873  6.08921786]]
2 Answers

Suppose you happened to have the following clustering:

from sklearn.cluster import KMeans
np.random.seed(42)
X = np.random.rand(10000)
Y = np.random.rand(10000)
kmeanDataFrame = pd.DataFrame({'x':X,'y':Y})
kmean = KMeans(init='k-means++',n_clusters = 6,random_state=0, n_init=10)
kmean.fit(kmeanDataFrame)

cc = kmean.cluster_centers_
print(cc)

[[0.14575507 0.27937172]
 [0.76783063 0.80079467]
 [0.47849743 0.14838875]
 [0.2147012  0.79923057]
 [0.48920425 0.5285314 ]
 [0.83935504 0.27354554]]

Then you can sort either along 0th column:

idx = np.argsort(cc[:,0])
cc[idx,:]
array([[0.14575507, 0.27937172],
       [0.2147012 , 0.79923057],
       [0.47849743, 0.14838875],
       [0.48920425, 0.5285314 ],
       [0.76783063, 0.80079467],
       [0.83935504, 0.27354554]])

or 1st column:

idx = np.argsort(cc[:,1])
cc[idx,:]
array([[0.47849743, 0.14838875],
       [0.83935504, 0.27354554],
       [0.14575507, 0.27937172],
       [0.48920425, 0.5285314 ],
       [0.2147012 , 0.79923057],
       [0.76783063, 0.80079467]])

After generating means, the list of means can br sorted by using sorted funtion in python. As in below line of code

sorted_Centers=sorted (kmean.cluster_centers_)

Related