Last updated

K-Means Clustering

Definition: Clustering is unsupervised learning — there are no labels. K-Means automatically groups data into K clusters of similar points. The model discovers the groups for you.

Example — find two groups

These points clearly form two clusters — a low group and a high group. K-Means finds them on its own:

from sklearn.cluster import KMeans
import numpy as np

X = np.array([[1,1],[1,2],[2,1],[8,8],[9,8],[8,9]])

model = KMeans(n_clusters=2, n_init=10, random_state=1)
groups = model.fit_predict(X)

for point, g in zip(X.tolist(), groups):
    print(point, "-> cluster", g)

Where clustering is used

  • Customer segmentation for marketing
  • Grouping similar documents or images
  • Detecting unusual activity (points that fit no cluster)

💡 Key difference: in classification you tell the model the categories; in clustering the model finds them without being told.

Try it Yourself
Output

          
Ad · responsive