How to set k-Means clustering labels from highest to lowest with Python?
Transforming the labels through a lookup table is a straightforward way to achieve what you want.
To begin with I generate some mock data:
import numpy as np
np.random.seed(1000)
n = 38
X_morning = np.random.uniform(low=.02, high=.18, size=38)
X_afternoon = np.random.uniform(low=.05, high=.20, size=38)
X_night = np.random.uniform(low=.025, high=.175, size=38)
X = np.vstack([X_morning, X_afternoon, X_night]).T
Then I perform clustering on data:
from sklearn.cluster import KMeans
k = 4
kmeans = KMeans(n_clusters=k, random_state=0).fit(X)
And finally I use NumPy's argsort
to create a lookup table like this:
idx = np.argsort(kmeans.cluster_centers_.sum(axis=1))
lut = np.zeros_like(idx)
lut[idx] = np.arange(k)
Sample run:
In [70]: kmeans.cluster_centers_.sum(axis=1)
Out[70]: array([ 0.3214523 , 0.40877735, 0.26911353, 0.25234873])
In [71]: idx
Out[71]: array([3, 2, 0, 1], dtype=int64)
In [72]: lut
Out[72]: array([2, 3, 1, 0], dtype=int64)
In [73]: kmeans.labels_
Out[73]: array([1, 3, 1, ..., 0, 1, 0])
In [74]: lut[kmeans.labels_]
Out[74]: array([3, 0, 3, ..., 2, 3, 2], dtype=int64)
idx
shows the cluster center labels ordered from lowest to highest consumption level. The appartments for which lut[kmeans.labels_]
is 0
/ 3
belong to the cluster with the lowest / highest consumption levels.