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#
- Choose K, the number of clusters.
- Place K centroids (cluster centres) - randomly, or with the smarter k-means++ start.
- Assign every point to its nearest centroid.
- Update each centroid to the mean (average position) of the points assigned to it.
- Repeat steps 3-4 until no point changes cluster (convergence).
K-means में पहले K केंद्र (centroids) रखे जाते हैं। फिर दो काम बार-बार होते हैं: (1) हर point को सबसे पास वाले केंद्र के समूह में डालो, (2) हर केंद्र को उसके समूह के points के औसत स्थान पर ले जाओ। जब कोई point समूह नहीं बदलता, तब algorithm रुक जाता है।
K-means from scratch with NumPy#
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#
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#
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.
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:
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 |
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_initfor robust results. - Scale features before clustering.
- Use DBSCAN for irregular shapes and noise, hierarchical clustering to explore structure.