Skip to content

Calinski-Harabasz score returns 1.0 for perfectly separated clusters #35387

Open

Description

@ricardo55ribeiro

Warning

This issue is not yet ready for a PR. If you are interested in contributing to scikit-learn, please have a look at our contributing guidelines, and in particular the sections for new contributors and the "Needs triage" label.

Introduce yourself

I'm currently pursuing a Master's degree in Computer Science and Engineering at Instituto Superior Técnico, specializing in Artificial Intelligence and Distributed Systems. I previously completed a Bachelor's degree in Engineering Physics and have experience with ML research within and outside Physics.

I'm currently using scikit-learn in a Data Science course. Separately, I'm interested in understanding and improving the correctness and reliability of ML software. While investigating calinski_harabasz_score and testing clustering edge cases, I noticed that perfectly separated clusters can receive a lower score than a less compact partition.

Even though I haven't encountered this issue in my coursework, I believe it could be relevant when using the Calinski-Harabasz index to compare clustering solutions and select the number of clusters

Describe the bug and give evidence about its user-facing impact

When calinski_harabasz_score evaluates a clustering with zero within-cluster dispersion, but with positive between-cluster dispersion, it returns 1.0, even though the score approaches positive infinity as the within-cluster dispersion approaches zero from above.

For example, consider these six samples with values [0, 0, 10, 10, 20, 20]

A partition into three perfectly separated clusters, [0, 0, 1, 1, 2, 2], receives a score of 1.0
However, a coarser two-cluster partition, [0, 0, 1, 1, 1, 1], receives a score of 12.0

This means that a procedure selecting the number of clusters by maximizing the Calinski-Harabasz score could prefer the coarser partition, even though the three-cluster solution has zero within-cluster dispersion.

The implementation appears to return 1.0 whenever the within-cluster dispersion is zero, without distinguishing between perfectly separated clusters and datasets where all observations are identical

Steps/Code to Reproduce

from sklearn.metrics import calinski_harabasz_score

X = [[0], [0], [10], [10], [20], [20]]

perfect_labels = [0, 0, 1, 1, 2, 2]
coarser_labels = [0, 0, 1, 1, 1, 1]

print("Perfect:", calinski_harabasz_score(X, perfect_labels))
print("Coarser:", calinski_harabasz_score(X, coarser_labels))
print("Identical:", calinski_harabasz_score([[1]] * 6, perfect_labels))

Expected Results

The Calinski-Harabasz index is based on the ratio of between-cluster to within-cluster dispersion, adjusted for the numbers of samples and clusters.

For the perfectly separated partition, the between-cluster dispersion is positive (400) and the within-cluster dispersion is zero. As the within-cluster dispersion approaches zero from above, while the between-cluster dispersion remains positive, the score approaches positive infinity.

Returning np.inf for this case would be consistent with that limiting behavior, although the convention may need discussion.

The case where all samples are identical is different.
Here, both dispersions are zero, leading to an indeterminate 0/0 expression. The current implementation returns 1.0 for this case, and retaining that convention would preserve existing behavior.

I would therefore expect these two situations to be handled separately rather than both returning 1.0

Actual Results

The perfectly separated partition receives a lower score than the coarser partition:

Perfect: 1.0
Coarser: 12.0
Identical: 1.0

No exception or warning is raised

Versions

System:
    python: 3.12.10 (tags/v3.12.10:0cc8128, Apr  8 2025, 12:21:36) [MSC v.1943 64 bit (AMD64)]
executable: C:\Users\ricky\AppData\Local\Programs\Python\Python312\python.exe
   machine: Windows-11-10.0.26300-SP0

Python dependencies:
      sklearn: 1.9.1
          pip: 26.3
   setuptools: 84.0.0
        numpy: 2.5.4
        scipy: 1.18.1
       Cython: None
       pandas: 2.3.3
   matplotlib: 3.11.2
       joblib: 1.6.0
threadpoolctl: 3.7.0
     narwhals: 2.27.1

Built with OpenMP: True

threadpoolctl info:
       user_api: openmp
   internal_api: openmp
    num_threads: 8
         prefix: vcomp
       filepath: C:\Users\ricky\AppData\Local\Programs\Python\Python312\Lib\site-packages\sklearn\.libs\vcomp140.dll
        version: None

       user_api: blas
   internal_api: openblas
    num_threads: 8
         prefix: libscipy_openblas
       filepath: C:\Users\ricky\AppData\Local\Programs\Python\Python312\Lib\site-packages\numpy.libs\libscipy_openblas64_-ed4f167a5330424524f45258e7ca2c8d.dll
        version: 0.3.34.106.0
threading_layer: pthreads
   architecture: Haswell

       user_api: blas
   internal_api: openblas
    num_threads: 8
         prefix: libscipy_openblas
       filepath: C:\Users\ricky\AppData\Local\Programs\Python\Python312\Lib\site-packages\scipy.libs\libscipy_openblas-197ee2fc9b4d071f7e048078cac74115.dll
        version: 0.3.31.dev
threading_layer: pthreads
   architecture: Haswell

Interest in fixing the bug

Yes, I would be very interested in contributing a fix after the maintainer triage

From inspecting sklearn/metrics/cluster/_unsupervised.py, the implementation appears to return 1.0 whenever intra_disp == 0.0, regardless of the value of extra_disp

This combines two different situations, which are positive between-cluster dispersion with zero within-cluster dispersion, and zero dispersion in both cases.

A possible correction is to return positive infinity when intra_disp == 0.0 and extra_disp > 0.0, while preserving the existing 1.0 behavior when both dispersions are zero.

I have tested a small local correction against the development version. It resolves the reproduced behavior, and a new regression test fails before the correction and passes afterward.

The clustering metrics test suite reports 189 passed and 61 skipped tests. The skipped tests require optional Array API libraries or settings, so I haven't checked whether the fix works with all supported backends.

I would be happy to receive maintainer feedback on whether returning infinity is the preferred behavior and on the proposed approach and test coverage before opening a PR

Activity

  1. ricardo55ribeiro commented on Nov 14, 2026

    @ricardo55ribeiro
    Author

    Hi! As the original reporter of this issue, I'd like to reiterate my interest in contributing the fix.

    I've already investigated the root cause and prepared a local correction with regression tests. The regression test fails before the fix and passes afterward, and the clustering metrics test suite reports 189 passed and 61 skipped tests.

    I noticed that PRs #35389 and #35390 were opened for this issue while it was still awaiting triage, despite my previously stated interest in implementing the correction!

    I understand that contributions are open to everyone, but I believe it's important to respect both the project's contribution guidelines and the intentions of contributors who have already investigated and expressed interest in resolving an issue. Opening competing PRs before maintainer consensus, particularly in these circumstances, seems contrary to that process.

    I'd therefore appreciate being considered for the implementation once the issue has been triaged and the expected behavior agreed upon. I'm happy to incorporate maintainer feedback and take responsibility for the correction and its tests.

    I'll continue to follow the contribution guidelines and wait for maintainer feedback before opening a PR

    Thanks!

  2. Alm0stSurely commented on Nov 18, 2026

    @Alm0stSurely

    I reproduced the reported behavior on current main and would like to add some analysis that may help triage, without opening a PR — @ricardo55ribeiro has already prepared a correction and expressed interest in implementing it, and this should stay theirs.

    Root cause (current main, sklearn/metrics/cluster/_unsupervised.py):

    return float(
        1.0
        if intra_disp == 0.0
        else extra_disp * (n_samples - n_labels) / (intra_disp * (n_labels - 1.0))
    )

    The intra_disp == 0.0 branch does not distinguish extra_disp > 0 (perfectly separated) from extra_disp == 0 (all samples identical), which are mathematically different degenerate cases.

    The discontinuity. With extra > 0 fixed, the score is extra·(n−k) / (intra·(k−1)), so CH → +∞ as intra → 0⁺. The branch inserts a downward jump to 1.0 at exactly intra = 0: the limit from the right is +∞, the value at the point is 1.0. Measured on the issue's example, moving one sample per cluster by ε:

    within-dispersion CH score
    2e-16 (one sample offset by 1e-8) 4.0e+18
    0.0 (exact) 1.0

    So a procedure maximizing CH is not merely indifferent to the perfect partition — it is actively repelled from it, scoring the exact optimum ~18 orders of magnitude below an arbitrarily close approximation. This is the strongest argument that 1.0 is the wrong value for the extra > 0, intra = 0 case, independent of which convention replaces it.

    One subtlety worth pinning down in the fix: intra_disp == 0.0 in float64 does not imply "perfectly separated." Squared deviations underflow: two points spaced 1e-200 apart have squared deviation 1e-400 → 0.0. Concretely, X = [[0],[1e-200],[10],[10+1e-200],[20],[20+1e-200]] with the perfect labels returns 1.0 today, although in exact arithmetic CH ≈ 2e+400. The same branch therefore conflates an exact-arithmetic +∞ case with a large-but-finite case. Returning np.inf whenever extra > 0 and intra == 0.0 treats both consistently (an underflown dispersion is, if anything, closer to the +∞ limit than the exact case); a tolerance-based alternative would need to justify where the threshold sits relative to underflow.

    The 0/0 case (extra = 0, intra = 0, e.g. all observations identical) is genuinely indeterminate, and keeping the current 1.0 there preserves backward compatibility — the two cases can be handled separately, as the issue suggests.

    Precedent-wise, ratio-type cluster-validity criteria each pick a convention at this pole (return inf, return a large finite value, or NaN); the important property for model selection is monotonicity in the right direction — the score of a refinement should not drop as within-dispersion decreases. Any fix should probably also document the convention in the Returns section, since downstream argmax-based selection is the user-facing impact.

  3. ricardo55ribeiro commented on Nov 18, 2026

    @ricardo55ribeiro
    Author

    Thank you for taking the time to investigate this further!

    I appreciate the additional analysis, especially the floating-point underflow case. And thanks for respecting my interest in implementing the fix

    I'll keep these points in mind and wait for maintainer feedback before proceeding :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    BugNeeds Triage

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions