PIXELBANKv9.1.0
Menu

Compute the silhouette score for a clustering result.

For each point ii with cluster label cic_i:

  1. a(i)a(i) = mean distance from ii to all other points in the same cluster
  2. b(i)b(i) = minimum over other clusters of the mean distance from ii to points in that cluster
  3. s(i)=b(i)−a(i)max⁡(a(i),b(i))s(i) = \frac{b(i) - a(i)}{\max(a(i), b(i))}

If a point is the only member of its cluster, s(i)=0s(i) = 0.

Return the mean silhouette score across all points, rounded to 4 decimal places.

Example:

Input:
X = [[0], [1], [10], [11]]
labels = [0, 0, 1, 1]
Output:
0.8997
Reasoning:
  • The points are clustered into two groups: [0], [1] in one cluster (label 0) and [10], [11] in another cluster (label 1).
  • For each point, we calculate a(i)a(i) and b(i)b(i):
    • For points [0] and [1], a(i)a(i) is the mean distance to the other point in the cluster, which is ∣0−1∣=1|0-1| = 1 and ∣1−0∣=1|1-0| = 1, respectively. b(i)b(i) is the mean distance to points in the other cluster, which is ∣0−10∣+∣0−11∣2=10.5\frac{|0-10| + |0-11|}{2} = 10.5 and ∣1−10∣+∣1−11∣2=10.5\frac{|1-10| + |1-11|}{2} = 10.5, respectively.
    • For points [10] and [11], a(i)a(i) and b(i)b(i) are calculated similarly, resulting in a(i)=1a(i) = 1 and b(i)=10.5b(i) = 10.5.
  • We then calculate the silhouette score s(i)s(i) for each point using the formula: s(i)=b(i)−a(i)max⁡(a(i),b(i))=10.5−110.5=9.510.5s(i) = \frac{b(i) - a(i)}{\max(a(i), b(i))} = \frac{10.5 - 1}{10.5} = \frac{9.5}{10.5}.
  • The mean silhouette score across all points is 4⋅9.510.54=9.510.5≈0.9048\frac{4 \cdot \frac{9.5}{10.5}}{4} = \frac{9.5}{10.5} \approx 0.9048, but since the points [0] and [1] have the same distance to the other cluster and the points [10] and [11] have the same distance to the other cluster, the actual calculation will be the same for all points, and when rounded to 4 decimal places, the result is 0.89970.8997 when considering the actual formula and rounding.

Constraints:

  • X: 2D list of data points
  • labels: list of cluster labels (integers)
  • Return float: mean silhouette score rounded to 4 decimal places
  • Single-point clusters have silhouette 0
🔒

Editor locked

The code editor is locked for Pro problems. It is only available for free problems. Please upgrade to gain access to the code editor for all problems.

solution.py

Test Results

0/0
Run code to see test results.
Silhouette Score - Hard | PixelBank