Skip to content

HDBSCAN modifies input precomputed distance matrix #31907

Closed

Description

@tolyanchik5

Describe the bug

When using sklearn.cluster.HDBSCAN with metric="precomputed", the input distance matrix is modified after calling fit_predict(). The original hdbscan package (v0.8.40) works correctly.

Steps/Code to Reproduce

import numpy as np
from sklearn.cluster import HDBSCAN

rmsd_matrix = np.random.rand(5, 5)
rmsd_matrix = (rmsd_matrix + rmsd_matrix.T) / 2
np.fill_diagonal(rmsd_matrix, 0)

print("Before HDBSCAN:")
print(rmsd_matrix)

hdb = HDBSCAN(metric="precomputed", min_cluster_size=2)
hdb.fit_predict(rmsd_matrix)

print("\nAfter HDBSCAN:")
print(rmsd_matrix)  # Matrix is changed!

Expected Results

Input matrix should remain unchanged (as in original hdbscan).

Actual Results

Input matrix is changed

Versions

System:
    python: 3.12.3 (main, Jun 18 2025, 17:59:45) [GCC 13.3.0]
executable: /home/username/project/bin/python3
   machine: Linux-6.14.0-27-generic-x86_64-with-glibc2.39

Python dependencies:
      sklearn: 1.7.0
          pip: 24.0
   setuptools: 80.9.0
        numpy: 2.2.6
        scipy: 1.16.0
       Cython: None
       pandas: 2.3.0
   matplotlib: 3.10.3
       joblib: 1.5.1
threadpoolctl: 3.6.0

Built with OpenMP: True

threadpoolctl info:
       user_api: blas
   internal_api: openblas
    num_threads: 18
         prefix: libscipy_openblas
       filepath: /home/username/project/lib/python3.12/site-packages/numpy.libs/libscipy_openblas64_-56d6093b.so
        version: 0.3.29
threading_layer: pthreads
   architecture: Haswell

       user_api: blas
   internal_api: openblas
    num_threads: 18
         prefix: libscipy_openblas
       filepath: /home/username/project/lib/python3.12/site-packages/scipy.libs/libscipy_openblas-68440149.so
        version: 0.3.28
threading_layer: pthreads
   architecture: Haswell

       user_api: openmp
   internal_api: openmp
    num_threads: 18
         prefix: libgomp
       filepath: /home/username/project/lib/python3.12/site-packages/scikit_learn.libs/libgomp-a34b3233.so.1.0.0
        version: None

Activity

  1. added
    Needs Triage
    on Aug 9, 2025
  2. NandiniV-20 commented on Aug 11, 2025

    @NandiniV-20
  3. Sarthakpurii commented on Aug 11, 2025

    @Sarthakpurii
    Contributor

    I’m currently working on this issue.
    I have confirmed that when passing a dense precomputed distance matrix to HDBSCAN, scikit-learn’s implementation mutates the matrix in place. This should not happen as the input pairwise distance matrix should remain unchanged after fitting.
    Earlier, I suspected that it was due to force_writeable=True but maybe that's not the case. I'm currently investigating the issue further.

  4. adrinjalali commented on Aug 12, 2025

    @adrinjalali
    Member

    You can control this by setting copy=True, but default, we avoid copies and it means the original data might be changed. Same is true for a lot of other estimators in scikit-learn. This code works as you expect:

    import numpy as np
    from sklearn.cluster import HDBSCAN
    
    rmsd_matrix = np.random.rand(5, 5)
    rmsd_matrix = (rmsd_matrix + rmsd_matrix.T) / 2
    np.fill_diagonal(rmsd_matrix, 0)
    
    print("Before HDBSCAN:")
    print(rmsd_matrix)
    
    hdb = HDBSCAN(metric="precomputed", min_cluster_size=2, copy=True)
    hdb.fit_predict(rmsd_matrix)
    
    print("\nAfter HDBSCAN:")
    print(rmsd_matrix)  # Matrix is changed!

    Gives:

    Before HDBSCAN:
    [[0.         0.52876727 0.49823361 0.55830935 0.59378674]
     [0.52876727 0.         0.18351196 0.11763614 0.56948849]
     [0.49823361 0.18351196 0.         0.51278008 0.3258964 ]
     [0.55830935 0.11763614 0.51278008 0.         0.45695423]
     [0.59378674 0.56948849 0.3258964  0.45695423 0.        ]]
    
    After HDBSCAN:
    [[0.         0.52876727 0.49823361 0.55830935 0.59378674]
     [0.52876727 0.         0.18351196 0.11763614 0.56948849]
     [0.49823361 0.18351196 0.         0.51278008 0.3258964 ]
     [0.55830935 0.11763614 0.51278008 0.         0.45695423]
     [0.59378674 0.56948849 0.3258964  0.45695423 0.        ]]
    

    @NandiniV-20 @Sarthakpurii please make sure you only contribute where the issue is confirmed and maintainers have agreed on a solution. Otherwise we might need to block you from the org.

  5. Sarthakpurii commented on Aug 12, 2025

    @Sarthakpurii
    Contributor

    @adrinjalali Please don't be so harsh. I just wanted to give back to the community.

    I have used scikit-learn a lot, and I did some research as well yesterday. According to that, be it scikit-learn or any other ML library, the input data should not be mutated/altered given to their fit() or transform() methods by default as it breaks the reproducibility and predictability.

    Also, I did come through that the required functioning can be delivered by setting copy=True but that's not the default case here (I understand to avoid copies default is False, making the algorithm memory efficient). This is the reason I handled copy to set to be True if the given metric is dense precomputed distance metrics; otherwise false. Another idea was to set copy=True by default but that would not have been the memory efficient solution because if hdbscan_brute is used as mst_func for metrics other than 'precomputed', it would be creating possible extra copies which is not required.

    Would love to discuss this a bit further or get your views on this.

  6. NandiniV-20 commented on Aug 12, 2025

    @NandiniV-20
  7. adrinjalali commented on Aug 12, 2025

    @adrinjalali
    Member

    @Sarthakpurii now that you're investigating, could you please have a look at other estimators where we have a copy arg and see how the default behavior there is, and if there's any other case of precomputed input which could be a similar case. I'd be happy to have this fixed if it's not consistent with other places.

  8. Sarthakpurii commented on Aug 13, 2025

    @Sarthakpurii
    Contributor

    @adrinjalali I investigated other estimators with the copy parameter. Every single one defaults to copy=True. Here is the list of all the estimators for your convenience to quickly go through - FactorAnalysis, PLSSVD, _PLS, AffinityPropagation, IncrementalPCA, PCA, SimpleImputer, OrthogonalMatchingPursuitCV, KNNImputer & all normalizers/scalers. HDBSCAN is the only estimator having copy=False.

    Earlier, I was hesitant to set HDBSCAN's default copy=True because I was concerned about the performance and memory overhead and scikit-learn's broader design patterns. This is the reason I handled the copy to be True just for dense precomputed distance metrics in my recent PR, but now I feel setting default copy=True would be the better choice to maintain consistency. I would love to raise another PR correcting the same if you allow.

    What are your thoughts on this?

  9. Sarthakpurii commented on Aug 15, 2025

    @Sarthakpurii
    Contributor

    @adrinjalali I am waiting for your views on this.

  10. adrinjalali commented on Aug 19, 2025

    @adrinjalali
    Member

    Then I think we can have a PR changing the default value, w/o deprecation cycle, and have it as a FIX. I wonder what @Micky774 thinks about it though.

  11. Micky774 commented on Aug 19, 2025

    @Micky774
    Contributor

    Then I think we can have a PR changing the default value, w/o deprecation cycle, and have it as a FIX. I wonder what @Micky774 thinks about it though.

    It's worth making it consistent with other estimators if it is currently off. I think it might be worth a deprecation cycle though, since it could meaningfully break some workflows that perhaps already assumed that a copy was being made, and hence wouldn't immediately know how to correct for the change. Thank you for bringing this to our attention @Sarthakpurii and @tolyanchik5 :)

  12. Sarthakpurii commented on Aug 19, 2025

    @Sarthakpurii
    Contributor

    @Micky774 @adrinjalali I went through the standards on how scikit-learn implements a deprecation cycle in contributing.rst . If we are going forward with a deprecation cycle, we can make default value of copy="warn" and raise a warning that the default value of copy is going to change from False to True in version x, if user uses the default value of copy. Additionally, making some minor changes to _parameter_constraints,etc to maintain consistency for this change.

    Does this works?

  13. Micky774 commented on Aug 19, 2025

    @Micky774
    Contributor

    @Micky774 @adrinjalali I went through the standards on how scikit-learn implements a deprecation cycle in contributing.rst . If we are going forward with a deprecation cycle, we can make default value of copy="warn" and raise a warning that the default value of copy is going to change from False to True in version x, if user uses the default value of copy. Additionally, making some minor changes to _parameter_constraints,etc to maintain consistency for this change.

    Does this works?

    That sounds good to me. Feel free to ping me for review on that PR

  14. Sarthakpurii commented on Aug 19, 2025

    @Sarthakpurii
    Contributor

    Which version should I mention for when this change will go live?

  15. adrinjalali commented on Aug 19, 2025

    @adrinjalali
    Member

    That would be 1.10

  16. added and removed
    Needs Triage
    on Aug 21, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions