Machine LearningClustering & Unsupervised Learning
What Is the Silhouette Score and How Is It Used to Evaluate Clustering?
Question 308 of 308 · Updated
On this page
- 1. Why clustering needs evaluation
- 2. The intuition: cohesion versus separation
- 3. A small numerical example
- 4. Per-sample scores and the overall score
- 5. Computing the score with scikit-learn
- 6. Using silhouette analysis to compare cluster counts
- 7. Important limitations
- It favors some geometries
- It depends on the distance metric
- It can be misleading with imbalanced clusters
- It is not a business outcome metric
- It can be computationally expensive
- It requires a valid number of clusters
- 8. Silhouette score versus other clustering metrics
- 9. Practical production workflow
- 10. Interview-ready answer
- 11. Key takeaways
1. Why clustering needs evaluation#
Clustering is an unsupervised learning task: an algorithm groups observations without relying on a supplied target label. That creates an evaluation problem. In a supervised classification task, predictions can be compared with known labels. In clustering, those labels are usually unavailable, so we need measures that inspect the geometry and structure of the produced groups.
The silhouette coefficient is an internal clustering evaluation measure. It compares how close a sample is to points in its own cluster with how close it is to points in the nearest alternative cluster. It can help answer two practical questions:
- Is this observation reasonably close to its assigned cluster?
- Is it separated from the next-best cluster?
The score can be calculated for every observation and averaged to summarize a clustering. It is useful for diagnosing cluster assignments and comparing candidate configurations, but it is not a universal measure of cluster quality.
2. The intuition: cohesion versus separation#
For each observation i, define two quantities:
- a(i): the average distance from observation i to all other observations in the same cluster. This is its within-cluster dissimilarity.
- b(i): for every other cluster, calculate the average distance from i to the observations in that cluster. b(i) is the smallest of those averages: the mean distance to the nearest neighboring cluster.
The silhouette coefficient is:
s(i) = (b(i) - a(i)) / max(a(i), b(i))
The denominator normalizes the difference, keeping the result between -1 and 1 when distances are non-negative and the quantities are well-defined.
Interpretation:
- Near +1: the observation is much closer to its own cluster than to the nearest alternative cluster. Its assignment is well separated under the chosen distance measure.
- Around 0: the observation lies near a decision boundary or between clusters. The groups may overlap.
- Below 0: the observation is, on average, closer to another cluster than to its assigned cluster. It may be misassigned, or the chosen representation and distance may not match the data structure.
A negative value is a diagnostic signal, not proof that the algorithm made an error. Some valid clusters overlap, have non-convex geometry, or are defined by density rather than simple distance to a center.
3. A small numerical example#
Suppose a customer record has an average distance of 2.0 to other customers in its assigned segment. Its average distance to the nearest alternative segment is 5.0.
a = 2.0 b = 5.0 s = (5.0 - 2.0) / max(2.0, 5.0) = 0.60
A score of 0.60 suggests this record is substantially closer to its own segment than to the nearest alternative.
Now suppose another record has a = 4.8 and b = 5.0:
s = (5.0 - 4.8) / 5.0 = 0.04
It is almost equally close to its own cluster and a neighboring cluster. It may sit near a boundary.
Finally, if a = 6.0 and b = 4.0:
s = (4.0 - 6.0) / 6.0 = -0.33
The record is, on average, closer to another cluster. Inspect it for unusual features, poor scaling, noise, or a questionable assignment.
4. Per-sample scores and the overall score#
The mean silhouette score is the arithmetic mean of the individual sample coefficients:
S = (1 / n) * sum(s(i), i=1..n)
A higher mean often indicates more compact and better-separated clusters for the selected distance metric. But an average hides important variation. A clustering can have a reasonable mean while one small cluster is badly formed or many observations have negative scores.
Use both levels of analysis:
- Overall mean: a compact summary for comparing candidate clusterings.
- Per-sample scores: identify ambiguous, poorly assigned, or anomalous observations.
- Per-cluster distributions: compare cluster size, mean, median, spread, and negative-score share.
- Silhouette plots: inspect the distribution of sample scores within each cluster, with clusters separated visually.
Do not report only the global average when a business decision depends on the quality of each segment.
5. Computing the score with scikit-learn#
The scikit-learn API provides two useful functions:
silhouette_score(X, labels)returns the mean coefficient across observations.silhouette_samples(X, labels)returns one coefficient per observation.
Example:
PYTHONfrom sklearn.cluster import KMeans from sklearn.metrics import silhouette_score, silhouette_samples from sklearn.preprocessing import StandardScaler X_scaled = StandardScaler().fit_transform(X) model = KMeans(n_clusters=4, random_state=42, n_init="auto") labels = model.fit_predict(X_scaled) overall = silhouette_score(X_scaled, labels) per_sample = silhouette_samples(X_scaled, labels) print(f"Mean silhouette: {overall:.3f}") print(f"Negative-score share: {(per_sample < 0).mean():.1%}")
The feature representation and distance metric are part of the evaluation definition. Scaling is not a mandatory ritual; it is appropriate when feature units and magnitudes should not dominate the distance. For example, a customer dataset containing annual income in thousands and age in years may need scaling, while a domain-specific weighted distance may be more appropriate in another application.
The API also accepts a metric name or callable. If you pass a precomputed distance matrix, set metric="precomputed" and ensure it represents valid pairwise distances with a zero diagonal.
6. Using silhouette analysis to compare cluster counts#
A common use is comparing candidate values of k for K-Means:
PYTHONfrom sklearn.cluster import KMeans from sklearn.metrics import silhouette_score for k in range(2, 9): labels = KMeans( n_clusters=k, random_state=42, n_init="auto" ).fit_predict(X_scaled) score = silhouette_score(X_scaled, labels) print(k, round(score, 3))
The highest mean score can be a useful candidate, but it should not be treated as an automatic answer to the question "How many clusters exist?"
A disciplined comparison should also examine:
- Cluster sizes: does a high score come from one large cluster and tiny fragments?
- Stability: do assignments and scores remain similar across random seeds or resampled data?
- Domain usefulness: do the groups support a meaningful decision or action?
- Alternative structures: does the algorithm impose a geometry that does not fit the data?
- Operational constraints: can the resulting groups be interpreted, served, and maintained?
This question is distinct from simply choosing k with the elbow method. The elbow method studies within-cluster dispersion as k changes; silhouette analysis evaluates relative within-cluster cohesion and nearest-cluster separation under a specified distance measure.
7. Important limitations#
It favors some geometries#
The silhouette score tends to work best when clusters are compact and reasonably separated under the chosen metric. It can favor convex, similarly sized groups and may undervalue density-based or non-convex structures. For example, two crescent-shaped clusters can be valid and clearly separated topologically while many points are not close to the mean of their own crescent under Euclidean distance.
For DBSCAN or other density-based methods, a low silhouette score does not automatically mean the discovered density structure is useless. Inspect cluster shapes and use complementary density-aware validation.
It depends on the distance metric#
Euclidean distance, Manhattan distance, cosine distance, and domain-specific distances can produce different values and even different nearest-cluster relationships. The metric should reflect what "similar" means for the task. Comparing scores computed using different metrics is generally not an apples-to-apples comparison.
It can be misleading with imbalanced clusters#
A global mean weights every observation equally, not every cluster equally. A large cluster can dominate the score and hide a poor small cluster. Always inspect per-cluster distributions and sizes.
It is not a business outcome metric#
A high silhouette score does not prove that segments improve conversion, retention, fraud detection, or operational efficiency. Validate the downstream utility of clusters separately.
It can be computationally expensive#
Exact silhouette computation requires pairwise distance calculations and can become costly as the dataset grows. scikit-learn supports sample_size to estimate the mean on a subset. Use a fixed random_state for reproducibility, and validate that the sample represents small clusters and important subpopulations. Sampling reduces cost but introduces estimation variability.
It requires a valid number of clusters#
The coefficient is defined only when the number of distinct labels is at least 2 and at most n_samples - 1. A single-cluster assignment or an assignment where every observation is its own cluster cannot be evaluated meaningfully with this metric.
8. Silhouette score versus other clustering metrics#
- Inertia / within-cluster sum of squares: measures the compactness of K-Means clusters, but decreases as the number of clusters increases. It does not directly measure separation from the nearest alternative cluster.
- Davies–Bouldin index: compares within-cluster scatter with between-cluster separation; lower is better. It has different assumptions and behavior.
- Calinski–Harabasz index: compares between-cluster dispersion with within-cluster dispersion; higher is better. It is also an internal measure.
- Adjusted Rand Index and Normalized Mutual Information: compare predicted cluster assignments with reference labels. They are external measures and require ground-truth labels or a trusted reference partition.
No single metric is sufficient for every clustering problem. Use multiple diagnostics that reflect the data geometry and the decision the clusters are intended to support.
9. Practical production workflow#
- Define what similarity means before choosing a distance metric.
- Build the feature representation using training data only; avoid leaking future or target information into clustering.
- Apply transformations and scaling consistently.
- Fit several plausible clustering configurations, including alternative algorithms when geometry is uncertain.
- Calculate the overall silhouette score and per-sample coefficients.
- Inspect per-cluster distributions, sizes, and negative-score examples.
- Check stability across seeds, samples, and time windows.
- Validate the segments with domain experts and downstream business outcomes.
- Record the metric, preprocessing, sample size, random seed, and algorithm configuration so comparisons are reproducible.
- Monitor cluster sizes and score distributions after deployment; changing data distributions can make previously useful segments less coherent.
10. Interview-ready answer#
The silhouette score is an internal metric for evaluating clustering when ground-truth labels are unavailable. For each sample, it compares its average distance to points in its own cluster (a) with its average distance to the nearest other cluster (b), using s = (b - a) / max(a, b). Scores close to +1 indicate well-separated assignments, values near zero indicate overlap, and negative values suggest a sample may fit another cluster better. The mean gives an overall summary, while per-sample and per-cluster scores reveal weak assignments. It depends on the distance metric, favors certain cluster shapes, can be expensive on large datasets, and should be combined with stability, domain, and downstream validation.
11. Key takeaways#
- Silhouette measures relative cohesion and separation, not absolute business quality.
- The per-sample formula is (b - a) / max(a, b).
- Values range from -1 to +1; positive is generally better, near zero signals overlap, and negative values deserve inspection.
- Compare per-cluster distributions, not just the global mean.
- The distance metric, feature scaling, cluster geometry, and class imbalance affect interpretation.
- Use silhouette alongside stability checks, alternative internal metrics, and domain validation.
References
- 1.scikit-learn — silhouette_score APIscikit-learn.org
- 2.scikit-learn — silhouette_samples APIscikit-learn.org
- 3.scikit-learn User Guide — Clustering and Silhouette Coefficientscikit-learn.org
- 4.
- 5.doi.org — 0377 0427(87doi.org
Related questions
Explore other topics:Forward Deployed EngineeringDeep LearningMLOps