FIX restore UnionFind path compression in single-linkage clustering - #34873
Closed
ShamikOfficial wants to merge 1 commit into
Closed
FIX restore UnionFind path compression in single-linkage clustering#34873ShamikOfficial wants to merge 1 commit into
ShamikOfficial wants to merge 1 commit into
Conversation
The fast_find method used a Cython tuple assignment that silently disabled path compression, degrading single-linkage to O(n^2) on adversarial inputs. Replace with an explicit two-pass compression loop and add regression tests. Fixes scikit-learn#34626
|
Thank you for opening your first pull request to scikit-learn! 🎉 To help get your contribution reviewed, please make sure that:
|
Contributor
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
What
UnionFind.fast_findin_hierarchical_fast.pyxwas supposed to do path compression, but the Cython tuple assignment on the compression loop doesn't actually updateself.parent[p]— it just rebinds a local variable. On adversarial MST inputs this degrades single-linkage to roughly O(n²) instead of the expected near-linear behavior.This affects
AgglomerativeClustering(linkage="single"), HDBSCAN, and anything else that goes through_single_linkage_label.Fix
Replaced the broken loop with an explicit two-pass compression (find root, then walk back and point nodes directly at the root). Also removed
@cython.wraparound(True)fromfast_findsince negative indexing isn't used there.Tests
test_union_find_fast_find_compresses_path— verifies parent pointers get flattened after a findtest_union_find_fast_find_on_root_is_noop— calling find on a root shouldn't mutate the structureFixes #34626