Score a clustering with the Davies-Bouldin index

Why it matters Davies-Bouldin is a cheap internal metric for choosing the number of clusters when no labels exist, for example in customer segmentation.

The Davies-Bouldin index compares how spread out each cluster is with how far it sits from its most similar neighbour cluster. Lower is better.

Write davies_bouldin(X, labels). Labels are arbitrary integers with at least 2 distinct values. For each cluster i (in sorted label order) let c_i be its centroid and s_i the average Euclidean distance of its points to c_i. For i != j, R_ij = (s_i + s_j) / ||c_i - c_j||. Return the float mean over clusters i of max_{j != i} R_ij.

Signaturedef davies_bouldin(X, labels)

Example

X [[0, 0], [0, 2], [4, 0], [4, 2]], labels [0, 0, 1, 1] gives 0.5.

Understand the idea

A good clustering has tight clusters that sit far apart. The Davies-Bouldin index checks this for each cluster against its most confusing neighbour: how big are the two clusters compared with the gap between them?

For clusters i and j, R_ij = (s_i + s_j) / distance between centroids, where s is the average distance of a cluster's points to its centroid. If two clusters have radius 1 each and their centers are 4 apart, R = 2 / 4 = 0.5. If their centers were only 2 apart, R = 1, meaning they practically touch.

Worked example: points (0, 0), (0, 2) in cluster 0 and (4, 0), (4, 2) in cluster 1. Centroids (0, 1) and (4, 1), each point is 1 away from its centroid, so s = 1 for both. The centroid gap is 4, so R = 0.5 for both clusters and the index is 0.5.

Rule: DB = mean over i of max over j != i of (s_i + s_j) / ||c_i - c_j||. Lower is better.

It is often plotted against the number of clusters k to pick a reasonable k.

Shapes and data flow

X (n, d) -> centroids (K, d), s (K,) -> R (K, K)
solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks the hidden tests with Pro.

  • Sample 1: exampledavies_bouldin([[0, 0], [0, 2], [4, 0], [4, 2]], [0, 0, 1, 1])
  • Sample 2: three clustersdavies_bouldin([[0, 0], [1, 0], [5, 5], [6, 5], [10, 0], [12, 0]], [7, 7, 3, 3, 9, 9])