K means permute clusters

Viewed 998

With the following code from a book I am clustering the digits dataset. Because the K means algorithm can find the clusters but has no knowledge about which cluster is for example a "0" or a "9" we must Match each learned cluster label with the true labels found in them.

digits=load_digits()
X=digits.data
y=digits.target

#Instantiate the k_means estimator and set the hyerparameters
model=KMeans(n_clusters=10,random_state=0)
model.fit(X)
y_pred=model.predict(X)

#Match each learned cluster label with the true labels found in them
from scipy.stats import mode

labels=np.zeros_like(y_pred)
for i in range(10):
    mask=(y_pred==i)
    labels[mask]=mode(digits.target[mask])[0]

conf=confusion_matrix(y,labels)

I understand all of the code except the part:

        labels[mask]=mode(digits.target[mask])[0] 

Can anybody please explain this to me?

1 Answers
Related