⚡0 XP🔥0

K-Means Clustering

Lesson 8 of 11 ⏱ 7 min read ✎ 2 exercises ❓ 4-question quiz ▶ Runs Python

Unsupervised learning with K-means - how the assign/update loop works, choosing K with the elbow method and silhouette score, scaling, customer segmentation, and a look at hierarchical clustering and DBSCAN.

So far every dataset had labels. Often you have data but no answers - customer purchases, website visits, sensor readings - and you want to discover natural groups. That is clustering, a form of unsupervised learning.

Uses: customer segmentation for marketing, grouping similar documents or products, image colour compression, detecting unusual behaviour (points far from every cluster).

The K-means algorithm#

  1. Choose K, the number of clusters.
  2. Place K centroids (cluster centres) - randomly, or with the smarter k-means++ start.
  3. Assign every point to its nearest centroid.
  4. Update each centroid to the mean (average position) of the points assigned to it.
  5. Repeat steps 3-4 until no point changes cluster (convergence).
InteractiveK-means step by step

Press Step to run one assign + update round and watch the square centroids move. Change K, add points by clicking, or generate new data.

हिंदी में समझें

K-means में पहले K केंद्र (centroids) रखे जाते हैं। फिर दो काम बार-बार होते हैं: (1) हर point को सबसे पास वाले केंद्र के समूह में डालो, (2) हर केंद्र को उसके समूह के points के औसत स्थान पर ले जाओ। जब कोई point समूह नहीं बदलता, तब algorithm रुक जाता है।

K-means from scratch with NumPy#

▶ Try it YourselfPython
Ctrl + Enter to run
Output
step 1: inertia   397.75  centroids [[4.3, 6.6], [2.0, 1.1], [1.6, 2.2]]
step 2: inertia   283.12  centroids [[4.4, 7.1], [1.9, 1.3], [2.0, 2.1]]
step 3: inertia   282.51  centroids [[4.4, 7.1], [1.8, 1.3], [2.1, 2.1]]
step 4: inertia   282.17  centroids [[4.4, 7.1], [1.7, 1.4], [2.2, 2.2]]
step 5: inertia   281.47  centroids [[4.4, 7.1], [1.8, 1.5], [2.3, 2.3]]
step 6: inertia   280.86  centroids [[4.4, 7.1], [1.7, 1.6], [2.6, 2.3]]
step 7: inertia   280.86  centroids [[4.4, 7.1], [1.7, 1.6], [2.6, 2.3]]
converged

Inertia (within-cluster sum of squared distances) falls at every step until the algorithm converges. But look at the result: because all three starting centroids came from the same blob, two centroids ended up sharing the bottom-left blob and one centroid sits between the other two blobs. K-means only finds a local optimum - this is exactly why scikit-learn uses the smarter k-means++ start and runs several restarts (n_init).

K-means with scikit-learn#

▶ Try it YourselfPython
Ctrl + Enter to run
Output
cluster sizes: [75 75 75 75]
centroids:
 [[ 9.52  0.53]
 [-1.31  4.54]
 [ 0.09 -8.71]
 [-8.44  5.49]]
inertia: 462.8

n_init=10 runs K-means 10 times from different starts and keeps the best result, because a bad start can get stuck in a poor solution.

Choosing K#

The elbow method#

▶ Try it YourselfPython
Ctrl + Enter to run
Output
K=1: inertia  22193.5   silhouette nan
K=2: inertia   8941.6   silhouette 0.599
K=3: inertia   2402.8   silhouette 0.776
K=4: inertia    462.8   silhouette 0.826
K=5: inertia    414.0   silhouette 0.721
K=6: inertia    370.8   silhouette 0.584
K=7: inertia    326.5   silhouette 0.456
K=8: inertia    282.6   silhouette 0.356

Inertia always decreases as K grows (with K = number of points it would be 0), so look for the elbow where the curve bends and extra clusters stop helping much - here at K = 4.

The silhouette score#

For each point, the silhouette compares how close it is to its own cluster versus the nearest other cluster. The average ranges from -1 to 1; higher is better. It peaks at K = 4 above, agreeing with the elbow.

Tip

The "right" K is also a business decision. A marketing team may want exactly 3 customer segments it can act on, even if 5 fits the data slightly better.

Scaling matters#

K-means uses distances, so features on bigger scales dominate. Income in rupees (lakhs) would swamp a 1-100 spending score. Always scale first:

▶ Try it YourselfPython
Ctrl + Enter to run
Output
raw labels   : [0 0 0 0 0 0 0 0 1 2 1 2]
scaled labels: [2 2 2 2 0 0 0 0 1 1 1 1]
segment 0: avg income Rs 500,000, avg spending 20
segment 1: avg income Rs 1,375,000, avg spending 50
segment 2: avg income Rs 487,500, avg spending 85

Without scaling, income (hundreds of thousands) completely dominates: K-means lumps all eight mid-income customers together and splits the rich ones by small income differences, ignoring spending. After scaling, it finds the three real segments - mid-income high-spenders, mid-income low-spenders and wealthy moderate spenders - which a marketing team can act on.

Beyond K-means#

Method Idea Good for
K-means centroids + means round, similar-sized clusters; fast on big data
Hierarchical (agglomerative) repeatedly merge the closest clusters; draw a dendrogram small datasets, seeing structure at every level
DBSCAN dense regions form clusters; sparse points are noise odd-shaped clusters, outlier detection, unknown K
▶ Try it YourselfPython
Ctrl + Enter to run
Output
K-means agreement with true moons: 0.234
DBSCAN  agreement with true moons: 1.0

K-means assumes round blobs and cuts the two crescent "moons" wrongly; DBSCAN follows the dense shapes.

Summary#

  • Clustering groups unlabelled data; K-means alternates assign to nearest centroid and move centroid to the mean.
  • Choose K with the elbow plot, the silhouette score and business sense; use n_init for robust results.
  • Scale features before clustering.
  • Use DBSCAN for irregular shapes and noise, hierarchical clustering to explore structure.

Practice Exercises

Write your code, then press Check. Your program is tested automatically.

1

Choose K with the silhouette score

For X from make_blobs(n_samples=300, centers=4, cluster_std=0.9, random_state=7), fit KMeans(n_clusters=k, n_init=10, random_state=0) for k = 2..7, store silhouette scores in a dict sil {k: score}, the best k in best_k, and print best_k.

2

Segment customers

Scale the customers array (annual income in lakhs, spending score 1-100) with StandardScaler, cluster it into 3 groups with KMeans(n_clusters=3, n_init=10, random_state=0), store the labels in labels, and print how many customers are in each cluster (sorted counts, e.g. [3, 4, 5]).

Quick Quiz

Q1.

K-means is an example of...

Q2.

What are the two repeated steps of K-means?

Q3.

The elbow method plots...

Q4.

A silhouette score close to 1 means...