Silhouette Score: Grading Clusters Without Labels

Metrics & EvaluationMedium+20 XP+15

Silhouette Score: Grading Clusters Without Labels

Clustering has no labels to check against, so how do you know whether the clusters are any good? The silhouette score asks, for each point: is it closer to its own cluster than to the nearest other one?

For point i:

  • a — mean distance from i to the other points in its own cluster
  • b — mean distance from i to the points of the nearest other cluster, taking the minimum over all other clusters
  • s = (b - a) / max(a, b)

Task: write silhouette_score(points, labels) returning the mean of s over all points, rounded to 4 decimal places. Use Euclidean distance.

  • A point alone in its cluster scores 0.0 by convention — a is undefined there.
  • b averages over all points of the other cluster, then takes the minimum across clusters. Don't take the single nearest point.
  • There are always at least two clusters.

The score runs from -1 to 1. Near 1 means tight, well-separated clusters; near 0 means points sitting on a boundary; negative means points would be better off in the neighbouring cluster — which usually means you picked the wrong k.

Examples

points = [[0.0, 0.0], [0.0, 1.0], [10.0, 0.0], [10.0, 1.0]]
labels = [0, 0, 1, 1]
returns 0.9002
points = [[0.0], [1.0], [2.0], [3.0]]
labels = [0, 0, 1, 1]
returns 0.4667

Hints

Solve it to unlock the solution

Once your code passes every test, a reference solution shows up here so you can compare it with yours.

solution.py
CtrlEnterto run