Reading history

K-Means Clustering in Python: Elbow Method and Silhouette

4 min read 2 views

Learn k-means clustering in Python: how the algorithm works, clustering with scikit-learn, choosing k with the elbow method and silhouette score.

So far every model has learned from labelled examples. Often, though, you have data with no labels at all, such as thousands of customers, and want to find natural groups in it. That is unsupervised learning, and k-means is its most popular clustering algorithm. It splits the data into k groups so that points in the same group sit close to their group’s centre.

In this lesson you will learn

  • How the k-means algorithm works step by step
  • Clustering data with scikit-learn’s KMeans
  • Assigning new points to clusters
  • Choosing k with the elbow method and silhouette score
  • Limitations of k-means

How K-Means Works

  1. Pick k starting centres (centroids). scikit-learn uses a smart random start called k-means++.
  2. Assign every point to its nearest centre.
  3. Move each centre to the average position of the points assigned to it.
  4. Repeat steps 2 and 3 until the assignments stop changing.

The algorithm tries to make the total squared distance from points to their centres, called inertia, as small as possible. Because the result depends on the starting centres, n_init=10 runs it 10 times and keeps the best.

Clustering Customers

import numpy as np
from sklearn.cluster import KMeans
from sklearn.datasets import make_blobs

# 300 customers described by two features, in 3 hidden groups
X, _ = make_blobs(n_samples=300, centers=3, cluster_std=1.0, random_state=42)

kmeans = KMeans(n_clusters=3, n_init=10, random_state=42)
labels = kmeans.fit_predict(X)

print("Points per cluster:", np.bincount(labels))
print("Cluster centres:")
print(kmeans.cluster_centers_.round(2))
print("New point [0, 5] goes to cluster", kmeans.predict([[0, 5]])[0])

Output

Points per cluster: [100 100 100]
Cluster centres:
[[-2.63  9.04]
 [-6.88 -6.98]
 [ 4.75  2.01]]
New point [0, 5] goes to cluster 0
  • make_blobs creates test data with 3 hidden groups. In real projects the features might be yearly spending and visits per month, scaled first with StandardScaler because k-means uses distances.
  • fit_predict returns a cluster number for each point. The numbers are just names: cluster 0 is not “first” or “best”.
  • cluster_centers_ describes each group by its average features, which is how you give clusters meaningful names such as “frequent low spenders”.
  • predict assigns a new point to the nearest centre.

Choosing the Number of Clusters

from sklearn.cluster import KMeans
from sklearn.datasets import make_blobs
from sklearn.metrics import silhouette_score

X, _ = make_blobs(n_samples=300, centers=4, cluster_std=0.9, random_state=7)

for k in range(2, 8):
    km = KMeans(n_clusters=k, n_init=10, random_state=0).fit(X)
    print(f"k = {k}: inertia {km.inertia_:8.1f}   silhouette {silhouette_score(X, km.labels_):.3f}")

Output

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
  • Elbow method: inertia always falls as k grows, so look for the “elbow” where it stops falling steeply. Here the drop from k = 3 to 4 is large (2,403 to 463) and after that it is small, so the elbow is at 4.
  • Silhouette score (from −1 to 1) measures how much closer each point is to its own cluster than to the next one. Higher is better, and it peaks at k = 4, agreeing with the elbow.
  • The data was generated with 4 centres, so both methods found the truth. With real data, also ask whether the clusters are useful for the business question.

Limitations

LimitationAlternative
You must choose k in advanceDBSCAN or hierarchical clustering
Assumes round, similarly sized clustersGaussian mixture models, DBSCAN
Sensitive to outliers and feature scaleScale first; remove extreme outliers
Needs numeric featuresOne-hot encode, or use k-prototypes for mixed data

Where K-Means Is Used

  • Customer segmentation for marketing
  • Grouping similar documents or products
  • Image compression by reducing the colours to k representative ones
  • Creating a “cluster” feature to help a supervised model

Common Mistakes

  1. Skipping scaling, so one large-valued feature decides the clusters.
  2. Reading cluster numbers as rankings.
  3. Picking k by eye without checking inertia or silhouette.
  4. Expecting identical results every run without setting random_state.

Practice Exercises

Exercise 1. Cluster the Iris measurements into 3 groups and compare the clusters with the real species.

Show answer
from sklearn.datasets import load_iris
import pandas as pd
X, y = load_iris(return_X_y=True)
labels = KMeans(n_clusters=3, n_init=10, random_state=0).fit_predict(X)
print(pd.crosstab(y, labels))

One species is separated perfectly; the other two overlap partly, because their measurements are similar.

Exercise 2. Why does inertia always decrease as k increases?

Show answer

More centres means every point can be closer to some centre. With k equal to the number of points, inertia reaches 0, but that clustering is useless. That is why you look for the elbow rather than the minimum.

Frequently Asked Questions

Is k-means supervised or unsupervised?

Unsupervised. It never sees labels; it only groups points by similarity. Do not confuse it with k-nearest neighbours, which is supervised.

How do I evaluate clusters without labels?

Use internal scores such as silhouette, check that the clusters are stable across runs, and most importantly ask whether the groups make sense and are useful to the people who will act on them.

Summary

  • K-means groups unlabelled data around k centres by repeating assign and update steps.
  • Scale features first; set n_init and random_state.
  • Choose k with the elbow method and silhouette score.
  • It assumes round clusters; try DBSCAN or mixture models otherwise.

Next: Project: An End-to-End Machine Learning Workflow.

Lessons are also marked complete when you click Next.

Leave a Reply

Your email address will not be published. Required fields are marked *