Repository navigation
FIX calinski_harabasz_score returns inf for perfectly separated clusters - #35389
Alm0stSurely wants to merge 1 commit into
Conversation
When intra-cluster dispersion is zero but between-cluster dispersion is positive, the score now returns +inf instead of 1.0. This is consistent with the limiting behavior as intra_disp approaches zero from above. The case where both dispersions are zero (all samples identical) preserves the existing 1.0 convention. Fixes scikit-learn#35387
|
Thank you for opening your first pull request to scikit-learn! 🎉 To help get your contribution reviewed, please make sure that:
|
❌ Linting issuesThis PR is introducing linting issues. Here's a summary of the issues. Note that you can avoid having linting issues by enabling You can see the details of the linting issues under the
|
|
Thanks for the PR. The linked issue #35387 is still labelled "Needs Triage", meaning maintainers haven't yet agreed that the current behaviour is a bug or what the fix should be. Returning |
Problem
calinski_harabasz_scorereturns1.0whenever within-cluster dispersion is zero, regardless of the between-cluster dispersion value. This conflates two distinct cases:intra_disp == 0,extra_disp > 0): the score should approach+infasintra_disp → 0⁺, but the current implementation returns1.0.intra_disp == 0,extra_disp == 0): a0/0indeterminate form where returning1.0is a reasonable convention.This means a clustering with three perfectly separated clusters can receive a lower score than a coarser two-cluster partition of the same data, potentially misleading cluster-count selection procedures.
Reproducer (from #35387):
Analysis
The Calinski-Harabasz index is:
When
intra_disp = 0andextra_disp > 0, the numerator is positive and the denominator is zero, so the ratio diverges to+inf. The current implementation short-circuits to1.0onintra_disp == 0.0without inspectingextra_disp, collapsing the two mathematically distinct cases into the same return value.Solution
Distinguish the two zero-dispersion cases:
intra_disp == 0andextra_disp == 0→ return1.0(preserve existing convention for indeterminate0/0)intra_disp == 0andextra_disp > 0→ returnfloat("inf")(consistent with the limiting behavior)Benchmarks
Not a performance change — the additional branch is evaluated only when
intra_disp == 0.0, which is a rare edge case.Behavior verification:
[0,0,1,1,2,2][0,0,1,1,1,1]Notes
float("inf")rather thanxp.infsince the return value is already cast to Pythonfloatand the dispersions are Python scalars at this point.np.isinfon the perfectly separated case.test_unsupervised.pysuite passes (50 tests).This pull request includes code written with the assistance of AI.
The code has not yet been reviewed by a human.