SilhouetteScore crashes when number of clusters < 2
š Bug description
The SilhouetteScore metric in ignite.metrics.clustering currently raises a ValueError when the number of unique clusters is invalid for the silhouette calculation. According to the silhouette coefficient definition, the score is undefined if:
- The number of clusters is 1 (no inter-cluster distance $b$ exists).
- The number of clusters equals the number of samples (each point is its own cluster, so intra-cluster distance $a$ is undefined).
Currently, the metric wraps sklearn.metrics.silhouette_score without pre-validating the labels. This causes the entire Ignite Engine to crash during an evaluation run if a clustering algorithm converges to a single cluster or assigns every point uniquely.
Steps to reproduce
import torch
from ignite.metrics.clustering import SilhouetteScore
metric = SilhouetteScore()
features = torch.randn(10, 5)
# Case 1: Only 1 cluster
labels_single = torch.zeros(10, dtype=torch.long)
metric.update((features, labels_single))
# Raises ValueError: Number of labels is 1. Valid values are 2 to n_samples - 1 (inclusive).
print(metric.compute())
# Case 2: Every point is its own cluster
labels_unique = torch.arange(10)
metric.reset()
metric.update((features, labels_unique))
# Raises ValueError: Number of labels is 10. Valid values are 2 to n_samples - 1 (inclusive).
print(metric.compute())
Hi @vfdev-5, I've spent some time auditing this and have a local fix ready that validates the cluster counts and returns a default value with a UserWarning to prevent the Engine from crashing.
I've also noticed this pattern repeats in DaviesBouldinScore (Issue #3642 ). Iād love to work on a consolidated PR to standardize this validation across the clustering module if that sounds good to you!
@Prathamesh8989 thanks for the reports and investigations, it is however a bit unclear the exception is coming from sklearn.metrics.silhouette_score ? Do they have an option to warn instead of raise an error?
It is the expected behaviour for sklearn.metrics.silhouette_score as much I have researched the nearest-cluster distance can't be computed with just 1 label.
I think best approach would be to return a very big number or Nan/None as penalty and adding a warning in .compute() method of the metrics that suffer from this problem.
Thanks for the feedback, @vfdev-5 and @aaishwarymishra!
To answer @vfdev-5: Yes, the exception is raised directly by sklearn.metrics.silhouette_score. Unfortunately, Scikit-learn does not provide a built-in parameter to warn instead of raise for these specific edge cases (1 cluster or N clusters).
I agree with @aaishwarymishra's suggestion. Since the silhouette score is undefined in these cases, returning float('nan') or None alongside a UserWarning in the .compute() method would prevent the Engine from crashing while still notifying the user that the clustering was invalid for this metric.
Would you prefer NaN or None as the return value? Once confirmed, I can submit the PR covering both this and the DaviesBouldinScore issue (#3642).
I've noted the related work on the Dunn Index (#3635).
My proposed fix focuses specifically on improving robustness against ValueError in existing metrics such as SilhouetteScore and DaviesBouldinScore.
The validation logic introduced here could also potentially serve as a reusable utility for other clustering metrics currently under development, helping ensure consistent and consistent behavior across the module.
I think using NaN as the return value makes more sense because most metrics use it to represent undefined values. Shared validation helps for the common cluster checks, as an addition it is better to wrap the sklearn call in a try/except so unexpected ValueError don't crash the engine
@Prathamesh8989 I think the same issue also exists in ignite.metrics.clustering.CalinskiHarabaszScore. We should also include it in the fixes
Good catch, @TahaZahid05! š
You're right ā CalinskiHarabaszScore has the same requirement on the number of clusters (2 <= n_labels <= n_samples - 1) in scikit-learn, so it could raise the same ValueError in those edge cases.
@lfshao it might be worth extending the validation logic introduced in this PR to CalinskiHarabaszScore as well to keep the behavior consistent across clustering metrics. This would ensure the engine doesn't crash if those cases occur.
Thanks everyone for the suggestions!
@TahaZahid05 I think we should close these seperate issues and open a common single issue as there can be many metrics that faces these problems, and each metric should have its separate pr.
@aaishwarymishra makes sense. I'll open a single issue that tracks all these cases. We'll close these issues then, and let contributors open separate PRs per metric to keep things uniform.
Closing this in favor of the consolidated tracking issue #3655. Let's continue the discussion and track PRs there.
Hi! I've looked into this bug and would like to fix it.
Root cause: _silhouette_score passes data directly to
sklearn.metrics.silhouette_score without validating the number
of unique clusters first. sklearn internally raises a raw ValueError
with a confusing message when there's only 1 unique label.
Proposed fix: Add an explicit check before calling sklearn and raise
NotComputableError with a clear message ā consistent with how other
Ignite metrics handle invalid states.
n_unique = len(set(np_labels.tolist()))
if n_unique < 2:
raise NotComputableError(
f"SilhouetteScore requires at least 2 clusters, "
f"but found only {n_unique} unique label(s)."
)
I'll also add a test case covering this edge case and fix the same issue
in DaviesBouldinScore (#3642) in the same PR since the root cause is identical.
Already have the fix ready ā will open the PR shortly. Please let me know if there's a preferred approach!
Hi! I've opened a PR to fix this: PR Link
The fix adds an explicit cluster count check before calling sklearn and raises NotComputableError with a clear message. Also includes a test case covering this edge case.
I would like to work on this issue. The fix is straightforward: add a validation check in _silhouette_score before calling sklearn to return float("nan") when the number of unique clusters is < 2 or >= n_samples. I have a PR ready: https://github.com/frankgoldfish/ignite/tree/fix/silhouette-score-edge-cases
Fix SilhouetteScore crash for invalid cluster counts
Return NaN when number of clusters < 2 or equals number of samples instead of raising ValueError from sklearn.