text_plain_output_1.png
from pandas import crosstab

from pyclustering.cluster.kmeans import kmeans

from pyclustering.cluster.kmedians import kmedians

from sklearn.datasets import load_iris

from sklearn.decomposition import PCA

from sklearn.metrics import adjusted_rand_score

import numpy as np

iris = load_iris()
X = iris['data']
y = iris['target']
pca = PCA(n_components=2)
X_pca = pca.fit_transform(X)
X_scaled = X_pca
ax = plt.axes()
cor = ['blue', 'red', 'green']
for i in range(3):
    idx = np.where(y == i)
ax.set_aspect('equal')
ax.set(title='Ground-truth')

kmeans_instance = kmeans(X_scaled, initial_centers)
kmeans_instance.process()
centroids = np.array(kmeans_instance.get_centers())
kmeans_clusters = kmeans_instance.get_clusters()
kmeans_labels = np.zeros([X.shape[0]], dtype='int64')
ax = plt.axes()
for i in range(3):
    kmeans_labels[kmeans_clusters[i]] = i
ax.set_aspect('equal')
ax.set(title='K-means clustering')
y_kmeans = np.zeros(150)
for i in range(3):
    y_kmeans[kmeans_clusters[i]] = i

kmedians_instance = kmedians(X_scaled, initial_centers)
kmedians_instance.process()
medians = np.array(kmedians_instance.get_medians())
kmedians_clusters = kmedians_instance.get_clusters()
kmedians_labels = np.zeros([X.shape[0]], dtype='int64')
plt.figure()
ax = plt.axes()
for i in range(3):
    kmedians_labels[kmeans_clusters[i]] = i
    ax.scatter(X_scaled[kmedians_clusters[i], 0], X_scaled[kmedians_clusters[i], 1], color=cor[i], alpha=0.5, zorder=2)
ax.scatter(medians[:, 0], medians[:, 1], c='k', marker='*', zorder=3)
ax.set_aspect('equal')
ax.grid(visible=True, zorder=1)
ax.set(title='K-medians clustering')
y_kmedians = np.zeros(150)
for i in range(3):
    y_kmedians[kmedians_clusters[i]] = i
crosstab(y, y_kmedians)
print(crosstab(y, y_kmedians))
print('ARI={ars:.2f}'.format(ars=adjusted_rand_score(y, kmedians_labels)))