Skip to content

Make neighbors work based on KNeighborsTransformer-compatible APIs - #2536

Merged
flying-sheep merged 76 commits into
masterfrom
neighbors-backend
Aug 31, 2023
Merged

flying-sheep merged 76 commits into
masterfrom
neighbors-backend

Conversation

@flying-sheep

@flying-sheep flying-sheep commented Jun 27, 2023 •

Copy link
Copy Markdown
Member

sklearn.neighbors.KNeighborsTransformer is a good abstraction for KNN calculations

We could follow the suggestion here, then finish this PR scikit-learn-contrib/sklearn-ann#8 (comment)

For reviewing

  • most functions were moved unchanged
  • I extensively changed
    def compute_neighbors(
    • This uncovered very grown-over-time logic:
      use_dense_distances = (metric == 'euclidean' and X.shape[0] < 8192) or not knn
      if shortcut and (use_dense_distances or X.shape[0] < 4096):

      Should we change that logic for more predictability at the expense of backwards compatibility? Especially the “euclidean” condition makes not much sense IMHO
    • Another piece of weird logic: Where to allowknn=False? It would make sense for e.g. the scipy knn transformer with algorithm='kd_tree' …
      if not knn and not (conn_method == 'gauss' and shortcut):
      # “knn=False” seems to be only intended for method “gauss”
      msg = f'`method = {method!r} only with `knn = True`.'
      raise ValueError(msg)
    • I also changed method to only mean “connectivity method”. transformer_cls alone now determines how to calculate distances

TODO

  • split of sklearn-ann part into own issue/PR
  • figure out what the _more_tags methods are
  • allow specifying algorithm and/or backend
  • revert 75c6670, move connectivities code out of backends
  • switch our stuff to KNeighborsTransformer
  • unify selection: algorithm+backend, metric, connectivity (maybe separate out connectivity)
  • figure out how to do connectivities: can mode be changed after fit? no, we just use umap connectivities as before
  • check out where we have coverage
    • is there paga specific stuff? not in the parts I changed
    • gauss: dense matrix when knn=True (“build a symmetric mask”, …) not covered, but also the logic shouldn’t have changed
    • pre-computed in umap transformer; handling of disconnected components in umap (indices == -1) replaced with our own implementation, see below
  • add tests
    • pyknndescent (we already depend on it through umap)

Maybe in another PR?

  • maybe store index in unified way?
  • for umap: use UMAP(precomputed_knn=...) instead of compute_connectivities?
  • unifiy transformer args, e.g. verbose

Implementation

The way it used to be

Our default use case was basically a thin wrapper around umap’s nearest_neighbors function, which in turn is a thin wrapper around PyNNDescent. We did some special casing around euclidean distance and small data sizes. That special casing reduced our test coverage:

  • we don’t actually test umap’s pynndescent codepath at all (just the fast precomputed path for small data)
  • umap’s precomputed code does some weird things to its knn indices array, which we don’t test for:
    grafik

The logic was:

  • if small data (<8000) and euclidean metric or knn==False, calculate pairwise_distances
    • if knn=True, then sparsify that matrix by pulling out KNN using _get_indices_distances_from_dense_matrix and converting that into a sparse one
  • if not, run umap.nearest_neighbors.
    • if even smaller data (<4000), calculate pairwise_distances like above and run umap.nearest_neighbors with metric='precomputed'. its internal logic then does the same as _get_indices_distances_from_dense_matrix
    • else run umap.nearest_neighbors directly, which simply runs PyNNDescent with n_trees and n_iters set with a heuristic.

now the logic is

  • if small data (for either definition of small), calculate pairwise_distances, sparsify on demand. (this covers both our previous optimization and the umap 'precomputed' code path)
  • else run a KNN transformer. if the old 'umap' method was chosen, pick the same parameters mentioned aboveto the PyNNDescent transformer

Fixes #2519

@codecov

codecov Bot commented Jun 27, 2023 •

Copy link
Copy Markdown

Codecov Report

Merging #2536 (0395f28) into master (0bf043c) will increase coverage by 0.15%.
The diff coverage is 76.65%.

Additional details and impacted files
@@            Coverage Diff             @@
##           master    #2536      +/-   ##
==========================================
+ Coverage   72.01%   72.17%   +0.15%     
==========================================
  Files         105      108       +3     
  Lines       11844    11894      +50     
==========================================
+ Hits         8529     8584      +55     
+ Misses       3315     3310       -5     
Files Changed Coverage Δ
scanpy/tools/_draw_graph.py 61.81% <ø> (ø)
scanpy/tools/_umap.py 73.84% <ø> (ø)
scanpy/tools/_ingest.py 64.83% <17.64%> (-3.51%) ⬇️
scanpy/_compat.py 48.00% <57.14%> (+0.63%) ⬆️
scanpy/neighbors/__init__.py 79.55% <73.75%> (+4.16%) ⬆️
scanpy/neighbors/_types.py 73.91% <73.91%> (ø)
scanpy/preprocessing/_pca.py 93.78% <83.33%> (-0.52%) ⬇️
scanpy/neighbors/_connectivity.py 86.44% <86.44%> (ø)
scanpy/neighbors/_common.py 100.00% <100.00%> (ø)
scanpy/tools/_utils.py 71.95% <100.00%> (+1.06%) ⬆️

@flying-sheep flying-sheep added this to the 1.10.0 milestone Jun 29, 2023

@ivirshup ivirshup left a comment •

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks pretty good. Just two remaining points from last review:

  • Can we add an example of using this to the documentation?
    • Could be under the "Usage" section? Maybe use a ball tree on low dim data?
  • What do you think about using being able to pass in an instance of a class, rather than the class + kwargs?
    • Just looking for a reasoning here.

And then:

  • Changelog entry

@flying-sheep

flying-sheep commented Aug 29, 2023 •

Copy link
Copy Markdown
Member Author

What “Usage” section? We have a “Usage principles” page and functions/classes can have an “Examples” section.

I’m pretty sure there was a very good reason for not passing an instance, but this was all so long ago that I forgot. I’ll see if it’s possible to maintain backwards compat while doing that!

@ivirshup

Copy link
Copy Markdown
Member

What “Usage” section? We have a “Usage principles” page and functions/classes can have an “Examples” section.

Yes, examples

I’m pretty sure there was a very good reason for not passing an instance, but this was all so long ago that I forgot. I’ll see if it’s possible to maintain backwards compat while doing that!

Maybe it was about passing in arguments to the function? But I do think it would be quite useful to pass in a class that gets .fit so you can keep a reference to the index.

@flying-sheep

Copy link
Copy Markdown
Member Author

I think it was just so convoluted that it seemed too hard to do while keeping backwards compatibility, but I managed it!

@flying-sheep
flying-sheep requested a review from ivirshup August 29, 2023 12:40
@flying-sheep

Copy link
Copy Markdown
Member Author

all done

@ivirshup ivirshup left a comment •

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

For when you're back, I believe all that needs doing is:

  • Revert change to plotting example
  • Fix doc builds

@flying-sheep

Copy link
Copy Markdown
Member Author

@ivirshup you can approve PRs where the only change missing is fixing checks.

@flying-sheep
flying-sheep requested a review from ivirshup August 31, 2023 08:52
@flying-sheep
flying-sheep enabled auto-merge (squash) August 31, 2023 13:55
@flying-sheep
flying-sheep merged commit 1fd6c46 into master Aug 31, 2023
@flying-sheep
flying-sheep deleted the neighbors-backend branch August 31, 2023 13:58
flying-sheep added a commit that referenced this pull request Sep 7, 2023
…2536)

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Development

Successfully merging this pull request may close these issues.

Add approximate nearest neighbor backend

2 participants