# K-means for 2D point clustering in python

I have a set of points(2D) whose pixels are set and want to perform k-means on these pixels. Is clustering the 2D coordinates the right way ?

If so, can that be done using any libraries in python ?

It can be done very easily with the scikit-learn. Examples are easy to find on their website, i.e. here. In my opinion it is the best way to go.

Modified code example from the above link:

import numpy as np
import matplotlib.pyplot as plt

from sklearn.cluster import KMeans
from sklearn.datasets.samples_generator import make_blobs

##############################################################################
# Generate sample data
np.random.seed(0)

batch_size = 45
centers = [[1, 1], [-1, -1], [1, -1]]
n_clusters = len(centers)
X, labels_true = make_blobs(n_samples=3000, centers=centers, cluster_std=0.7)

##############################################################################
# Compute clustering with Means

k_means = KMeans(init='k-means++', n_clusters=3, n_init=10)
k_means.fit(X)
k_means_labels = k_means.labels_
k_means_cluster_centers = k_means.cluster_centers_
k_means_labels_unique = np.unique(k_means_labels)

##############################################################################
# Plot result

colors = ['#4EACC5', '#FF9C34', '#4E9A06']
plt.figure()
plt.hold(True)
for k, col in zip(range(n_clusters), colors):
my_members = k_means_labels == k
cluster_center = k_means_cluster_centers[k]
plt.plot(X[my_members, 0], X[my_members, 1], 'w',
markerfacecolor=col, marker='.')
plt.plot(cluster_center[0], cluster_center[1], 'o', markerfacecolor=col,
markeredgecolor='k', markersize=6)
plt.title('KMeans')
plt.grid(True)
plt.show()


Yielding:

• How do we give the dataset of 2D points for clustering in this function? – 1010101 May 26 '15 at 9:43
• Please check the variable X in the line no. 14. It's simply a numpy array of a shape (n_samples, n_dim). – jojek May 26 '15 at 9:47
• Can we find the values in each cluster ? i.e. the data and the correspoinding centoirds ? – 1010101 May 26 '15 at 15:56
• I suggest you to go through the code slowly, trying to debug every line. What you are trying to achieve is done in line 32 and used later in 34. – jojek May 26 '15 at 16:00