Score a clustering with the silhouette coefficient

How do you know if a clustering is any good without labels? The silhouette compares how close a point is to its own cluster against the nearest other cluster.

For point i: a = mean distance to the other points in its cluster, b = smallest mean distance to the points of any other cluster, s = (b - a) / max(a, b). A point alone in its cluster gets s = 0.

Write silhouette(X, labels) returning the mean s over all points. Use Euclidean distance. Assume at least two clusters.

Signaturedef silhouette(X, labels)

Understand the idea

The silhouette checks a clustering without labels by asking, for each point, whether it sits closer to its own cluster than to the nearest other cluster. Like checking whether each student sits closer to their own group's table than to any other table. For point i, a is the mean distance to the other points in its cluster (exclude itself), and b is the smallest mean distance to all points of another cluster. Then s = (b - a) / max(a, b), between -1 and 1. A point alone in its cluster gets s = 0. Worked example, 1D: points 0 and 1 in cluster A, point 4 in cluster B. Point 0: a = 1, b = 4, s = 3/4 = 0.75. Point 1: a = 1, b = 3, s = 2/3 = 0.667. Point 4 is alone, s = 0. Mean = (0.75 + 0.667 + 0) / 3 = 0.472. Rule: average s over all points with Euclidean distance. It is used to compare cluster counts when grouping documents or users.

solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

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

  • Sample 1: good clusteringsilhouette(_X, [0, 0, 0, 1, 1, 1])
  • Sample 2: bad clusteringsilhouette(_X, [0, 1, 0, 1, 0, 1])