How can i make invisible the clusters without cluster centroid in python?

Viewed 87

I have a kmeans clustered object with 15 clusters. I rearranged the cluster_centers of the object and removed 5 specific cluster centers form that list. Now i want to visiulize my object and cluster centers. But i couldn't find a way to make some clusters invisible.

My originally clustered data is :

enter image description here

When i try to visualize my kmeans data object with its new cluster centroids i get this output: enter image description here

I want to make invisible the clusters without "X" markers on it. How can i do that?

I used this code to plot the above:

plt.scatter(X_train[:,0], X_train[:,1],c=TrainData[1],cmap='gist_rainbow')
plt.scatter(new_centroids[:,0], new_centroids[:, 1],s = 150, c = 'black', label = 'Centroid', marker="x")
plt.show()
1 Answers

You can build a filter to exclude the undesired values. You need to convert your TrainData[1] to a numpy array (if it isn't already), using np.array(TrainData[1]).

Here is an example using sklearns KMeans:


import matplotlib.pyplot as plt
from sklearn.cluster import KMeans
import numpy as np

X_train = np.random.normal(size=(5000, 2))
kmeans_result = KMeans(n_clusters=15).fit(X_train)
new_centroids = kmeans_result.cluster_centers_
cluster_ids = kmeans_result.labels_
# cluster_ids = np.array(TrainData[1])

undesired1 = 3
undesired2 = 5
undesired3 = 7
filter = (cluster_ids != undesired1) & (cluster_ids != undesired2) & (cluster_ids != undesired3)
plt.scatter(X_train[filter, 0], X_train[filter, 1], c=cluster_ids[filter], cmap='gist_rainbow', alpha=0.4)
desired_centroid_ids = np.array([i for i in range(len(new_centroids)) if i not in [undesired1, undesired2, undesired3]])
plt.scatter(new_centroids[desired_centroid_ids, 0], new_centroids[desired_centroid_ids, 1], s=150, c='black',
            label='Centroid', marker="x")
plt.show()

example plot

Related