Compute Silhouette Score
Compute Silhouette Score
Implement a function to compute the Silhouette Score for clustering. The Silhouette Score measures how well each point fits within its cluster compared to other clusters.
For each sample i:
- a(i): average distance to all other points in the same cluster (intra-cluster distance)
- b(i): minimum average distance to points in any other cluster (nearest inter-cluster distance)
The silhouette for point i is:
s(i)=max(a(i),b(i))b(i)−a(i)The final score is the mean of all s(i).
Examples
Input: X=[[0,0],[0,1],[1,0],[5,5],[5,6],[6,5]], labels=[0,0,0,1,1,1]
Output: ≈ 0.79
Hint 1
Use broadcasting to compute all-pairs Euclidean distances efficiently.
Hint 2
Use boolean masking to efficiently compute intra-cluster and inter-cluster means.
Requirements
- Must work for any number of clusters (K ≥ 2)
- Distance metric: Euclidean
- Fully vectorized (no nested loops)
- Return a single float in range [-1, 1]
Constraints
- 2 ≤ n_samples ≤ 500
- Use only NumPy
Log in to take notes on this problem
Accepts: array
Accepts: array
Compute Silhouette Score
Compute Silhouette Score
Implement a function to compute the Silhouette Score for clustering. The Silhouette Score measures how well each point fits within its cluster compared to other clusters.
For each sample i:
- a(i): average distance to all other points in the same cluster (intra-cluster distance)
- b(i): minimum average distance to points in any other cluster (nearest inter-cluster distance)
The silhouette for point i is:
s(i)=max(a(i),b(i))b(i)−a(i)The final score is the mean of all s(i).
Examples
Input: X=[[0,0],[0,1],[1,0],[5,5],[5,6],[6,5]], labels=[0,0,0,1,1,1]
Output: ≈ 0.79
Hint 1
Use broadcasting to compute all-pairs Euclidean distances efficiently.
Hint 2
Use boolean masking to efficiently compute intra-cluster and inter-cluster means.
Requirements
- Must work for any number of clusters (K ≥ 2)
- Distance metric: Euclidean
- Fully vectorized (no nested loops)
- Return a single float in range [-1, 1]
Constraints
- 2 ≤ n_samples ≤ 500
- Use only NumPy
Log in to take notes on this problem
Accepts: array
Accepts: array