Data Science · Chapter 33 of 43

Clustering with K-Means

K-MEANS groups points into K clusters by iteratively assigning each point to the nearest CENTROID and updating centroids.

Unsupervised — no labels needed. Great for customer segmentation.

Example 1 (python)
from sklearn.cluster import KMeans
k = KMeans(n_clusters=3, n_init=10, random_state=42).fit(X)
print(k.labels_[:10])
Output
[0 2 1 0 1 2 0 1 2 0]

Each point gets a cluster ID.

Example 2 (python)
# Elbow method: plot inertia vs K, pick the elbow

Choosing K.

Key points

  • Unsupervised.
  • You pick K.
  • Sensitive to scale and init.
  • Elbow method helps choose K.
💡 Note: Run K-means with `n_init=10` (or more) to avoid unlucky centroid initialisations.

📝 Quick Quiz

1. K-means is:

2. K is:

3. Before K-means you should: