Silhouette Score From Scratch in NumPy

Quick Overview

Implement per-point silhouette values and the mean silhouette score in NumPy without scikit-learn, for both Euclidean features and a precomputed distance matrix. It tests vectorized distance bookkeeping, noise handling, singleton clusters and input validation.

Silhouette Score From Scratch in NumPy

Role: Machine Learning Engineer

Category: Machine Learning

Difficulty: medium

Interview Round: Other

Implement `silhouette_samples(X, labels, metric="euclidean")` returning a per-point silhouette array of length n, and `silhouette_score(X, labels, metric="euclidean")` returning the mean as a Python `float`. Use `s(i) = (b(i) - a(i)) / max(a(i), b(i))`, where `a(i)` is the mean distance to the other members of i's cluster and `b(i)` is the smallest mean distance to any other cluster. Do not use `sklearn.metrics`. Requirements: - `metric` is `"euclidean"` (X is n×d) or `"precomputed"` (X is a square n×n distance matrix). Any other value raises `ValueError`. - Label `-1` is noise: its value is `NaN`, and it is excluded from all a/b computations and from the mean. - A point in a singleton cluster scores `0.0`. If `max(a, b) == 0`, the score is `0.0`. - Fewer than 2 non-noise clusters, a non-square precomputed matrix, or a length mismatch between `X` and `labels` raises `ValueError`. - Labels are arbitrary integers. Results must be invariant to relabelling and match sklearn on non-noise points (rtol 1e-7). Examples: ```python X = [[0.0], [1.0], [4.0], [5.0]] labels = [0, 0, 1, 1] silhouette_samples(X, labels) # [7/9, 5/7, 5/7, 7/9] X = [[0.0], [1.0], [10.0]] labels = [0, 0, 1] silhouette_samples(X, labels) # [0.9, 8/9, 0.0] (the singleton scores 0) ``` ```hint One table for a and b Both a(i) and b(i) are mean distances from point i to the members of some cluster. Think about which single n × k table gives you both. ``` ```hint Self-distance When you average over i's own cluster, check whether i itself is in the sum and what the divisor should be. ``` ### Constraints & Assumptions - n is at most a few hundred, so an O(n²) distance matrix is acceptable. - `scipy.spatial.distance.cdist` may be used for distances. ### What a Strong Answer Covers - Distance handling for both metrics, with the checks on the metric name, the square matrix and the length match. - Noise points removed before any a(i) or b(i) is computed, and returned as `NaN`. - The correct divisor for a(i) and b(i) as a minimum over the other clusters' mean distances. - The singleton and zero-denominator rules, and a score that averages only non-noise points. - The time and memory cost of the full distance matrix. ### Follow-up Questions - How would you scale this to n = 10⁶ points? - Why exclude noise rather than treat `-1` as its own cluster? - What are the silhouette's weaknesses as a model-selection metric?

Overview: Implement per-point silhouette values and the mean silhouette score in NumPy without scikit-learn, for both Euclidean features and a precomputed distance matrix. It tests vectorized distance bookkeeping, noise handling, singleton clusters and input validation.

General logo
General
Nov 25, 2026
mediumMachine Learning EngineerOtherMachine Learning
0
0

Implement silhouette_samples(X, labels, metric="euclidean") returning a per-point silhouette array of length n, and silhouette_score(X, labels, metric="euclidean") returning the mean as a Python float. Use s(i) = (b(i) - a(i)) / max(a(i), b(i)), where a(i) is the mean distance to the other members of i's cluster and b(i) is the smallest mean distance to any other cluster. Do not use sklearn.metrics.

Requirements:

  • metric is "euclidean" (X is n×d) or "precomputed" (X is a square n×n distance matrix). Any other value raises ValueError .
  • Label -1 is noise: its value is NaN , and it is excluded from all a/b computations and from the mean.
  • A point in a singleton cluster scores 0.0 . If max(a, b) == 0 , the score is 0.0 .
  • Fewer than 2 non-noise clusters, a non-square precomputed matrix, or a length mismatch between X and labels raises ValueError .
  • Labels are arbitrary integers. Results must be invariant to relabelling and match sklearn on non-noise points (rtol 1e-7).

Examples:

X = [[0.0], [1.0], [4.0], [5.0]]
labels = [0, 0, 1, 1]
silhouette_samples(X, labels)   # [7/9, 5/7, 5/7, 7/9]

X = [[0.0], [1.0], [10.0]]
labels = [0, 0, 1]
silhouette_samples(X, labels)   # [0.9, 8/9, 0.0]  (the singleton scores 0)

Constraints & Assumptions

  • n is at most a few hundred, so an O(n²) distance matrix is acceptable.
  • scipy.spatial.distance.cdist may be used for distances.

What a Strong Answer Covers Guidance

  • Distance handling for both metrics, with the checks on the metric name, the square matrix and the length match.
  • Noise points removed before any a(i) or b(i) is computed, and returned as NaN .
  • The correct divisor for a(i) and b(i) as a minimum over the other clusters' mean distances.
  • The singleton and zero-denominator rules, and a score that averages only non-noise points.
  • The time and memory cost of the full distance matrix.

Follow-up Questions Guidance

  • How would you scale this to n = 10⁶ points?
  • Why exclude noise rather than treat -1 as its own cluster?
  • What are the silhouette's weaknesses as a model-selection metric?