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0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0],
 [1 ,0 ,1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
 [0 ,0 ,0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 1, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 1, 0, 0, 0, 0]] 

i used KMeans algorithm from scikitlearn to form clusters but i need a way to visualize these clusters. here my code for k-means

cl= KMeans(n_clusters=4)
cl.fit(d)
cen = cl.cluster_centers_
lab=cl.labels_

i know how to use matplot to plot simple graph but i never used to Multidimensional. i want to plot d and then cluster_centers (centroids) plot should be something like this enter image description here is there any hit may help me accomplish this task?

Upvotes: 0

Views: 541

Answers (1)

Ilya V. Schurov
Ilya V. Schurov

Reputation: 8047

As @Mahdi said, you have to use some dimensionality reduction to be able to plot the points from high-dimensional space on two-dimensional screen. (Of course, you will loose some information, but that's unavoidable.) Here is an example to how to do it with PCA (however, there are different techniques, check the references above).

from sklearn.decomposition import PCA
from sklearn.cluster import KMeans
import matplotlib.pyplot as plt
%matplotlib inline

# d = ... (the same as in the question)

n_clusters = 4
cl= KMeans(n_clusters=n_clusters)
cl.fit(d)
cen = cl.cluster_centers_
lab=cl.labels_

pca = PCA(2)
# reduce dimension to 2

coords = pca.fit_transform(d)

plt.scatter(coords[:, 0], coords[:, 1], 20, c=lab, cmap='spring')
centroids_transformed = pca.transform(cen)
# transform centroids coordinate to new space

plt.scatter(centroids_transformed[:, 0], centroids_transformed[:, 1], 60,
            c=range(n_clusters), cmap='spring', marker='v')
# plot centroids. they are presented in the same order as labels,
# so colors are just range

enter image description here

Upvotes: 2

Related Questions